fix(orchestrator): retry on_agent_error recovery after a failed commit instead of giving up (#3441)
Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com> Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
@@ -0,0 +1,281 @@
|
||||
package orchestrator
|
||||
|
||||
// TestEvaluateOnlyOperationMarkingCallSitesArePinned is the AC-EO-15
|
||||
// regression guard for docs/specs/workflow-evaluate-only-operation-marking:
|
||||
// it walks the whole backend source tree (go/parser, rooted at apps/backend)
|
||||
// for engine.HandleInput composite literals that pair EvaluateOnly: true with
|
||||
// a non-empty OperationID — the exact shape this spec's contract governs.
|
||||
// Every such call site must defer the mark to its own caller and complete it
|
||||
// itself only after its own commit succeeds (AC-EO-10, AC-EO-13), whether by
|
||||
// capturing HandleResult.OperationMarkDeferred (this spec's mechanism) or by
|
||||
// setting HandleInput.DeferOperationMark (the generic caller-owned-mark flag
|
||||
// added by #3447); the closed set here is the only place that responsibility
|
||||
// currently lives. A new call site pairing the two fields is not
|
||||
// automatically wrong, but it must take on that same responsibility before
|
||||
// being added to the registered set. Mirrors the design of
|
||||
// agent_error_fire_site_pin_test.go, reusing its shared AST-walk helpers.
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"io/fs"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var registeredEvaluateOnlyOperationMarkingSites = []string{
|
||||
"internal/orchestrator/Service.dispatchKanbanAgentErrorTrigger",
|
||||
// evaluateChildrenCompleted sets DeferOperationMark: true (added by
|
||||
// #3447), not this spec's OperationMarkDeferred output flag. Its caller,
|
||||
// processOnChildrenCompleted, marks the operation itself via
|
||||
// markChildCompletionApplied after applyEngineTransitionWithMode commits
|
||||
// (transition case) or immediately (non-transition case) — the same
|
||||
// commit-then-mark discipline this spec requires, on the newer
|
||||
// caller-owned mechanism.
|
||||
"internal/orchestrator/Service.evaluateChildrenCompleted",
|
||||
}
|
||||
|
||||
func TestEvaluateOnlyOperationMarkingCallSitesArePinned(t *testing.T) {
|
||||
root, err := findAgentErrorBackendSourceRoot(".")
|
||||
if err != nil {
|
||||
t.Fatalf("locate backend source root: %v", err)
|
||||
}
|
||||
if filepath.Base(root) != "backend" {
|
||||
t.Fatalf("scan root %q is not the apps/backend directory", root)
|
||||
}
|
||||
|
||||
found, err := findEvaluateOnlyOperationMarkingSites(root)
|
||||
if err != nil {
|
||||
t.Fatalf("scan backend source for EvaluateOnly+OperationID call sites: %v", err)
|
||||
}
|
||||
|
||||
registered := make(map[string]bool, len(registeredEvaluateOnlyOperationMarkingSites))
|
||||
for _, name := range registeredEvaluateOnlyOperationMarkingSites {
|
||||
registered[name] = true
|
||||
}
|
||||
|
||||
var unregistered []string
|
||||
for name := range found {
|
||||
if !registered[name] {
|
||||
unregistered = append(unregistered, name)
|
||||
}
|
||||
}
|
||||
if len(unregistered) > 0 {
|
||||
sort.Strings(unregistered)
|
||||
t.Fatalf(
|
||||
"function(s) %v pair engine.HandleInput{EvaluateOnly: true} with a "+
|
||||
"non-empty OperationID but are not in "+
|
||||
"registeredEvaluateOnlyOperationMarkingSites. Every such call site "+
|
||||
"must capture HandleResult.OperationMarkDeferred and mark the "+
|
||||
"operation applied itself only after its own commit succeeds "+
|
||||
"(AC-EO-10, AC-EO-13, AC-EO-15) — update the registered set only "+
|
||||
"after confirming the new call site does that.",
|
||||
unregistered)
|
||||
}
|
||||
|
||||
var missing []string
|
||||
for _, name := range registeredEvaluateOnlyOperationMarkingSites {
|
||||
if !found[name] {
|
||||
missing = append(missing, name)
|
||||
}
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
sort.Strings(missing)
|
||||
t.Fatalf(
|
||||
"registeredEvaluateOnlyOperationMarkingSites lists %v but no matching "+
|
||||
"call site was found — it was likely renamed, removed, or no longer "+
|
||||
"pairs EvaluateOnly with a non-empty OperationID. Update "+
|
||||
"registeredEvaluateOnlyOperationMarkingSites to match reality.",
|
||||
missing)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFunctionPairsEvaluateOnlyWithOperationID_UnrelatedHandleInputType pins
|
||||
// the false-positive fix: a HandleInput composite literal from a package
|
||||
// other than internal/workflow/engine must not register as a call site this
|
||||
// spec governs, even though it pairs the same two field names.
|
||||
func TestFunctionPairsEvaluateOnlyWithOperationID_UnrelatedHandleInputType(t *testing.T) {
|
||||
const src = `package other
|
||||
|
||||
import unrelated "some/other/package"
|
||||
|
||||
func Call() {
|
||||
unrelated.HandleInput{EvaluateOnly: true, OperationID: "x"}
|
||||
}
|
||||
`
|
||||
fset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fset, "unrelated.go", src, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("parse fixture: %v", err)
|
||||
}
|
||||
engineAlias := engineImportAlias(file)
|
||||
isEnginePackage := file.Name != nil && file.Name.Name == "engine"
|
||||
|
||||
var fn *ast.FuncDecl
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
if decl, ok := n.(*ast.FuncDecl); ok {
|
||||
fn = decl
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
if fn == nil || fn.Body == nil {
|
||||
t.Fatalf("fixture did not parse a function body")
|
||||
}
|
||||
|
||||
if functionPairsEvaluateOnlyWithOperationID(fn.Body, engineAlias, isEnginePackage) {
|
||||
t.Fatalf("unrelated package's HandleInput{EvaluateOnly, OperationID} literal must not match")
|
||||
}
|
||||
}
|
||||
|
||||
func findEvaluateOnlyOperationMarkingSites(root string) (map[string]bool, error) {
|
||||
var paths []string
|
||||
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if d.IsDir() {
|
||||
if d.Name() == "testdata" && path != root {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
name := d.Name()
|
||||
if strings.HasSuffix(name, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
if strings.HasSuffix(name, ".go") {
|
||||
paths = append(paths, path)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
found := make(map[string]bool)
|
||||
fset := token.NewFileSet()
|
||||
for _, path := range paths {
|
||||
file, parseErr := parser.ParseFile(fset, path, nil, 0)
|
||||
if parseErr != nil {
|
||||
return nil, parseErr
|
||||
}
|
||||
relDir, relErr := filepath.Rel(root, filepath.Dir(path))
|
||||
if relErr != nil {
|
||||
return nil, relErr
|
||||
}
|
||||
engineAlias := engineImportAlias(file)
|
||||
isEnginePackage := file.Name != nil && file.Name.Name == "engine"
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
fn, ok := n.(*ast.FuncDecl)
|
||||
if !ok || fn.Body == nil {
|
||||
return true
|
||||
}
|
||||
if functionPairsEvaluateOnlyWithOperationID(fn.Body, engineAlias, isEnginePackage) {
|
||||
found[agentErrorFuncIdentity(fn, relDir)] = true
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
return found, nil
|
||||
}
|
||||
|
||||
// engineImportAlias returns the local qualifier a file uses to refer to
|
||||
// internal/workflow/engine ("" if the file does not import it), resolving a
|
||||
// renamed import instead of assuming the package name "engine".
|
||||
func engineImportAlias(file *ast.File) string {
|
||||
const enginePath = "github.com/kandev/kandev/internal/workflow/engine"
|
||||
for _, imp := range file.Imports {
|
||||
path, err := strconv.Unquote(imp.Path.Value)
|
||||
if err != nil || path != enginePath {
|
||||
continue
|
||||
}
|
||||
if imp.Name != nil {
|
||||
return imp.Name.Name
|
||||
}
|
||||
return "engine"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// functionPairsEvaluateOnlyWithOperationID reports whether body contains a
|
||||
// HandleInput composite literal resolved to internal/workflow/engine — either
|
||||
// qualified via engineAlias (external callers) or bare when the file itself
|
||||
// is package engine (isEnginePackage; spec.md's detection predicate names
|
||||
// both forms) — with both an EvaluateOnly: true key and an OperationID key
|
||||
// whose value is not the empty-string literal. A HandleInput literal from an
|
||||
// unrelated package is not a match.
|
||||
func functionPairsEvaluateOnlyWithOperationID(body *ast.BlockStmt, engineAlias string, isEnginePackage bool) bool {
|
||||
pairs := false
|
||||
ast.Inspect(body, func(n ast.Node) bool {
|
||||
lit, ok := n.(*ast.CompositeLit)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if !isHandleInputLitType(lit.Type, engineAlias, isEnginePackage) {
|
||||
return true
|
||||
}
|
||||
hasEvaluateOnlyTrue := false
|
||||
hasNonEmptyOperationID := false
|
||||
for _, elt := range lit.Elts {
|
||||
kv, ok := elt.(*ast.KeyValueExpr)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
key, ok := kv.Key.(*ast.Ident)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch key.Name {
|
||||
case "EvaluateOnly":
|
||||
if ident, ok := kv.Value.(*ast.Ident); ok && ident.Name == "true" {
|
||||
hasEvaluateOnlyTrue = true
|
||||
}
|
||||
case "OperationID":
|
||||
if !isEmptyStringLiteral(kv.Value) {
|
||||
hasNonEmptyOperationID = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if hasEvaluateOnlyTrue && hasNonEmptyOperationID {
|
||||
pairs = true
|
||||
}
|
||||
return true
|
||||
})
|
||||
return pairs
|
||||
}
|
||||
|
||||
// isHandleInputLitType reports whether t names internal/workflow/engine's
|
||||
// HandleInput type, either package-qualified (engineAlias.HandleInput, the
|
||||
// shape every external caller uses — engineAlias resolves the file's actual
|
||||
// import qualifier, empty if the file does not import the engine package at
|
||||
// all) or bare (HandleInput, accepted only when the literal's own file is
|
||||
// package engine itself). A same-named HandleInput type from an unrelated
|
||||
// package matches neither branch.
|
||||
func isHandleInputLitType(t ast.Expr, engineAlias string, isEnginePackage bool) bool {
|
||||
switch typ := t.(type) {
|
||||
case *ast.SelectorExpr:
|
||||
ident, ok := typ.X.(*ast.Ident)
|
||||
return ok && engineAlias != "" && ident.Name == engineAlias && typ.Sel.Name == "HandleInput"
|
||||
case *ast.Ident:
|
||||
return isEnginePackage && typ.Name == "HandleInput"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func isEmptyStringLiteral(expr ast.Expr) bool {
|
||||
lit, ok := expr.(*ast.BasicLit)
|
||||
if !ok || lit.Kind != token.STRING {
|
||||
return false
|
||||
}
|
||||
unquoted, err := strconv.Unquote(lit.Value)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return unquoted == ""
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime/debug"
|
||||
"sync"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
@@ -28,6 +29,7 @@ const (
|
||||
msgAgentErrorNoActions = "on_agent_error dispatch: step declares no actions"
|
||||
msgAgentErrorDispatchFailed = "on_agent_error dispatch failed"
|
||||
msgAgentErrorDispatchPanicked = "on_agent_error dispatch panicked"
|
||||
msgAgentErrorMarkFailed = "on_agent_error dispatch: failed to mark deferred operation applied"
|
||||
|
||||
// defaultAgentFailedMessage backfills an empty AgentEventData.ErrorMessage
|
||||
// (e.g. a synthetic start-failure event). Shared with the two other
|
||||
@@ -62,6 +64,51 @@ func agentErrorOperationID(sessionID, agentExecutionID string) string {
|
||||
return fmt.Sprintf("agent_error:session:%s:%s", sessionID, agentExecutionID)
|
||||
}
|
||||
|
||||
// agentErrorOperationLock is the ref-counted per-operation-id mutex entry
|
||||
// serializing dispatchKanbanAgentErrorTrigger's load -> evaluate -> commit ->
|
||||
// mark window for a given operation id. Same shape as
|
||||
// childCompletionOperationLock, but a separate type and a separate map on
|
||||
// Service: the two triggers' contention must not be coupled by sharing one
|
||||
// lock's lifetime.
|
||||
type agentErrorOperationLock struct {
|
||||
mu sync.Mutex
|
||||
refs int
|
||||
}
|
||||
|
||||
// lockAgentErrorOperation serializes concurrent dispatchKanbanAgentErrorTrigger
|
||||
// calls carrying the same operation id. The returned unlock func must be
|
||||
// deferred immediately by the caller: dispatchKanbanAgentErrorTrigger runs
|
||||
// under dispatchKanbanAgentErrorTriggerRecovered's recover(), so a
|
||||
// non-deferred unlock would leak the lock on panic.
|
||||
func (s *Service) lockAgentErrorOperation(operationID string) func() {
|
||||
s.agentErrorOperationLocksMu.Lock()
|
||||
if s.agentErrorOperationLocks == nil {
|
||||
s.agentErrorOperationLocks = make(map[string]*agentErrorOperationLock)
|
||||
}
|
||||
entry := s.agentErrorOperationLocks[operationID]
|
||||
if entry == nil {
|
||||
entry = &agentErrorOperationLock{}
|
||||
s.agentErrorOperationLocks[operationID] = entry
|
||||
}
|
||||
entry.refs++
|
||||
s.agentErrorOperationLocksMu.Unlock()
|
||||
|
||||
entry.mu.Lock()
|
||||
// Order is deliberately reversed from acquisition (map lock released
|
||||
// before entry.mu.Lock() above): no goroutine ever holds
|
||||
// agentErrorOperationLocksMu while blocked on entry.mu, so the map lock
|
||||
// taken here to decrement refs cannot deadlock against it.
|
||||
return func() {
|
||||
s.agentErrorOperationLocksMu.Lock()
|
||||
entry.refs--
|
||||
if entry.refs == 0 {
|
||||
delete(s.agentErrorOperationLocks, operationID)
|
||||
}
|
||||
s.agentErrorOperationLocksMu.Unlock()
|
||||
entry.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// agentErrorFailedAgentID resolves OnAgentErrorPayload.FailedAgentID.
|
||||
// The synthetic failure events built by handleAgentStartFailed and
|
||||
// the transient-loop exits carry no AgentProfileID, so the session fallback
|
||||
@@ -195,6 +242,13 @@ func (s *Service) resolveAgentErrorDispatchTarget(
|
||||
// session-then-task reload feeding the ownership and shape guards
|
||||
// (resolveAgentErrorDispatchTarget).
|
||||
//
|
||||
// The operation id is computed and its lock acquired before the
|
||||
// task/session/MachineState load, and held across the engine call, the
|
||||
// commit, and this dispatch's own mark: the engine consumes PreloadedState
|
||||
// verbatim, so a lock taken only around the engine call would let a blocked
|
||||
// racer wake holding state built before a winner's commit and re-evaluate
|
||||
// the step the task has already left.
|
||||
//
|
||||
// ctx is stripped of the caller's cancellation (see the call site in
|
||||
// handleRecoverableFailureLocked): this dispatch is the recovery path for an
|
||||
// already-failed session, so a canceled request context must not suppress
|
||||
@@ -214,13 +268,16 @@ func (s *Service) dispatchKanbanAgentErrorTrigger(ctx context.Context, data watc
|
||||
return
|
||||
}
|
||||
|
||||
operationID := agentErrorOperationID(data.SessionID, data.AgentExecutionID)
|
||||
unlock := s.lockAgentErrorOperation(operationID)
|
||||
defer unlock()
|
||||
|
||||
session, task, ok := s.resolveAgentErrorDispatchTarget(ctx, data)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
state := s.buildMachineState(ctx, task, session)
|
||||
operationID := agentErrorOperationID(data.SessionID, data.AgentExecutionID)
|
||||
|
||||
s.warnUnregisteredAgentErrorActions(ctx, deps, task, data.SessionID)
|
||||
|
||||
@@ -250,7 +307,16 @@ func (s *Service) dispatchKanbanAgentErrorTrigger(ctx context.Context, data watc
|
||||
}
|
||||
|
||||
if result.Transitioned {
|
||||
s.applyEngineTransition(ctx, data.TaskID, session, result, engine.TriggerOnAgentError, task.Description, true)
|
||||
applied := s.applyEngineTransition(ctx, data.TaskID, session, result, engine.TriggerOnAgentError, task.Description, true)
|
||||
if applied && result.OperationMarkDeferred {
|
||||
if markErr := deps.store.MarkOperationApplied(ctx, operationID); markErr != nil {
|
||||
s.logger.Warn(msgAgentErrorMarkFailed,
|
||||
zap.String("task_id", data.TaskID),
|
||||
zap.String("session_id", data.SessionID),
|
||||
zap.String("operation_id", operationID),
|
||||
zap.Error(markErr))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if result.ActionCount > 0 {
|
||||
|
||||
@@ -143,12 +143,16 @@ func TestDispatchKanbanAgentErrorTrigger_ReadsPostReconciliationStep(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-C7: a declined transition (target step fails to load) still reports
|
||||
// a dispatch and, because the engine already marked the operation applied
|
||||
// when it evaluated the action, is never retried on redelivery even though
|
||||
// the underlying transition never landed. ---
|
||||
// --- AC-EO-11 (workflow-evaluate-only-operation-marking): a declined
|
||||
// transition (target step fails to load) still reports a dispatch, and IS
|
||||
// retried on redelivery — the engine defers the mark for a deferred
|
||||
// transition (OperationMarkDeferred), and the caller only marks once
|
||||
// applyEngineTransition actually commits. Superseded former behavior: AC-C7
|
||||
// used to describe this operation as marked applied by the engine's
|
||||
// unconditional mark and therefore never retried, which was the defect this
|
||||
// spec's contract change fixes. ---
|
||||
|
||||
func TestDispatchKanbanAgentErrorTrigger_DeclinedTransitionIsNotRetried(t *testing.T) {
|
||||
func TestDispatchKanbanAgentErrorTrigger_DeclinedTransitionIsRetried(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "t1", "s1", "step1")
|
||||
@@ -182,6 +186,12 @@ func TestDispatchKanbanAgentErrorTrigger_DeclinedTransitionIsNotRetried(t *testi
|
||||
t.Fatalf("got %d dispatch INFO records, want 1 (dispatch still reports success)", len(got))
|
||||
}
|
||||
|
||||
operationID := agentErrorOperationID("s1", "exec-1")
|
||||
applied, err := svc.workflowStore.IsOperationApplied(ctx, operationID)
|
||||
if err != nil || applied {
|
||||
t.Fatalf("IsOperationApplied = %v, %v, want false, nil (a declined transition must leave the operation unmarked)", applied, err)
|
||||
}
|
||||
|
||||
logs.TakeAll()
|
||||
svc.handleRecoverableFailureLocked(ctx, data)
|
||||
|
||||
@@ -190,10 +200,10 @@ func TestDispatchKanbanAgentErrorTrigger_DeclinedTransitionIsNotRetried(t *testi
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step1" {
|
||||
t.Fatalf("WorkflowStepID = %q after redelivery, want step1 (still not retried)", task.WorkflowStepID)
|
||||
t.Fatalf("WorkflowStepID = %q after redelivery, want step1 (still declined the same way)", task.WorkflowStepID)
|
||||
}
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 0 {
|
||||
t.Errorf("redelivery emitted %d dispatch record(s), want 0 (idempotent)", len(got))
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 1 {
|
||||
t.Errorf("redelivery emitted %d dispatch record(s), want 1 (AC-EO-11: an unmarked declined transition retries instead of short-circuiting on Idempotent)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,865 @@
|
||||
package orchestrator
|
||||
|
||||
// Tests for docs/specs/workflow-evaluate-only-operation-marking/spec.md
|
||||
// (AC-EO-9 through AC-EO-17): dispatchKanbanAgentErrorTrigger must mark an
|
||||
// operation applied if and only if it has itself fully determined that
|
||||
// operation's transition outcome. In EvaluateOnly mode the engine defers the
|
||||
// mark for a deferred transition (HandleResult.OperationMarkDeferred), and
|
||||
// this dispatch only marks the operation once its own commit has actually
|
||||
// succeeded — never before, and never on a declined or errored commit.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/orchestrator/watcher"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite"
|
||||
"github.com/kandev/kandev/internal/workflow/engine"
|
||||
wfmodels "github.com/kandev/kandev/internal/workflow/models"
|
||||
)
|
||||
|
||||
// --- AC-EO-10: a successful transition is marked applied by the caller (not
|
||||
// the engine) after its own commit succeeds, and a redelivery of the exact
|
||||
// same failure is then idempotent. ---
|
||||
|
||||
func TestDispatchKanbanAgentErrorTrigger_SuccessfulTransitionMarksAppliedAndIsIdempotent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "t1", "s1", "step1")
|
||||
|
||||
stepGetter := newMockStepGetter()
|
||||
stepGetter.steps["step1"] = &wfmodels.WorkflowStep{
|
||||
ID: "step1", WorkflowID: "wf1", Name: "Step 1", Position: 0,
|
||||
Events: wfmodels.StepEvents{OnAgentError: []wfmodels.GenericAction{
|
||||
{Type: wfmodels.GenericActionMoveToStep, Config: map[string]interface{}{"step_id": "step2"}},
|
||||
}},
|
||||
}
|
||||
stepGetter.steps["step2"] = &wfmodels.WorkflowStep{ID: "step2", WorkflowID: "wf1", Name: "Step 2", Position: 1}
|
||||
svc, logs := newAgentErrorTestService(t, repo, stepGetter, nil)
|
||||
|
||||
data := watcher.AgentEventData{TaskID: "t1", SessionID: "s1", AgentExecutionID: "exec-1", ErrorMessage: "boom"}
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
|
||||
task, err := repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step2" {
|
||||
t.Fatalf("WorkflowStepID = %q, want step2 (the transition must have committed)", task.WorkflowStepID)
|
||||
}
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 1 {
|
||||
t.Fatalf("got %d dispatch INFO records, want 1", len(got))
|
||||
}
|
||||
|
||||
operationID := agentErrorOperationID("s1", "exec-1")
|
||||
applied, err := svc.workflowStore.IsOperationApplied(ctx, operationID)
|
||||
if err != nil || !applied {
|
||||
t.Fatalf("IsOperationApplied = %v, %v, want true, nil (AC-EO-10: the caller must mark applied itself after its own commit succeeds)", applied, err)
|
||||
}
|
||||
|
||||
logs.TakeAll()
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
|
||||
task, err = repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step2" {
|
||||
t.Fatalf("WorkflowStepID changed to %q on redelivery, want unchanged step2", task.WorkflowStepID)
|
||||
}
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 0 {
|
||||
t.Errorf("redelivery emitted %d dispatch record(s), want 0 (AC-EO-10: idempotent short-circuit)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-EO-11 case 2: a credential preflight failure declines the
|
||||
// transition, and the operation must stay unmarked so a redelivery retries. ---
|
||||
|
||||
// agentErrorListSessionsFailsAfterFirstCallRepo fails every other
|
||||
// ListTaskSessions call: each delivery makes exactly two calls in sequence
|
||||
// (otherWorkingSessionID's own guard check, then
|
||||
// findReusableSessionForProfile's credential-preflight lookup), so an
|
||||
// odd/even split lets the guard check keep succeeding on every redelivery
|
||||
// while the later preflight call keeps failing.
|
||||
type agentErrorListSessionsFailsAfterFirstCallRepo struct {
|
||||
sessionExecutorStore
|
||||
calls int32
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *agentErrorListSessionsFailsAfterFirstCallRepo) ListTaskSessions(
|
||||
ctx context.Context, taskID string,
|
||||
) ([]*models.TaskSession, error) {
|
||||
if atomic.AddInt32(&r.calls, 1)%2 == 0 {
|
||||
return nil, r.err
|
||||
}
|
||||
return r.sessionExecutorStore.ListTaskSessions(ctx, taskID)
|
||||
}
|
||||
|
||||
func TestDispatchKanbanAgentErrorTrigger_CredentialPreflightFailureLeavesOperationUnmarked(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "t1", "s1", "step1")
|
||||
|
||||
stepGetter := newMockStepGetter()
|
||||
stepGetter.steps["step1"] = &wfmodels.WorkflowStep{
|
||||
ID: "step1", WorkflowID: "wf1", Name: "Step 1", Position: 0,
|
||||
Events: wfmodels.StepEvents{OnAgentError: []wfmodels.GenericAction{
|
||||
{Type: wfmodels.GenericActionMoveToStep, Config: map[string]interface{}{"step_id": "step2"}},
|
||||
}},
|
||||
}
|
||||
// A different AgentProfileID than the current session's (empty) forces
|
||||
// preflightWorkflowStepCredentials past its early-return and into
|
||||
// findReusableSessionForProfile's ListTaskSessions call.
|
||||
stepGetter.steps["step2"] = &wfmodels.WorkflowStep{
|
||||
ID: "step2", WorkflowID: "wf1", Name: "Step 2", Position: 1, AgentProfileID: "profile-x",
|
||||
}
|
||||
svc, logs := newAgentErrorTestService(t, repo, stepGetter, nil)
|
||||
// The first ListTaskSessions call is otherWorkingSessionID's own guard
|
||||
// check (which must still succeed); only the later credential-preflight
|
||||
// call fails.
|
||||
svc.repo = &agentErrorListSessionsFailsAfterFirstCallRepo{sessionExecutorStore: svc.repo, err: errors.New("list sessions unavailable")}
|
||||
|
||||
data := watcher.AgentEventData{TaskID: "t1", SessionID: "s1", AgentExecutionID: "exec-1", ErrorMessage: "boom"}
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
|
||||
task, err := repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step1" {
|
||||
t.Fatalf("WorkflowStepID = %q, want step1 (a credential preflight failure must decline the transition)", task.WorkflowStepID)
|
||||
}
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 1 {
|
||||
t.Fatalf("got %d dispatch INFO records, want 1 (dispatch still reports success)", len(got))
|
||||
}
|
||||
|
||||
operationID := agentErrorOperationID("s1", "exec-1")
|
||||
applied, err := svc.workflowStore.IsOperationApplied(ctx, operationID)
|
||||
if err != nil || applied {
|
||||
t.Fatalf("IsOperationApplied = %v, %v, want false, nil (a declined transition must leave the operation unmarked)", applied, err)
|
||||
}
|
||||
|
||||
logs.TakeAll()
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
|
||||
task, err = repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step1" {
|
||||
t.Fatalf("WorkflowStepID = %q after redelivery, want step1 (still declined the same way)", task.WorkflowStepID)
|
||||
}
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 1 {
|
||||
t.Errorf("redelivery emitted %d dispatch record(s), want 1 (AC-EO-11: an unmarked declined transition retries)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-EO-11 case 3: a source (from-step) load failure declines the
|
||||
// transition, and the operation must stay unmarked so a redelivery retries. ---
|
||||
|
||||
func TestDispatchKanbanAgentErrorTrigger_SourceStepLoadFailureLeavesOperationUnmarked(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "t1", "s1", "step1")
|
||||
|
||||
stepGetter := newMockStepGetter()
|
||||
stepGetter.steps["step1"] = &wfmodels.WorkflowStep{
|
||||
ID: "step1", WorkflowID: "wf1", Name: "Step 1", Position: 0,
|
||||
Events: wfmodels.StepEvents{OnAgentError: []wfmodels.GenericAction{
|
||||
{Type: wfmodels.GenericActionMoveToStep, Config: map[string]interface{}{"step_id": "step2"}},
|
||||
}},
|
||||
}
|
||||
stepGetter.steps["step2"] = &wfmodels.WorkflowStep{ID: "step2", WorkflowID: "wf1", Name: "Step 2", Position: 1}
|
||||
|
||||
// The pre-engine walk's own LoadStep call (through workflowStore's
|
||||
// stepCache) populates and permanently caches step1's compiled spec on
|
||||
// its first, successful fetch. applyEngineTransitionWithCommitMode's
|
||||
// loadWorkflowStepForLifecycle("transition source") call bypasses that
|
||||
// cache and calls GetStep directly every time — so failing step1 from its
|
||||
// second raw GetStep call onward fails only that call, on every delivery.
|
||||
var mu sync.Mutex
|
||||
callsPerID := map[string]int{}
|
||||
stepGetter.getStepFunc = func(_ context.Context, id string) (*wfmodels.WorkflowStep, error) {
|
||||
mu.Lock()
|
||||
callsPerID[id]++
|
||||
n := callsPerID[id]
|
||||
mu.Unlock()
|
||||
if id == "step1" && n >= 2 {
|
||||
return nil, errors.New("source step store unavailable")
|
||||
}
|
||||
return stepGetter.steps[id], nil
|
||||
}
|
||||
|
||||
svc, logs := newAgentErrorTestService(t, repo, stepGetter, nil)
|
||||
|
||||
data := watcher.AgentEventData{TaskID: "t1", SessionID: "s1", AgentExecutionID: "exec-1", ErrorMessage: "boom"}
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
|
||||
task, err := repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step1" {
|
||||
t.Fatalf("WorkflowStepID = %q, want step1 (a from-step load failure must decline the transition)", task.WorkflowStepID)
|
||||
}
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 1 {
|
||||
t.Fatalf("got %d dispatch INFO records, want 1 (dispatch still reports success)", len(got))
|
||||
}
|
||||
|
||||
operationID := agentErrorOperationID("s1", "exec-1")
|
||||
applied, err := svc.workflowStore.IsOperationApplied(ctx, operationID)
|
||||
if err != nil || applied {
|
||||
t.Fatalf("IsOperationApplied = %v, %v, want false, nil (a declined transition must leave the operation unmarked)", applied, err)
|
||||
}
|
||||
|
||||
logs.TakeAll()
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
|
||||
task, err = repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step1" {
|
||||
t.Fatalf("WorkflowStepID = %q after redelivery, want step1 (still declined the same way)", task.WorkflowStepID)
|
||||
}
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 1 {
|
||||
t.Errorf("redelivery emitted %d dispatch record(s), want 1 (AC-EO-11: an unmarked declined transition retries)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-EO-11 case 4: a commit error declines the transition, and the
|
||||
// operation must stay unmarked so a redelivery retries. ---
|
||||
|
||||
type agentErrorCommitErrorRepo struct {
|
||||
sessionExecutorStore
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *agentErrorCommitErrorRepo) UpdateTaskWithWorkflowStepAdmission(
|
||||
_ context.Context, _ *models.Task, _ string, _ int,
|
||||
) (bool, error) {
|
||||
return false, r.err
|
||||
}
|
||||
|
||||
func TestDispatchKanbanAgentErrorTrigger_CommitErrorLeavesOperationUnmarked(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "t1", "s1", "step1")
|
||||
|
||||
stepGetter := newMockStepGetter()
|
||||
stepGetter.steps["step1"] = &wfmodels.WorkflowStep{
|
||||
ID: "step1", WorkflowID: "wf1", Name: "Step 1", Position: 0,
|
||||
Events: wfmodels.StepEvents{OnAgentError: []wfmodels.GenericAction{
|
||||
{Type: wfmodels.GenericActionMoveToStep, Config: map[string]interface{}{"step_id": "step2"}},
|
||||
}},
|
||||
}
|
||||
stepGetter.steps["step2"] = &wfmodels.WorkflowStep{ID: "step2", WorkflowID: "wf1", Name: "Step 2", Position: 1}
|
||||
svc, logs := newAgentErrorTestService(t, repo, stepGetter, nil)
|
||||
// workflowStore captured svc.repo at initWorkflowEngine time; reassigning
|
||||
// svc.repo alone would leave the commit path on the old repo, so this
|
||||
// case (unlike the credential-preflight one) must reinit after wrapping.
|
||||
svc.repo = &agentErrorCommitErrorRepo{sessionExecutorStore: svc.repo, err: errors.New("db write failed")}
|
||||
svc.initWorkflowEngine()
|
||||
|
||||
data := watcher.AgentEventData{TaskID: "t1", SessionID: "s1", AgentExecutionID: "exec-1", ErrorMessage: "boom"}
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
|
||||
task, err := repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step1" {
|
||||
t.Fatalf("WorkflowStepID = %q, want step1 (a commit error must leave the task on its source step)", task.WorkflowStepID)
|
||||
}
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 1 {
|
||||
t.Fatalf("got %d dispatch INFO records, want 1 (dispatch still reports success)", len(got))
|
||||
}
|
||||
|
||||
operationID := agentErrorOperationID("s1", "exec-1")
|
||||
applied, err := svc.workflowStore.IsOperationApplied(ctx, operationID)
|
||||
if err != nil || applied {
|
||||
t.Fatalf("IsOperationApplied = %v, %v, want false, nil (a declined transition must leave the operation unmarked)", applied, err)
|
||||
}
|
||||
|
||||
logs.TakeAll()
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
|
||||
task, err = repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step1" {
|
||||
t.Fatalf("WorkflowStepID = %q after redelivery, want step1 (still declined the same way)", task.WorkflowStepID)
|
||||
}
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 1 {
|
||||
t.Errorf("redelivery emitted %d dispatch record(s), want 1 (AC-EO-11: an unmarked declined transition retries)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-EO-14: an unmarked operation is retried at least once, so a
|
||||
// non-transition action from the same trigger (e.g. clear_decisions) must
|
||||
// replay on redelivery rather than being skipped as already-applied. ---
|
||||
|
||||
func TestDispatchKanbanAgentErrorTrigger_CommitErrorReplaysNonTransitionAction(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "t1", "s1", "step1")
|
||||
|
||||
stepGetter := newMockStepGetter()
|
||||
stepGetter.steps["step1"] = &wfmodels.WorkflowStep{
|
||||
ID: "step1", WorkflowID: "wf1", Name: "Step 1", Position: 0,
|
||||
Events: wfmodels.StepEvents{OnAgentError: []wfmodels.GenericAction{
|
||||
{Type: wfmodels.GenericActionClearDecisions},
|
||||
{Type: wfmodels.GenericActionMoveToStep, Config: map[string]interface{}{"step_id": "step2"}},
|
||||
}},
|
||||
}
|
||||
stepGetter.steps["step2"] = &wfmodels.WorkflowStep{ID: "step2", WorkflowID: "wf1", Name: "Step 2", Position: 1}
|
||||
|
||||
decisions := &spyDecisionStore{}
|
||||
svc, logs := newAgentErrorTestService(t, repo, stepGetter, func(s *Service) { s.engineDecisions = decisions })
|
||||
// workflowStore captured svc.repo at initWorkflowEngine time; reassigning
|
||||
// svc.repo alone would leave the commit path on the old repo, so this
|
||||
// case (like the sibling CommitErrorLeavesOperationUnmarked test) must
|
||||
// reinit after wrapping.
|
||||
svc.repo = &agentErrorCommitErrorRepo{sessionExecutorStore: svc.repo, err: errors.New("db write failed")}
|
||||
svc.initWorkflowEngine()
|
||||
|
||||
data := watcher.AgentEventData{TaskID: "t1", SessionID: "s1", AgentExecutionID: "exec-1", ErrorMessage: "boom"}
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
|
||||
task, err := repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step1" {
|
||||
t.Fatalf("WorkflowStepID = %q, want step1 (a commit error must leave the task on its source step)", task.WorkflowStepID)
|
||||
}
|
||||
|
||||
operationID := agentErrorOperationID("s1", "exec-1")
|
||||
applied, err := svc.workflowStore.IsOperationApplied(ctx, operationID)
|
||||
if err != nil || applied {
|
||||
t.Fatalf("IsOperationApplied = %v, %v, want false, nil (a declined transition must leave the operation unmarked)", applied, err)
|
||||
}
|
||||
if decisions.clearCalls != 1 {
|
||||
t.Fatalf("clearCalls = %d, want 1 after the first (failed-commit) delivery", decisions.clearCalls)
|
||||
}
|
||||
|
||||
logs.TakeAll()
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
|
||||
task, err = repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step1" {
|
||||
t.Fatalf("WorkflowStepID = %q after redelivery, want step1 (still declined the same way)", task.WorkflowStepID)
|
||||
}
|
||||
if decisions.clearCalls != 2 {
|
||||
t.Fatalf("clearCalls = %d, want 2 (AC-EO-14: an unmarked operation's non-transition "+
|
||||
"action must replay on redelivery, not be skipped as already-applied)", decisions.clearCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-EO-13: the operation-id lock spans load -> evaluate -> commit ->
|
||||
// mark, so two concurrent deliveries of the same failure commit exactly
|
||||
// once. ---
|
||||
|
||||
// blockingAgentErrorDecisionStore is engine.DecisionStore's clear_decisions
|
||||
// action, wired to block the first caller inside ClearStepDecisions until the
|
||||
// test releases it — used to hold a dispatch goroutine mid-evaluation (after
|
||||
// its operation-id lock is already acquired) so a second, concurrent
|
||||
// delivery of the same operation id can be proven to block on that lock
|
||||
// rather than racing ahead.
|
||||
type blockingAgentErrorDecisionStore struct {
|
||||
mu sync.Mutex
|
||||
clearCalls int
|
||||
entered chan struct{}
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (b *blockingAgentErrorDecisionStore) ListStepDecisions(context.Context, string, string) ([]engine.DecisionInfo, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (b *blockingAgentErrorDecisionStore) RecordStepDecision(context.Context, engine.DecisionInfo) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *blockingAgentErrorDecisionStore) ClearStepDecisions(context.Context, string, string) (int64, error) {
|
||||
b.mu.Lock()
|
||||
b.clearCalls++
|
||||
first := b.clearCalls == 1
|
||||
b.mu.Unlock()
|
||||
if first {
|
||||
close(b.entered)
|
||||
<-b.release
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// agentErrorCountingGetTaskSessionRepo counts GetTaskSession calls so a test
|
||||
// can prove a blocked dispatch's own state load has not yet started —
|
||||
// distinct from the lock's ref count, which only proves a goroutine is
|
||||
// registered as a waiter, not that it has been kept from reaching
|
||||
// resolveAgentErrorDispatchTarget. It embeds the concrete repository (rather
|
||||
// than the narrower sessionExecutorStore interface) so every other
|
||||
// type-asserted repo capability the commit path relies on — e.g.
|
||||
// workflowMoveAdmissionRepository in updateTransitionTask — stays promoted
|
||||
// through the wrapper; embedding the interface would silently drop those.
|
||||
type agentErrorCountingGetTaskSessionRepo struct {
|
||||
*sqliterepo.Repository
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
}
|
||||
|
||||
func (r *agentErrorCountingGetTaskSessionRepo) GetTaskSession(
|
||||
ctx context.Context, sessionID string,
|
||||
) (*models.TaskSession, error) {
|
||||
r.mu.Lock()
|
||||
r.calls++
|
||||
r.mu.Unlock()
|
||||
return r.Repository.GetTaskSession(ctx, sessionID)
|
||||
}
|
||||
|
||||
func (r *agentErrorCountingGetTaskSessionRepo) callCount() int {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.calls
|
||||
}
|
||||
|
||||
func waitForAgentErrorLockRefs(t *testing.T, svc *Service, operationID string, want int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
svc.agentErrorOperationLocksMu.Lock()
|
||||
got := 0
|
||||
if entry := svc.agentErrorOperationLocks[operationID]; entry != nil {
|
||||
got = entry.refs
|
||||
}
|
||||
svc.agentErrorOperationLocksMu.Unlock()
|
||||
if got == want {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
t.Fatalf("timed out waiting for agent-error lock refs = %d", want)
|
||||
}
|
||||
|
||||
func waitForAgentErrorTestGoroutine(t *testing.T, name string, done <-chan struct{}) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Errorf("timed out waiting for %s during cleanup", name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchKanbanAgentErrorTrigger_ConcurrentSameOperationExactlyOneCommits(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "t1", "s1", "step1")
|
||||
|
||||
stepGetter := newMockStepGetter()
|
||||
stepGetter.steps["step1"] = &wfmodels.WorkflowStep{
|
||||
ID: "step1", WorkflowID: "wf1", Name: "Step 1", Position: 0,
|
||||
Events: wfmodels.StepEvents{OnAgentError: []wfmodels.GenericAction{
|
||||
{Type: wfmodels.GenericActionClearDecisions},
|
||||
{Type: wfmodels.GenericActionMoveToStep, Config: map[string]interface{}{"step_id": "step2"}},
|
||||
}},
|
||||
}
|
||||
stepGetter.steps["step2"] = &wfmodels.WorkflowStep{ID: "step2", WorkflowID: "wf1", Name: "Step 2", Position: 1}
|
||||
|
||||
decisions := &blockingAgentErrorDecisionStore{entered: make(chan struct{}), release: make(chan struct{})}
|
||||
countingRepo := &agentErrorCountingGetTaskSessionRepo{Repository: repo}
|
||||
svc, logs := newAgentErrorTestService(t, repo, stepGetter, func(s *Service) {
|
||||
s.engineDecisions = decisions
|
||||
s.repo = countingRepo
|
||||
})
|
||||
|
||||
data := watcher.AgentEventData{TaskID: "t1", SessionID: "s1", AgentExecutionID: "exec-1", ErrorMessage: "boom"}
|
||||
operationID := agentErrorOperationID("s1", "exec-1")
|
||||
|
||||
firstDone := make(chan struct{})
|
||||
secondDone := make(chan struct{})
|
||||
secondStarted := false
|
||||
var releaseOnce sync.Once
|
||||
release := func() {
|
||||
releaseOnce.Do(func() { close(decisions.release) })
|
||||
}
|
||||
// Release every blocking path and join every goroutine that this test has
|
||||
// started, including when an assertion below calls t.Fatal.
|
||||
t.Cleanup(func() {
|
||||
release()
|
||||
waitForAgentErrorTestGoroutine(t, "first dispatch", firstDone)
|
||||
if secondStarted {
|
||||
waitForAgentErrorTestGoroutine(t, "second dispatch", secondDone)
|
||||
}
|
||||
})
|
||||
go func() {
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
close(firstDone)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-decisions.entered:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for the first dispatch to enter clear_decisions")
|
||||
}
|
||||
|
||||
// AC-EO-13: the first dispatch's own state load must have already
|
||||
// happened (it is blocked past that point, inside clear_decisions), and
|
||||
// nothing else has touched GetTaskSession yet.
|
||||
if got := countingRepo.callCount(); got != 1 {
|
||||
t.Fatalf("GetTaskSession calls = %d, want 1 before the second dispatch starts", got)
|
||||
}
|
||||
|
||||
secondStarted = true
|
||||
go func() {
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
close(secondDone)
|
||||
}()
|
||||
|
||||
waitForAgentErrorLockRefs(t, svc, operationID, 2)
|
||||
select {
|
||||
case <-secondDone:
|
||||
t.Fatal("second dispatch returned before the first released the operation-id lock")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
|
||||
// AC-EO-13: the operation-id lock must be held across the entire
|
||||
// load -> evaluate -> commit -> mark sequence, not just around the engine
|
||||
// call. If a regression narrowed the lock's span to start later, the
|
||||
// second dispatch's own GetTaskSession call could run here, ahead of the
|
||||
// first dispatch's commit — this assertion is the one that would catch
|
||||
// that narrowing, which waitForAgentErrorLockRefs alone cannot (it only
|
||||
// proves the second goroutine registered as a waiter, not that it was
|
||||
// kept from reaching resolveAgentErrorDispatchTarget).
|
||||
if got := countingRepo.callCount(); got != 1 {
|
||||
t.Fatalf("GetTaskSession calls = %d, want 1 while the first dispatch still holds the operation-id lock", got)
|
||||
}
|
||||
|
||||
release()
|
||||
|
||||
select {
|
||||
case <-firstDone:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for the first dispatch to finish")
|
||||
}
|
||||
select {
|
||||
case <-secondDone:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for the second dispatch to finish")
|
||||
}
|
||||
|
||||
task, err := repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step2" {
|
||||
t.Fatalf("WorkflowStepID = %q, want step2", task.WorkflowStepID)
|
||||
}
|
||||
|
||||
decisions.mu.Lock()
|
||||
clearCalls := decisions.clearCalls
|
||||
decisions.mu.Unlock()
|
||||
if clearCalls != 1 {
|
||||
t.Fatalf("clearCalls = %d, want 1 (the lock must serialize the two deliveries so the second sees the operation already applied)", clearCalls)
|
||||
}
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 1 {
|
||||
t.Fatalf("got %d dispatch INFO records, want 1 (the serialized second delivery must be idempotent)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// agentErrorBlockingCommitRepo blocks the first
|
||||
// UpdateTaskWithWorkflowStepAdmission call (the transition commit) until the
|
||||
// test releases it, and counts GetTaskSession calls the same way
|
||||
// agentErrorCountingGetTaskSessionRepo does. It embeds the concrete
|
||||
// *sqliterepo.Repository, not the narrower sessionExecutorStore interface,
|
||||
// for the same reason agentErrorCountingGetTaskSessionRepo does: the commit
|
||||
// path type-asserts s.repo against workflowMoveAdmissionRepository, and an
|
||||
// interface embed would silently drop that capability.
|
||||
type agentErrorBlockingCommitRepo struct {
|
||||
*sqliterepo.Repository
|
||||
|
||||
sessionMu sync.Mutex
|
||||
sessionCalls int
|
||||
|
||||
commitMu sync.Mutex
|
||||
commitCalls int
|
||||
entered chan struct{}
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (r *agentErrorBlockingCommitRepo) GetTaskSession(
|
||||
ctx context.Context, sessionID string,
|
||||
) (*models.TaskSession, error) {
|
||||
r.sessionMu.Lock()
|
||||
r.sessionCalls++
|
||||
r.sessionMu.Unlock()
|
||||
return r.Repository.GetTaskSession(ctx, sessionID)
|
||||
}
|
||||
|
||||
func (r *agentErrorBlockingCommitRepo) sessionCallCount() int {
|
||||
r.sessionMu.Lock()
|
||||
defer r.sessionMu.Unlock()
|
||||
return r.sessionCalls
|
||||
}
|
||||
|
||||
func (r *agentErrorBlockingCommitRepo) UpdateTaskWithWorkflowStepAdmission(
|
||||
ctx context.Context, task *models.Task, targetStepID string, limit int,
|
||||
) (bool, error) {
|
||||
r.commitMu.Lock()
|
||||
r.commitCalls++
|
||||
first := r.commitCalls == 1
|
||||
r.commitMu.Unlock()
|
||||
if first {
|
||||
close(r.entered)
|
||||
<-r.release
|
||||
}
|
||||
return r.Repository.UpdateTaskWithWorkflowStepAdmission(ctx, task, targetStepID, limit)
|
||||
}
|
||||
|
||||
// TestDispatchKanbanAgentErrorTrigger_ConcurrentSameOperationLockSpansThroughCommit
|
||||
// is the AC-EO-13 lock-SPAN case the sibling
|
||||
// ConcurrentSameOperationExactlyOneCommits test cannot see: that test blocks
|
||||
// the first dispatch inside engine evaluation (clear_decisions), which is
|
||||
// *before* the caller's own commit call, so it proves the lock covers
|
||||
// load -> engine-call but says nothing about whether the lock is still held
|
||||
// once HandleTrigger has returned and the caller is committing and marking.
|
||||
// This test blocks the first dispatch inside its own commit call instead — a
|
||||
// strictly later point in the sequence — and re-asserts that the second
|
||||
// dispatch's state load still has not run. A lock released as soon as
|
||||
// HandleTrigger returns (before the caller's commit and mark) would let the
|
||||
// second dispatch's GetTaskSession call run here, which this test's
|
||||
// sessionCallCount assertion below would catch.
|
||||
func TestDispatchKanbanAgentErrorTrigger_ConcurrentSameOperationLockSpansThroughCommit(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "t1", "s1", "step1")
|
||||
|
||||
stepGetter := newMockStepGetter()
|
||||
stepGetter.steps["step1"] = &wfmodels.WorkflowStep{
|
||||
ID: "step1", WorkflowID: "wf1", Name: "Step 1", Position: 0,
|
||||
Events: wfmodels.StepEvents{OnAgentError: []wfmodels.GenericAction{
|
||||
{Type: wfmodels.GenericActionMoveToStep, Config: map[string]interface{}{"step_id": "step2"}},
|
||||
}},
|
||||
}
|
||||
stepGetter.steps["step2"] = &wfmodels.WorkflowStep{ID: "step2", WorkflowID: "wf1", Name: "Step 2", Position: 1}
|
||||
|
||||
blockingRepo := &agentErrorBlockingCommitRepo{Repository: repo, entered: make(chan struct{}), release: make(chan struct{})}
|
||||
svc, logs := newAgentErrorTestService(t, repo, stepGetter, func(s *Service) { s.repo = blockingRepo })
|
||||
|
||||
data := watcher.AgentEventData{TaskID: "t1", SessionID: "s1", AgentExecutionID: "exec-1", ErrorMessage: "boom"}
|
||||
operationID := agentErrorOperationID("s1", "exec-1")
|
||||
|
||||
firstDone := make(chan struct{})
|
||||
secondDone := make(chan struct{})
|
||||
secondStarted := false
|
||||
var releaseOnce sync.Once
|
||||
release := func() {
|
||||
releaseOnce.Do(func() { close(blockingRepo.release) })
|
||||
}
|
||||
// Release every blocking path and join every goroutine that this test has
|
||||
// started, including when an assertion below calls t.Fatal.
|
||||
t.Cleanup(func() {
|
||||
release()
|
||||
waitForAgentErrorTestGoroutine(t, "first dispatch", firstDone)
|
||||
if secondStarted {
|
||||
waitForAgentErrorTestGoroutine(t, "second dispatch", secondDone)
|
||||
}
|
||||
})
|
||||
go func() {
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
close(firstDone)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-blockingRepo.entered:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for the first dispatch to enter its commit call")
|
||||
}
|
||||
|
||||
secondStarted = true
|
||||
go func() {
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
close(secondDone)
|
||||
}()
|
||||
|
||||
waitForAgentErrorLockRefs(t, svc, operationID, 2)
|
||||
select {
|
||||
case <-secondDone:
|
||||
t.Fatal("second dispatch returned before the first released the operation-id lock")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
|
||||
// AC-EO-13: the lock must still be held here — the first dispatch is
|
||||
// blocked *inside its own commit call*, strictly after HandleTrigger has
|
||||
// already returned. If the lock's span were narrowed to end as soon as
|
||||
// HandleTrigger returns (i.e. released before the commit and mark), the
|
||||
// second dispatch's own state load could run concurrently with the
|
||||
// first's pending commit, which this assertion would catch.
|
||||
if got := blockingRepo.sessionCallCount(); got != 1 {
|
||||
t.Fatalf("GetTaskSession calls = %d, want 1 while the first dispatch is still inside its own commit call", got)
|
||||
}
|
||||
operationApplied, err := svc.workflowStore.IsOperationApplied(ctx, operationID)
|
||||
if err != nil || operationApplied {
|
||||
t.Fatalf("IsOperationApplied = %v, %v, want false, nil (the first dispatch has not committed or marked yet)", operationApplied, err)
|
||||
}
|
||||
|
||||
release()
|
||||
|
||||
select {
|
||||
case <-firstDone:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for the first dispatch to finish")
|
||||
}
|
||||
select {
|
||||
case <-secondDone:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for the second dispatch to finish")
|
||||
}
|
||||
|
||||
task, err := repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step2" {
|
||||
t.Fatalf("WorkflowStepID = %q, want step2", task.WorkflowStepID)
|
||||
}
|
||||
|
||||
blockingRepo.commitMu.Lock()
|
||||
commitCalls := blockingRepo.commitCalls
|
||||
blockingRepo.commitMu.Unlock()
|
||||
if commitCalls != 1 {
|
||||
t.Fatalf("commit calls = %d, want 1 (the lock held through commit must serialize the second delivery into an idempotent no-op)", commitCalls)
|
||||
}
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 1 {
|
||||
t.Fatalf("got %d dispatch INFO records, want 1 (the serialized second delivery must be idempotent)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// TestLockAgentErrorOperationKeepsEntryUntilWaitersExit is the direct
|
||||
// ref-counting unit test for the lock helper itself, mirroring
|
||||
// TestLockChildCompletionOperationKeepsEntryUntilWaitersExit.
|
||||
func TestLockAgentErrorOperationKeepsEntryUntilWaitersExit(t *testing.T) {
|
||||
svc := &Service{}
|
||||
unlockFirst := svc.lockAgentErrorOperation("op")
|
||||
var unlockFirstOnce sync.Once
|
||||
releaseFirst := func() { unlockFirstOnce.Do(unlockFirst) }
|
||||
|
||||
secondAcquired := make(chan struct{})
|
||||
releaseSecond := make(chan struct{})
|
||||
var releaseSecondOnce sync.Once
|
||||
releaseSecondLock := func() { releaseSecondOnce.Do(func() { close(releaseSecond) }) }
|
||||
done := make(chan struct{})
|
||||
// Release both lock holders and join the waiter even when an assertion
|
||||
// below calls t.Fatal before the normal release sequence.
|
||||
t.Cleanup(func() {
|
||||
releaseFirst()
|
||||
releaseSecondLock()
|
||||
waitForAgentErrorTestGoroutine(t, "second lock holder", done)
|
||||
})
|
||||
go func() {
|
||||
unlockSecond := svc.lockAgentErrorOperation("op")
|
||||
close(secondAcquired)
|
||||
<-releaseSecond
|
||||
unlockSecond()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
waitForAgentErrorLockRefs(t, svc, "op", 2)
|
||||
releaseFirst()
|
||||
select {
|
||||
case <-secondAcquired:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for second lock holder")
|
||||
}
|
||||
waitForAgentErrorLockRefs(t, svc, "op", 1)
|
||||
releaseSecondLock()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for second lock release")
|
||||
}
|
||||
|
||||
svc.agentErrorOperationLocksMu.Lock()
|
||||
_, exists := svc.agentErrorOperationLocks["op"]
|
||||
svc.agentErrorOperationLocksMu.Unlock()
|
||||
if exists {
|
||||
t.Fatal("expected lock entry to be deleted after all holders exit")
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-EO-17: a marker lost after a successful commit (the process-local
|
||||
// map is not durable across a restart) must not replay the stale
|
||||
// transition — a redelivery evaluates the task's current (target) step. ---
|
||||
|
||||
func TestDispatchKanbanAgentErrorTrigger_MarkerLostAfterCommitRedeliveryEvaluatesFreshState(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "t1", "s1", "step1")
|
||||
|
||||
stepGetter := newMockStepGetter()
|
||||
stepGetter.steps["step1"] = &wfmodels.WorkflowStep{
|
||||
ID: "step1", WorkflowID: "wf1", Name: "Step 1", Position: 0,
|
||||
Events: wfmodels.StepEvents{OnAgentError: []wfmodels.GenericAction{
|
||||
{Type: wfmodels.GenericActionMoveToStep, Config: map[string]interface{}{"step_id": "step2"}},
|
||||
}},
|
||||
}
|
||||
stepGetter.steps["step2"] = &wfmodels.WorkflowStep{
|
||||
ID: "step2", WorkflowID: "wf1", Name: "Step 2", Position: 1,
|
||||
Events: wfmodels.StepEvents{OnAgentError: []wfmodels.GenericAction{{Type: wfmodels.GenericActionClearDecisions}}},
|
||||
}
|
||||
decisions := &spyDecisionStore{}
|
||||
svc, logs := newAgentErrorTestService(t, repo, stepGetter, func(s *Service) { s.engineDecisions = decisions })
|
||||
|
||||
data := watcher.AgentEventData{TaskID: "t1", SessionID: "s1", AgentExecutionID: "exec-1", ErrorMessage: "boom"}
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
|
||||
task, err := repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step2" {
|
||||
t.Fatalf("WorkflowStepID = %q, want step2 after the first delivery's transition", task.WorkflowStepID)
|
||||
}
|
||||
|
||||
operationID := agentErrorOperationID("s1", "exec-1")
|
||||
applied, err := svc.workflowStore.IsOperationApplied(ctx, operationID)
|
||||
if err != nil || !applied {
|
||||
t.Fatalf("IsOperationApplied = %v, %v, want true, nil after a successful commit", applied, err)
|
||||
}
|
||||
|
||||
// Simulate the marker being lost (a process restart clears the
|
||||
// process-local operation ledger) without touching persisted task/step
|
||||
// state.
|
||||
svc.workflowStore.ledger.applied.Delete(operationID)
|
||||
logs.TakeAll()
|
||||
|
||||
svc.dispatchKanbanAgentErrorTrigger(ctx, data)
|
||||
|
||||
task, err = repo.GetTask(ctx, "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("reload task: %v", err)
|
||||
}
|
||||
if task.WorkflowStepID != "step2" {
|
||||
t.Fatalf("WorkflowStepID = %q after redelivery, want step2 (unchanged; step2's own action must fire, not step1's stale transition)", task.WorkflowStepID)
|
||||
}
|
||||
if decisions.clearCalls != 1 {
|
||||
t.Fatalf("clearCalls = %d, want 1 (redelivery must evaluate step2's declared action, proving it re-read current state rather than replaying step1's stale transition)", decisions.clearCalls)
|
||||
}
|
||||
if got := filterLogs(logs, msgAgentErrorDispatched); len(got) != 1 {
|
||||
t.Fatalf("got %d dispatch INFO records on redelivery, want 1", len(got))
|
||||
}
|
||||
|
||||
reapplied, err := svc.workflowStore.IsOperationApplied(ctx, operationID)
|
||||
if err != nil || !reapplied {
|
||||
t.Fatalf("IsOperationApplied after redelivery = %v, %v, want true, nil (a further delivery must be idempotent again)", reapplied, err)
|
||||
}
|
||||
}
|
||||
@@ -109,6 +109,85 @@ func TestProcessOnChildrenCompleted_TransitionsParentWhenAllActiveChildrenTermin
|
||||
}
|
||||
}
|
||||
|
||||
// TestProcessOnChildrenCompleted_StillIdempotentOnRedelivery is the AC-EO-16
|
||||
// pin for docs/specs/workflow-evaluate-only-operation-marking: this trigger
|
||||
// passes its operation ID with DeferOperationMark and keeps the outer
|
||||
// commit-to-mark bracket (childCompletionAlreadyApplied /
|
||||
// markChildCompletionApplied), unchanged by that spec's runtime contract.
|
||||
//
|
||||
// step_done also declares an OnChildrenCompleted action (unlike the sibling
|
||||
// TransitionsParentWhenAllActiveChildrenTerminal test's terminal step_done,
|
||||
// which has none) so the marker check is load-bearing: without it, the
|
||||
// unchanged, still-all-terminal child rows would let a redelivery re-evaluate
|
||||
// step_done's own trigger and advance the parent a second time, to
|
||||
// step_final. A mutation that deletes childCompletionAlreadyApplied's guard
|
||||
// makes this test observe exactly that second move.
|
||||
func TestProcessOnChildrenCompleted_StillIdempotentOnRedelivery(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "parent", "parent-session", "step_wait")
|
||||
|
||||
stepGetter := newMockStepGetter()
|
||||
stepGetter.steps["step_wait"] = &wfmodels.WorkflowStep{
|
||||
ID: "step_wait", WorkflowID: "wf1", Name: "Wait for Subtasks", Position: 0,
|
||||
Events: wfmodels.StepEvents{
|
||||
OnChildrenCompleted: []wfmodels.GenericAction{{Type: wfmodels.GenericActionMoveToNext}},
|
||||
},
|
||||
}
|
||||
stepGetter.steps["step_done"] = &wfmodels.WorkflowStep{
|
||||
ID: "step_done", WorkflowID: "wf1", Name: "Done", Position: 1,
|
||||
Events: wfmodels.StepEvents{
|
||||
OnChildrenCompleted: []wfmodels.GenericAction{{Type: wfmodels.GenericActionMoveToNext}},
|
||||
},
|
||||
}
|
||||
stepGetter.steps["step_final"] = &wfmodels.WorkflowStep{ID: "step_final", WorkflowID: "wf1", Name: "Final", Position: 2}
|
||||
|
||||
agentMgr := &mockAgentManager{repoForExecutionLookup: repo}
|
||||
svc := createEngineService(t, repo, stepGetter, agentMgr)
|
||||
seedMockTaskState(svc.taskRepo.(*mockTaskRepo), "parent", v1.TaskStateInProgress)
|
||||
onEnterDone := make(chan struct{}, 1)
|
||||
svc.onProcessOnEnterComplete = func() {
|
||||
select {
|
||||
case onEnterDone <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
requireCreateTask(t, repo, &models.Task{
|
||||
ID: "child-complete", WorkflowID: "wf1", Title: "Complete child",
|
||||
State: v1.TaskStateCompleted, ParentID: "parent", CreatedAt: now, UpdatedAt: now,
|
||||
})
|
||||
|
||||
if transitioned := svc.processOnChildrenCompleted(ctx, "parent"); !transitioned {
|
||||
t.Fatalf("expected the first delivery to transition the parent")
|
||||
}
|
||||
waitForChildrenCompletedOnEnter(t, onEnterDone)
|
||||
|
||||
rows, err := repo.ListChildCompletionRows(ctx, "parent")
|
||||
if err != nil {
|
||||
t.Fatalf("list child completion rows: %v", err)
|
||||
}
|
||||
operationID := childCompletionOperationID("parent", rows)
|
||||
applied, err := svc.workflowStore.IsOperationApplied(ctx, operationID)
|
||||
if err != nil || !applied {
|
||||
t.Fatalf("IsOperationApplied = %v, %v, want true, nil (on_children_completed defers the engine "+
|
||||
"mark and its outer handler marks after commit)", applied, err)
|
||||
}
|
||||
|
||||
if transitioned := svc.processOnChildrenCompleted(ctx, "parent"); transitioned {
|
||||
t.Fatalf("expected redelivery of the same completion to be idempotent (no second transition)")
|
||||
}
|
||||
parent, err := repo.GetTask(ctx, "parent")
|
||||
if err != nil {
|
||||
t.Fatalf("load parent after redelivery: %v", err)
|
||||
}
|
||||
if parent.WorkflowStepID != "step_done" {
|
||||
t.Fatalf("WorkflowStepID = %q after redelivery, want step_done unchanged (a broken guard would "+
|
||||
"re-fire step_done's own OnChildrenCompleted action and advance to step_final)", parent.WorkflowStepID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessOnChildrenCompleted_UsesCommittedTaskState(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
|
||||
@@ -797,6 +797,16 @@ type Service struct {
|
||||
// childCompletionLocks serializes duplicate on_children_completed deliveries.
|
||||
childCompletionLocksMu sync.Mutex
|
||||
childCompletionLocks map[string]*childCompletionOperationLock
|
||||
// agentErrorOperationLocks serializes concurrent on_agent_error dispatches
|
||||
// that carry the same operation id — the load -> evaluate -> commit ->
|
||||
// mark window, held from before the task/session/MachineState load so a
|
||||
// blocked racer always reloads state rather than evaluating a
|
||||
// PreloadedState built before another racer's commit. Deliberately a
|
||||
// separate map from childCompletionLocks: coupling two unrelated
|
||||
// triggers' contention through one map would let a change to either
|
||||
// lock's lifetime silently affect the other.
|
||||
agentErrorOperationLocksMu sync.Mutex
|
||||
agentErrorOperationLocks map[string]*agentErrorOperationLock
|
||||
// onProcessOnEnterComplete is a package-test hook for synchronizing with
|
||||
// applyEngineTransition's asynchronous processOnEnter goroutine.
|
||||
onProcessOnEnterComplete func()
|
||||
|
||||
@@ -128,6 +128,13 @@ type HandleResult struct {
|
||||
// abandoning is an expected outcome of concurrent re-evaluation, not a
|
||||
// failure.
|
||||
TransitionAbandoned bool
|
||||
|
||||
// OperationMarkDeferred is true when the engine deliberately skipped
|
||||
// marking HandleInput.OperationID applied because EvaluateOnly deferred
|
||||
// this transition's commit to the caller. The caller then owns the
|
||||
// marker and must invoke TransitionStore.MarkOperationApplied itself,
|
||||
// once and only once its own commit succeeds.
|
||||
OperationMarkDeferred bool
|
||||
}
|
||||
|
||||
// Option configures an Engine at construction time. Use With* helpers below.
|
||||
@@ -280,6 +287,15 @@ func (e *Engine) handleTrigger(ctx context.Context, in HandleInput, filter func(
|
||||
return HandleResult{}, err
|
||||
}
|
||||
|
||||
// A deferred transition is work this call evaluated but did not commit
|
||||
// (processActions skips ApplyTransition under EvaluateOnly). Marking the
|
||||
// operation applied here would claim a commit the caller still owes, so
|
||||
// ownership of the marker passes to the caller instead.
|
||||
if in.EvaluateOnly && result.Transitioned {
|
||||
result.OperationMarkDeferred = in.OperationID != ""
|
||||
return result, nil
|
||||
}
|
||||
|
||||
return result, e.markOperationAppliedForInput(ctx, in)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
package engine
|
||||
|
||||
// Tests for docs/specs/workflow-evaluate-only-operation-marking/spec.md
|
||||
// (AC-EO-1 through AC-EO-8): split out of engine_test.go to keep that file
|
||||
// under the 800-effective-line limit (apps/backend/AGENTS.md). Shares
|
||||
// fakeStore/fakeCallback/erroringCallback/MapRegistry from engine_test.go.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// --- AC-EO-1/AC-EO-4: EvaluateOnly with a deferred transition and a
|
||||
// non-empty OperationID must not mark the operation applied, and must report
|
||||
// OperationMarkDeferred so the caller knows it now owns the marker. ---
|
||||
|
||||
func TestHandleTrigger_EvaluateOnlyDeferredTransitionSkipsMarkAndReportsDeferred(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{
|
||||
"step-1": {
|
||||
ID: "step-1",
|
||||
Position: 1,
|
||||
Events: map[Trigger][]Action{
|
||||
TriggerOnTurnComplete: {{Kind: ActionMoveToNext}},
|
||||
},
|
||||
},
|
||||
},
|
||||
nextSteps: map[int]StepSpec{1: {ID: "step-2", Position: 2}},
|
||||
applied: map[string]bool{},
|
||||
}
|
||||
|
||||
eng := New(store, MapRegistry{})
|
||||
result, err := eng.HandleTrigger(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnTurnComplete,
|
||||
EvaluateOnly: true, OperationID: "op-1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !result.Transitioned {
|
||||
t.Fatalf("expected transition")
|
||||
}
|
||||
if !result.OperationMarkDeferred {
|
||||
t.Fatalf("expected OperationMarkDeferred true")
|
||||
}
|
||||
if store.applied["op-1"] {
|
||||
t.Fatalf("expected op-1 not marked applied")
|
||||
}
|
||||
for _, call := range store.callLog {
|
||||
if call == "MarkOperationApplied" {
|
||||
t.Fatalf("MarkOperationApplied must not be invoked, callLog: %v", store.callLog)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-EO-2: EvaluateOnly with no deferred transition still marks, whether
|
||||
// or not a non-transition callback produced a data patch. A patch does not
|
||||
// change marker ownership — it is dropped on this path (spec.md § The
|
||||
// contract), which this test deliberately does not assert either way. ---
|
||||
|
||||
func TestHandleTrigger_EvaluateOnlyNoTransitionStillMarks(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
patch map[string]any
|
||||
}{
|
||||
{name: "no data patch"},
|
||||
{name: "with data patch", patch: map[string]any{"k": "v"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{
|
||||
"step-1": {
|
||||
ID: "step-1",
|
||||
Events: map[Trigger][]Action{
|
||||
TriggerOnEnter: {{Kind: ActionSetWorkflowData}},
|
||||
},
|
||||
},
|
||||
},
|
||||
applied: map[string]bool{},
|
||||
}
|
||||
registry := MapRegistry{ActionSetWorkflowData: &fakeCallback{result: ActionResult{DataPatch: tc.patch}}}
|
||||
|
||||
eng := New(store, registry)
|
||||
result, err := eng.HandleTrigger(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnEnter,
|
||||
EvaluateOnly: true, OperationID: "op-1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if result.Transitioned {
|
||||
t.Fatalf("did not expect transition")
|
||||
}
|
||||
if !store.applied["op-1"] {
|
||||
t.Fatalf("expected op-1 marked applied")
|
||||
}
|
||||
if result.OperationMarkDeferred {
|
||||
t.Fatalf("expected OperationMarkDeferred false on a no-transition path")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-EO-3: EvaluateOnly false marks after the commit, transition or not.
|
||||
// ---
|
||||
|
||||
func TestHandleTrigger_NotEvaluateOnlyMarksAfterCommit(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{
|
||||
"step-1": {
|
||||
ID: "step-1",
|
||||
Position: 1,
|
||||
Events: map[Trigger][]Action{
|
||||
TriggerOnTurnComplete: {{Kind: ActionMoveToNext}},
|
||||
},
|
||||
},
|
||||
},
|
||||
nextSteps: map[int]StepSpec{1: {ID: "step-2", Position: 2}},
|
||||
applied: map[string]bool{},
|
||||
}
|
||||
|
||||
eng := New(store, MapRegistry{})
|
||||
result, err := eng.HandleTrigger(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnTurnComplete, OperationID: "op-1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !result.Transitioned {
|
||||
t.Fatalf("expected transition")
|
||||
}
|
||||
if !store.applied["op-1"] {
|
||||
t.Fatalf("expected op-1 marked applied")
|
||||
}
|
||||
if result.OperationMarkDeferred {
|
||||
t.Fatalf("expected OperationMarkDeferred false when EvaluateOnly is false")
|
||||
}
|
||||
wantLog := []string{"IsOperationApplied", "ApplyTransition", "MarkOperationApplied"}
|
||||
if len(store.callLog) != len(wantLog) {
|
||||
t.Fatalf("callLog = %v, want %v", store.callLog, wantLog)
|
||||
}
|
||||
for i, call := range wantLog {
|
||||
if store.callLog[i] != call {
|
||||
t.Fatalf("callLog[%d] = %q, want %q (commit must precede mark): %v", i, store.callLog[i], call, store.callLog)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-EO-4: OperationMarkDeferred is false on every return path other
|
||||
// than the AC-EO-1 deferred-transition-with-a-non-empty-OperationID case. ---
|
||||
|
||||
func TestHandleTrigger_OperationMarkDeferredFalseCases(t *testing.T) {
|
||||
t.Run("idempotent short-circuit", func(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{
|
||||
"step-1": {ID: "step-1", Position: 1, Events: map[Trigger][]Action{
|
||||
TriggerOnTurnComplete: {{Kind: ActionMoveToNext}},
|
||||
}},
|
||||
},
|
||||
nextSteps: map[int]StepSpec{1: {ID: "step-2", Position: 2}},
|
||||
applied: map[string]bool{"op-1": true},
|
||||
}
|
||||
eng := New(store, MapRegistry{})
|
||||
result, err := eng.HandleTrigger(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnTurnComplete,
|
||||
EvaluateOnly: true, OperationID: "op-1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !result.Idempotent {
|
||||
t.Fatalf("expected idempotent short-circuit")
|
||||
}
|
||||
if result.OperationMarkDeferred {
|
||||
t.Fatalf("expected OperationMarkDeferred false on the idempotent short-circuit")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("step declares no actions for the trigger", func(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{
|
||||
"step-1": {ID: "step-1", Position: 1},
|
||||
},
|
||||
applied: map[string]bool{},
|
||||
}
|
||||
eng := New(store, MapRegistry{})
|
||||
result, err := eng.HandleTrigger(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnTurnComplete,
|
||||
EvaluateOnly: true, OperationID: "op-1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if result.OperationMarkDeferred {
|
||||
t.Fatalf("expected OperationMarkDeferred false when the step declares no actions")
|
||||
}
|
||||
if !store.applied["op-1"] {
|
||||
t.Fatalf("expected op-1 marked applied (nothing was deferred)")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("EvaluateOnly false", func(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{
|
||||
"step-1": {ID: "step-1", Position: 1, Events: map[Trigger][]Action{
|
||||
TriggerOnTurnComplete: {{Kind: ActionMoveToNext}},
|
||||
}},
|
||||
},
|
||||
nextSteps: map[int]StepSpec{1: {ID: "step-2", Position: 2}},
|
||||
applied: map[string]bool{},
|
||||
}
|
||||
eng := New(store, MapRegistry{})
|
||||
result, err := eng.HandleTrigger(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnTurnComplete, OperationID: "op-1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if result.OperationMarkDeferred {
|
||||
t.Fatalf("expected OperationMarkDeferred false when EvaluateOnly is false")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("deferred transition with empty OperationID", func(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{
|
||||
"step-1": {ID: "step-1", Position: 1, Events: map[Trigger][]Action{
|
||||
TriggerOnTurnComplete: {{Kind: ActionMoveToNext}},
|
||||
}},
|
||||
},
|
||||
nextSteps: map[int]StepSpec{1: {ID: "step-2", Position: 2}},
|
||||
applied: map[string]bool{},
|
||||
}
|
||||
eng := New(store, MapRegistry{})
|
||||
result, err := eng.HandleTrigger(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnTurnComplete,
|
||||
EvaluateOnly: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !result.Transitioned {
|
||||
t.Fatalf("expected transition")
|
||||
}
|
||||
if result.OperationMarkDeferred {
|
||||
t.Fatalf("expected OperationMarkDeferred false when OperationID is empty")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("processActions error", func(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{
|
||||
"step-1": {ID: "step-1", Events: map[Trigger][]Action{
|
||||
TriggerOnEnter: {{Kind: ActionSetWorkflowData}},
|
||||
}},
|
||||
},
|
||||
applied: map[string]bool{},
|
||||
}
|
||||
registry := MapRegistry{ActionSetWorkflowData: &erroringCallback{}}
|
||||
eng := New(store, registry)
|
||||
result, err := eng.HandleTrigger(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnEnter,
|
||||
EvaluateOnly: true, OperationID: "op-1",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("expected error")
|
||||
}
|
||||
if result.Transitioned || result.OperationMarkDeferred || result.ActionCount != 0 {
|
||||
t.Fatalf("expected zero HandleResult, got %+v", result)
|
||||
}
|
||||
if store.applied["op-1"] {
|
||||
t.Fatalf("expected op-1 not marked applied")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// --- AC-EO-5: a processActions error never marks the operation, regardless
|
||||
// of EvaluateOnly. ---
|
||||
|
||||
func TestHandleTrigger_ProcessActionsErrorNeverMarks(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{
|
||||
"step-1": {ID: "step-1", Events: map[Trigger][]Action{
|
||||
TriggerOnEnter: {{Kind: ActionSetWorkflowData}},
|
||||
}},
|
||||
},
|
||||
applied: map[string]bool{},
|
||||
}
|
||||
registry := MapRegistry{ActionSetWorkflowData: &erroringCallback{}}
|
||||
eng := New(store, registry)
|
||||
|
||||
_, err := eng.HandleTrigger(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnEnter, OperationID: "op-1",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("expected error")
|
||||
}
|
||||
if store.applied["op-1"] {
|
||||
t.Fatalf("expected op-1 not marked applied")
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-EO-6: a step declaring no actions for the trigger marks regardless
|
||||
// of EvaluateOnly, because nothing was deferred. ---
|
||||
|
||||
func TestHandleTrigger_NoDeclaredActionsMarksEvenWhenEvaluateOnly(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{"step-1": {ID: "step-1"}},
|
||||
applied: map[string]bool{},
|
||||
}
|
||||
eng := New(store, MapRegistry{})
|
||||
|
||||
result, err := eng.HandleTrigger(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnTurnComplete,
|
||||
EvaluateOnly: true, OperationID: "op-1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !store.applied["op-1"] {
|
||||
t.Fatalf("expected op-1 marked applied")
|
||||
}
|
||||
if result.OperationMarkDeferred {
|
||||
t.Fatalf("expected OperationMarkDeferred false")
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-EO-7: an empty OperationID never touches the store's idempotency
|
||||
// calls at all, deferred transition or not. ---
|
||||
|
||||
func TestHandleTrigger_EmptyOperationIDSkipsStoreCallsEvenWhenDeferred(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{
|
||||
"step-1": {ID: "step-1", Position: 1, Events: map[Trigger][]Action{
|
||||
TriggerOnTurnComplete: {{Kind: ActionMoveToNext}},
|
||||
}},
|
||||
},
|
||||
nextSteps: map[int]StepSpec{1: {ID: "step-2", Position: 2}},
|
||||
applied: map[string]bool{},
|
||||
}
|
||||
eng := New(store, MapRegistry{})
|
||||
|
||||
result, err := eng.HandleTrigger(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnTurnComplete, EvaluateOnly: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !result.Transitioned {
|
||||
t.Fatalf("expected transition")
|
||||
}
|
||||
if len(store.callLog) != 0 {
|
||||
t.Fatalf("expected no store calls at all, callLog: %v", store.callLog)
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC-EO-8: HandleTriggerSessionShapedOnly follows the same rules — no
|
||||
// deferred-transition case is constructible through it, so this pins the
|
||||
// AC-EO-2/AC-EO-4-false/AC-EO-7 behaviors plus the structural precondition
|
||||
// (sessionShapedActionKinds admits no transition kind) that makes AC-EO-1
|
||||
// vacuous here. ---
|
||||
|
||||
func TestHandleTriggerSessionShapedOnly_FollowsMarkerRulesAndFilterIsDisjointFromTransitions(t *testing.T) {
|
||||
for kind := range sessionShapedActionKinds {
|
||||
if isTransitionAction(kind) {
|
||||
t.Fatalf("sessionShapedActionKinds admits transition kind %q — AC-EO-1 would become reachable through HandleTriggerSessionShapedOnly and double-dispatch step entry (AC-OFFICE-STEP-ENTRY-001)", kind)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("EvaluateOnly with only session-shaped actions still marks (AC-EO-2)", func(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{
|
||||
"step-1": {ID: "step-1", Events: map[Trigger][]Action{
|
||||
TriggerOnEnter: {{Kind: ActionAutoStartAgent}},
|
||||
}},
|
||||
},
|
||||
applied: map[string]bool{},
|
||||
}
|
||||
eng := New(store, MapRegistry{ActionAutoStartAgent: &fakeCallback{}})
|
||||
result, err := eng.HandleTriggerSessionShapedOnly(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnEnter,
|
||||
EvaluateOnly: true, OperationID: "op-1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !store.applied["op-1"] {
|
||||
t.Fatalf("expected op-1 marked applied")
|
||||
}
|
||||
if result.OperationMarkDeferred {
|
||||
t.Fatalf("expected OperationMarkDeferred false (AC-EO-4)")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty OperationID skips store calls (AC-EO-7)", func(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
state: MachineState{TaskID: "t1", SessionID: "s1", WorkflowID: "wf1", CurrentStepID: "step-1"},
|
||||
stepsByID: map[string]StepSpec{
|
||||
"step-1": {ID: "step-1", Events: map[Trigger][]Action{
|
||||
TriggerOnEnter: {{Kind: ActionAutoStartAgent}},
|
||||
}},
|
||||
},
|
||||
applied: map[string]bool{},
|
||||
}
|
||||
eng := New(store, MapRegistry{ActionAutoStartAgent: &fakeCallback{}})
|
||||
if _, err := eng.HandleTriggerSessionShapedOnly(context.Background(), HandleInput{
|
||||
TaskID: "t1", SessionID: "s1", Trigger: TriggerOnEnter, EvaluateOnly: true,
|
||||
}); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(store.callLog) != 0 {
|
||||
t.Fatalf("expected no store calls at all, callLog: %v", store.callLog)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -17,6 +17,10 @@ type fakeStore struct {
|
||||
applied map[string]bool
|
||||
transitionFrom string
|
||||
transitionTo string
|
||||
// callLog records ApplyTransition and MarkOperationApplied invocations in
|
||||
// order, so tests can assert both whether a call happened and, for
|
||||
// AC-EO-3, that the commit precedes the mark.
|
||||
callLog []string
|
||||
}
|
||||
|
||||
func (s *fakeStore) LoadState(_ context.Context, _, _ string) (MachineState, error) {
|
||||
@@ -50,6 +54,7 @@ func (s *fakeStore) LoadPreviousStep(_ context.Context, _ string, currentPositio
|
||||
func (s *fakeStore) ApplyTransition(_ context.Context, _, _, fromStepID, toStepID string, _ Trigger) error {
|
||||
s.transitionFrom = fromStepID
|
||||
s.transitionTo = toStepID
|
||||
s.callLog = append(s.callLog, "ApplyTransition")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -71,6 +76,10 @@ func (s *fakeStore) PersistData(_ context.Context, _ string, data map[string]any
|
||||
}
|
||||
|
||||
func (s *fakeStore) IsOperationApplied(_ context.Context, operationID string) (bool, error) {
|
||||
// Logged unconditionally (even for an empty operationID) so the AC-EO-7
|
||||
// "no store calls at all" tests actually prove this method was never
|
||||
// reached, rather than passing vacuously because this method never logs.
|
||||
s.callLog = append(s.callLog, "IsOperationApplied")
|
||||
if operationID == "" {
|
||||
return false, nil
|
||||
}
|
||||
@@ -82,9 +91,18 @@ func (s *fakeStore) MarkOperationApplied(_ context.Context, operationID string)
|
||||
return nil
|
||||
}
|
||||
s.applied[operationID] = true
|
||||
s.callLog = append(s.callLog, "MarkOperationApplied")
|
||||
return nil
|
||||
}
|
||||
|
||||
// erroringCallback always fails, for AC-EO-5: a processActions error must
|
||||
// short-circuit HandleTrigger before the mark is ever attempted.
|
||||
type erroringCallback struct{}
|
||||
|
||||
func (c *erroringCallback) Execute(_ context.Context, _ ActionInput) (ActionResult, error) {
|
||||
return ActionResult{}, errors.New("callback failed")
|
||||
}
|
||||
|
||||
type fakeCallback struct {
|
||||
result ActionResult
|
||||
executed bool
|
||||
|
||||
@@ -141,6 +141,12 @@ func TestReevaluateGuardedTransitions_IdempotentOnRepeatedDecisionID(t *testing.
|
||||
if store.casCalls != 1 {
|
||||
t.Fatalf("expected 1 CAS call after first reevaluate, got %d", store.casCalls)
|
||||
}
|
||||
// AC-EO-9: the operation id is marked applied once this call has itself
|
||||
// determined and committed the outcome, unlike EvaluateOnly's deferred
|
||||
// mark — this is what makes the second call idempotent below.
|
||||
if !store.applied["decision:task-1:review:decision-1"] {
|
||||
t.Fatalf("expected the decision operation id marked applied after the committing reevaluate")
|
||||
}
|
||||
|
||||
second, err := eng.reevaluateGuardedTransitions(context.Background(), "task-1", "sess-1", "review", "decision-1")
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,475 @@
|
||||
---
|
||||
status: draft
|
||||
created: 2026-09-05
|
||||
updated: 2026-09-05
|
||||
owner: Kandev
|
||||
---
|
||||
|
||||
# `EvaluateOnly` operation marking in the workflow engine
|
||||
|
||||
Decisions:
|
||||
|
||||
- [ADR-0004 task-model-unification](../../decisions/0004-task-model-unification.md) — establishes
|
||||
`internal/workflow/engine` as the shared coordinator every trigger routes through, which is why this
|
||||
is a contract change, not a call-site patch.
|
||||
|
||||
Origin:
|
||||
|
||||
- Review comment 3921830599 on [PR #3315](https://github.com/kdlbs/kandev/pull/3315)
|
||||
(thread `PRRT_kwDOQ2-eWs6ezhf9`). The defect predates that PR; #3315 added the fourth
|
||||
`EvaluateOnly` call site and the reviewer noticed the shared gap from it.
|
||||
|
||||
Related spec (same subsystem, adjacent defect class):
|
||||
|
||||
- [`docs/specs/workflow-on-agent-error-dispatch/spec.md`](../workflow-on-agent-error-dispatch/spec.md)
|
||||
— the six `on_agent_error` dispatch routes (R1-R6) and the fire site this spec's caller half sits
|
||||
in. Its route table is load-bearing here and is not restated.
|
||||
|
||||
## Why
|
||||
|
||||
`Engine.handleTrigger` records an operation as applied even when it has deliberately not committed
|
||||
that operation's effect. In `EvaluateOnly` mode the engine skips `ApplyTransition` and leaves the
|
||||
commit to its caller, then marks the operation applied anyway before returning. If the caller's
|
||||
commit does not land, the idempotency marker still says it did, and every later delivery of the same
|
||||
operation short-circuits on `Idempotent: true`. The task stays on its old step with no further
|
||||
recovery attempt.
|
||||
|
||||
Verified 2026-09-05 against `ddcc4fc6a`: `handleTrigger`'s tail
|
||||
(`apps/backend/internal/workflow/engine/engine.go`) marks unconditionally, while the commit that mark
|
||||
claims sits inside `processActions` behind `if !in.EvaluateOnly` — so in `EvaluateOnly` mode
|
||||
`applyTransition` never runs, yet the mark still does. Source quoted in
|
||||
[`verification.md`](verification.md#defect-receipt).
|
||||
|
||||
This is not a new design position. `Engine.reevaluateGuardedTransitions` already states the same rule
|
||||
in its own doc comment and commits in-call before marking, so `EvaluateOnly` is the one mode that
|
||||
marks an outcome it did not determine. Quoted and dissected in
|
||||
[`verification.md`](verification.md#why-the-contract-changed-rather-than-the-call-site).
|
||||
|
||||
### Corrections to the reported scope
|
||||
|
||||
The originating comment lists four call sites. Two pass an operation id and use the marker. The two
|
||||
turn callbacks omit one, so `markOperationApplied` returns `nil` for them by construction. Verified by
|
||||
cross-referencing every non-test `EvaluateOnly: true` site with `OperationID:`:
|
||||
|
||||
| Call site | `EvaluateOnly` | `OperationID` passed | Affected today |
|
||||
|---|---|---|---|
|
||||
| `event_handlers_agent_error.go:284` (`dispatchKanbanAgentErrorTrigger`) | true | **yes** (`agentErrorOperationID`) | **yes** |
|
||||
| `event_handlers_workflow.go:6074` (`on_turn_complete`) | true | no | no — mark is a no-op |
|
||||
| `event_handlers_workflow.go:6662` (`on_turn_start`) | true | no | no — mark is a no-op |
|
||||
| `event_handlers_children_completed.go:228` (`on_children_completed`) | true | **yes** (`operationID`) | **yes — explicit `DeferOperationMark` path** |
|
||||
| `office/engine_dispatcher/dispatcher.go:166` | false | yes | no — engine commits, then marks |
|
||||
| `orchestrator/workflow_callbacks.go:142` (`switchWorkflowDispatcher`) | false | yes | no — engine commits, then marks |
|
||||
|
||||
`on_children_completed` is the explicit exception: it passes `operationID` with
|
||||
`DeferOperationMark: true`, then keeps its two-phase bracket — `childCompletionAlreadyApplied`
|
||||
before the engine call and `markChildCompletionApplied` after the commit. The outer caller owns the
|
||||
marker; this path is registered in AC-EO-15.
|
||||
|
||||
This is a latent contract defect with one default engine-deferral caller and one explicit caller-owned
|
||||
deferral. The ACs target the engine contract and require both paths to preserve commit-then-mark order.
|
||||
|
||||
### Blast radius, measured rather than assumed
|
||||
|
||||
`workflowStore.IsOperationApplied` / `MarkOperationApplied`
|
||||
(`internal/orchestrator/workflow_store.go:886-899`) are backed by `appliedOps sync.Map` (`:104`), and
|
||||
there is no `applied_operations` table and no operation-id column anywhere in the schema (measurement
|
||||
receipts in [`verification.md`](verification.md#blast-radius-receipts)). Two consequences the fix must
|
||||
be specified against:
|
||||
|
||||
1. Suppression is **process-scoped, not permanent** — a restart clears every marker. The defect strands
|
||||
a task until then, which on a long-lived install is hours to days, but "permanently" overstates it.
|
||||
2. There is no marker-clearing verb, which rules out the "each caller re-opens the marker on commit
|
||||
failure" option: adding one grows `TransitionStore` for every implementation, and the clear leaves
|
||||
a crash window that reproduces the original bug. Not marking has no such window.
|
||||
|
||||
The suppression window is also wider than the "transient DB failure" the report imagines. AC-EO-11
|
||||
enumerates the four reachable non-committing paths, most of them ordinary: a credential preflight
|
||||
failure is a routine operator condition, and today it burns the operation id for the process's
|
||||
lifetime. Worse, where `AgentExecutionID` is empty the key falls back to one per *session*, so a
|
||||
suppression there disables `on_agent_error` recovery for that whole session until restart, not just
|
||||
for one failure (receipts in [`verification.md`](verification.md#blast-radius-receipts)).
|
||||
|
||||
## Prior art
|
||||
|
||||
Three legs; receipts, findings, and what we do differently in
|
||||
[`verification.md`](verification.md#prior-art-receipts). The wiki and `saas-kb` legs **DID NOT RUN**
|
||||
(tools absent from this sandbox — redo them from an unsandboxed checkout before treating this
|
||||
contract as unprecedented); the in-repo leg **RAN** and produced the two precedents dissected above.
|
||||
|
||||
## What
|
||||
|
||||
### The contract
|
||||
|
||||
The engine records an operation as applied when, and only when, its own call has fully determined
|
||||
that operation's **transition** outcome. Work the engine defers to its caller is not the engine's to
|
||||
claim.
|
||||
|
||||
In `EvaluateOnly` mode a transition is deferred work. Nothing else is: callbacks have already
|
||||
executed by the time `processActions` returns, and a run that produces no transition has no
|
||||
transition outstanding.
|
||||
|
||||
Ownership of the marker therefore transfers to the caller exactly when a transition is deferred, and
|
||||
the engine says so in its result — `HandleResult.OperationMarkDeferred` — rather than leaving each
|
||||
caller to re-derive the rule from `EvaluateOnly`.
|
||||
|
||||
**The invariant is scoped to transitions, deliberately and narrowly.** It is not "the call fully
|
||||
determined every effect". One effect is knowingly excluded: in `EvaluateOnly` mode an evaluation that
|
||||
produces a data patch and no transition drops that patch, because the engine skips `PersistData` and
|
||||
the caller only persists `result.DataPatch` inside its transition branch. That is a real, separate
|
||||
defect, tracked in [Out of scope](#out-of-scope). AC-EO-2 still marks on that path, and this is a
|
||||
decision rather than an oversight: marking there is the pre-existing behavior, withholding the mark
|
||||
would strand the operation forever without persisting the patch, and no re-delivery can recover a
|
||||
patch that no code path writes. Widening the invariant to cover patches would mean fixing the drop — a
|
||||
different change with a different owner. Naming the exclusion here keeps AC-EO-2 and the invariant
|
||||
consistent rather than quietly contradictory.
|
||||
|
||||
### Terms
|
||||
|
||||
- **Deferred transition** — a `HandleTrigger` call where `HandleInput.EvaluateOnly` is `true` and
|
||||
evaluation selected a target step different from the current step (the condition that sets
|
||||
`HandleResult.Transitioned`).
|
||||
- **Marker** — the `(operation id → applied)` entry read by `TransitionStore.IsOperationApplied` and
|
||||
written by `TransitionStore.MarkOperationApplied`.
|
||||
- **Commit** — the caller's persistence of a deferred transition. For the live caller this is
|
||||
`Service.applyEngineTransition` returning `true`.
|
||||
- **Deferred-mark flag** — `HandleResult.OperationMarkDeferred`, the new exported boolean defined by
|
||||
AC-EO-4. The identifier is fixed here: AC-EO-10 reads it and AC-EO-15 scans for it by name.
|
||||
|
||||
### Engine acceptance criteria
|
||||
|
||||
- **AC-EO-1:** WHERE `HandleInput.EvaluateOnly` is `true` AND the call produces a deferred
|
||||
transition, `Engine.HandleTrigger` SHALL NOT invoke `TransitionStore.MarkOperationApplied` for
|
||||
`HandleInput.OperationID`.
|
||||
|
||||
- **AC-EO-2:** WHERE `HandleInput.EvaluateOnly` is `true` AND the call produces no deferred
|
||||
transition, `Engine.HandleTrigger` SHALL invoke `TransitionStore.MarkOperationApplied` for a
|
||||
non-empty `HandleInput.OperationID`, unchanged from current behavior. This includes the case where
|
||||
callbacks executed and returned a data patch but no transition action fired. A data patch SHALL NOT
|
||||
change marker ownership. This is not a claim that the patch was persisted — on this path it is
|
||||
dropped, per the carve-out in [The contract](#the-contract) and the entry in
|
||||
[Out of scope](#out-of-scope). Marking is still correct here because withholding it fixes nothing
|
||||
and strands the operation instead.
|
||||
|
||||
- **AC-EO-3:** WHERE `HandleInput.EvaluateOnly` is `false`, `Engine.HandleTrigger` SHALL invoke
|
||||
`TransitionStore.MarkOperationApplied` after `processActions` returns a nil error, unchanged from
|
||||
current behavior, whether or not a transition occurred.
|
||||
|
||||
- **AC-EO-4:** `HandleResult` SHALL expose an exported boolean field named exactly
|
||||
`OperationMarkDeferred`, reporting that the engine skipped the mark and the caller now owns it. It
|
||||
SHALL be `true` if and only if AC-EO-1 applied **and** `HandleInput.OperationID` is non-empty. It SHALL be `false` on every other return from
|
||||
`HandleTrigger`, including: the idempotent short-circuit, a step declaring no actions for the
|
||||
trigger, `EvaluateOnly: false`, a deferred transition with an empty `OperationID`, and every error
|
||||
return.
|
||||
|
||||
- **AC-EO-5:** IF `processActions` returns a non-nil error, THEN `Engine.HandleTrigger` SHALL NOT
|
||||
invoke `MarkOperationApplied` and SHALL return the zero `HandleResult`. (Current behavior; pinned
|
||||
so the fix cannot regress it.)
|
||||
|
||||
- **AC-EO-6:** WHERE the step declares no actions for the trigger, `Engine.HandleTrigger` SHALL
|
||||
invoke `MarkOperationApplied` regardless of `EvaluateOnly`, because nothing was deferred.
|
||||
|
||||
- **AC-EO-7:** WHERE `HandleInput.OperationID` is the empty string, `Engine.HandleTrigger` SHALL NOT
|
||||
invoke `IsOperationApplied` or `MarkOperationApplied`, unchanged from current behavior.
|
||||
|
||||
- **AC-EO-8:** `HandleTriggerSessionShapedOnly` SHALL follow AC-EO-1 through AC-EO-7 identically to
|
||||
`HandleTrigger`; the action-kind filter SHALL NOT change marker ownership. Both route through the
|
||||
same `handleTrigger` body.
|
||||
|
||||
AC-EO-1 holds **vacuously** on this entry point, by construction rather than by omission:
|
||||
`sessionShapedActionKinds` and the kinds `isTransitionAction` admits are disjoint sets, and
|
||||
`evaluateActions` applies the filter *before* the transition branch, so no deferred transition is
|
||||
reachable here. Observable coverage is therefore AC-EO-2, AC-EO-4's `false`, and AC-EO-7 through this
|
||||
entry point, plus a structural assertion that `sessionShapedActionKinds` admits no transition kind —
|
||||
that assertion is what fails if a later change widens the filter and makes AC-EO-1 reachable, which
|
||||
is the "a fix applied to only one entry point fails" property this AC exists for. Satisfying this AC
|
||||
by admitting a transition kind into the session-shaped set is FORBIDDEN: it would double-dispatch
|
||||
step entry against AC-OFFICE-STEP-ENTRY-001.
|
||||
|
||||
- **AC-EO-9:** `Engine.reevaluateGuardedTransitions` SHALL continue to mark its own
|
||||
`decision:<task>:<step>:<decision>` operation id after `applyFirstSatisfiedGuardedTransition`
|
||||
returns, unchanged. Its commit is in-call, so it is not deferred work and is outside AC-EO-1.
|
||||
|
||||
### Caller acceptance criteria
|
||||
|
||||
- **AC-EO-10:** WHEN `dispatchKanbanAgentErrorTrigger` receives a `HandleResult` whose
|
||||
`OperationMarkDeferred` is `true`, it SHALL invoke `MarkOperationApplied` for that operation id if
|
||||
and only if `applyEngineTransition` returned `true`. The live call site discards that return value
|
||||
today; capturing it is part of this AC.
|
||||
|
||||
- **AC-EO-11:** IF `applyEngineTransition` returns `false` for a deferred transition, THEN the
|
||||
operation SHALL remain unmarked, so a later delivery carrying the same operation id re-evaluates
|
||||
instead of short-circuiting on `Idempotent: true`. This SHALL hold for **all four non-committing
|
||||
return paths reachable from this caller**: target step not found, credential preflight failure,
|
||||
source-step load failure, and commit error — not only the commit-error path.
|
||||
|
||||
`applyEngineTransitionWithCommitMode` has a fifth non-committing return, `applied == false`, and it
|
||||
is **unreachable from `applyEngineTransition` by construction** — the closure trace is in
|
||||
[`verification.md`](verification.md#the-fifth-return-path). No test is required for it and its
|
||||
absence from the test table is deliberate, not an omission. If a future change makes that return
|
||||
reachable from this caller, this AC extends to it unchanged.
|
||||
|
||||
- **AC-EO-12:** IF the caller's own `MarkOperationApplied` returns an error, THEN the caller SHALL
|
||||
log at warn level with the task id, session id and operation id, and SHALL NOT treat the
|
||||
transition as failed. The transition is already committed; the consequence is a possible
|
||||
re-delivery, whose behavior AC-EO-17 defines.
|
||||
|
||||
**This is a code-shape requirement, not a runtime-observable one, and no test is required for it.**
|
||||
The branch is unreachable and not injectable — see the `agentErrorDispatchDeps.store` entry under
|
||||
[Out of scope](#out-of-scope) for why. Enforcement is static instead: `errcheck` is active for this
|
||||
package via golangci-lint v2's **default** set — absent from `apps/backend/.golangci.yml`'s
|
||||
`enable:` list, which sets no `linters.default`, so confirm it with `golangci-lint linters` rather
|
||||
than by grepping that file — so the error cannot be silently discarded, and this AC fixes what the
|
||||
handler does with it. Do not manufacture a seam to test it, and do not drop the handler because it
|
||||
cannot be tested — it becomes reachable the moment the marker is persisted.
|
||||
|
||||
- **AC-EO-13:** `dispatchKanbanAgentErrorTrigger` SHALL serialize concurrent invocations that carry
|
||||
the same operation id. The lock SHALL be acquired **before the task, session and `MachineState`
|
||||
used for evaluation are loaded**, and held across the engine call, the commit, and the caller's
|
||||
mark. Locking only the engine-call-to-mark span breaks AC-EO-17: a racer that blocked on the lock
|
||||
wakes holding a `PreloadedState` built before the winner's commit, which the engine consumes
|
||||
verbatim, so it re-evaluates the **source** step. The operation id derives only from the failure
|
||||
event, so it is computable at entry, before any load.
|
||||
See [Concurrency](#concurrency) for why this becomes required rather than merely advisable.
|
||||
|
||||
The lock SHALL be a **new, separate** ref-counted per-operation-id helper on `Service` — the same
|
||||
shape as `lockChildCompletionOperation`, not the same instance. `Service.childCompletionLocks` is
|
||||
named for child-completion ids; admitting `agent_error:*` keys couples two unrelated triggers'
|
||||
contention and lets a change to either one's lock lifetime silently affect the other. Naming is the
|
||||
builder's; the contract is not: keyed by operation id, created on first acquire, ref-counted, and
|
||||
deleted when the last holder releases, so the map does not grow without bound.
|
||||
|
||||
- **AC-EO-14:** On the deferred path, action callbacks SHALL be understood as at-least-once. When a
|
||||
commit fails and the operation is re-delivered, the **source** step's callbacks run again alongside
|
||||
the re-evaluation (AC-EO-17 covers the case where the commit instead succeeded). This is the intended trade: on the failure path, re-running recovery actions is
|
||||
preferable to a task stranded with no recovery at all. Callers that cannot tolerate a callback
|
||||
replay must not defer.
|
||||
|
||||
- **AC-EO-15:** A regression guard SHALL fail when a non-test `engine.HandleInput` composite literal
|
||||
pairs `EvaluateOnly: true` with a non-empty `OperationID` and its enclosing function is not in a
|
||||
registered set. The predicate below is this AC's exact and intended reach, not an approximation of a
|
||||
broader rule: the blind spot it names is part of the requirement, not a shortfall against it. This is
|
||||
the AC that makes the contract survive the next caller. Its mechanism and predicate are fixed here
|
||||
because the obvious reading — verify the caller *consults* `OperationMarkDeferred` — is a data-flow
|
||||
property no source scan can decide, and
|
||||
attempting it false-fires on any caller that delegates the check into a helper, the way
|
||||
`dispatchKanbanAgentErrorTrigger` already delegates its commit into `s.applyEngineTransition`.
|
||||
|
||||
- **Mechanism: a closed-set allowlist pin**, modelled on `agent_error_fire_site_pin_test.go` — a
|
||||
`go/parser` walk rooted at `apps/backend`, skipping `_test.go` files, collecting offending call
|
||||
sites keyed `"pkgRelDir/ReceiverType.FuncName"` and failing on any key not in a registered set.
|
||||
The guard SHALL NOT attempt to verify that `OperationMarkDeferred` is read. It does not check
|
||||
correctness; it forces a human to review any new caller.
|
||||
- **Detection predicate, purely syntactic and therefore decidable:** a composite literal of type
|
||||
`engine.HandleInput` (or `HandleInput` inside the engine package) having **both** an
|
||||
`EvaluateOnly:` key whose value is the literal `true`, **and** an `OperationID:` key whose value
|
||||
is anything other than the empty-string literal. Runtime non-emptiness is undecidable and SHALL
|
||||
NOT be attempted — every live site passes an identifier (`OperationID: operationID`), never a
|
||||
literal, so "key present and not literally empty" is the working definition of non-empty. A caller
|
||||
that omits the `OperationID:` key entirely is not detected, which is correct: AC-EO-7 makes it
|
||||
unaffected. **Known blind spot:** a caller that does not build a `HandleInput` composite literal
|
||||
in place — assigning fields on a variable, or receiving one from a helper — is not detected
|
||||
either. Accepted: no live site does it, and widening the walk to chase assignments reintroduces
|
||||
the data-flow analysis this AC exists to avoid.
|
||||
- **Registered set has two entries:**
|
||||
`internal/orchestrator/Service.dispatchKanbanAgentErrorTrigger` and
|
||||
`internal/orchestrator/Service.evaluateChildrenCompleted`. The latter is the explicit
|
||||
`DeferOperationMark` path in the scope table above.
|
||||
- **Remediation when it fires:** add the new call site to the registered set, in the same commit
|
||||
that makes that caller honour `OperationMarkDeferred` per AC-EO-10 and serialize per AC-EO-13.
|
||||
Editing the set is the intended remediation, not a workaround — it is the review gate. The failure
|
||||
message SHALL cite AC-EO-10, AC-EO-13 and AC-EO-15 so the next author reads the obligations before
|
||||
editing the set rather than after.
|
||||
|
||||
- **AC-EO-16:** The two `EvaluateOnly` callers that pass no operation id — `on_turn_complete` and
|
||||
`on_turn_start` — SHALL remain unchanged. `processOnChildrenCompleted` is the explicit deferral
|
||||
exception: it passes `operationID` with `DeferOperationMark: true`, and SHALL keep its own
|
||||
`IsOperationApplied` / `MarkOperationApplied` bracket around the outer commit. AC-EO-15 pins it.
|
||||
|
||||
- **AC-EO-17:** WHERE a deferred transition's commit succeeded but the operation was left unmarked,
|
||||
a re-delivery of that operation id SHALL evaluate the task's **current** step — which is now the
|
||||
transition's target step — and that step's own `on_agent_error` actions. It SHALL NOT re-evaluate
|
||||
the source step. A further transition produced by that evaluation is permitted. An evaluation that
|
||||
completes **without a failed commit** invokes the mark — via AC-EO-10 once the caller commits, or
|
||||
via AC-EO-2 when no transition fires — and once that invocation succeeds the next delivery
|
||||
short-circuits on `Idempotent: true`. An evaluation whose commit fails leaves it unmarked, which is
|
||||
the ordinary AC-EO-11 retry path, now anchored at whatever step the task occupies. Re-delivery is
|
||||
therefore bounded by the event source's
|
||||
own retry policy, not by this marker; the marker only guarantees a *successful* outcome is not
|
||||
re-run.
|
||||
|
||||
This window is narrow but real. **Three** things can open it, and only one is reachable for the live
|
||||
caller today: a panic between commit and mark, swallowed by
|
||||
`dispatchKanbanAgentErrorTriggerRecovered`'s `recover()`. The other two are shut by facts about this
|
||||
caller rather than by the engine, so a future caller inherits the duty to re-check both: a failing
|
||||
caller mark, which AC-EO-12 permits and which cannot occur while the store's `MarkOperationApplied`
|
||||
is infallible; and `applyEngineTransition` returning `false` *after* it has committed, which happens
|
||||
only in a lifecycle mode this caller never selects. Receipts for all three in
|
||||
[`verification.md`](verification.md#the-fifth-return-path). The reachable one is accepted rather
|
||||
than closed — one extra recovery evaluation against the step the task actually occupies is the same
|
||||
work
|
||||
`on_agent_error` would do if the agent failed again there, and strictly preferable to the defect
|
||||
being fixed here, where the task is stranded with no recovery at all. A caller that cannot tolerate
|
||||
it must not defer.
|
||||
|
||||
## Forced-to-invent pass
|
||||
|
||||
The axes below are settled here so a builder does not have to guess. Each states a decision, not a
|
||||
description.
|
||||
|
||||
### Ordering
|
||||
|
||||
There is exactly one ordering constraint and it is total: **commit, then mark.** For a deferred
|
||||
transition the sequence is state load → `IsOperationApplied` → evaluate → caller commit →
|
||||
`MarkOperationApplied`, all inside AC-EO-13's lock. No step may be reordered and none may be skipped
|
||||
on the success path.
|
||||
|
||||
The marker write is unordered with respect to the transition's other post-commit work (step history
|
||||
row, `processOnEnter`, session state flip) because it shares no state with them. It SHALL be issued
|
||||
after `applyEngineTransition` returns, from the same goroutine, and SHALL NOT be moved into
|
||||
`launchProcessOnEnter`'s goroutine, where a panic or early return would drop it silently.
|
||||
|
||||
### Idempotency and retry
|
||||
|
||||
Marking an already-marked operation is a no-op: `sync.Map.Store` overwrites. A double mark is harmless
|
||||
and needs no guard.
|
||||
|
||||
The engine's `Idempotent: true` short-circuit keeps its current meaning — "this operation's outcome was
|
||||
already fully determined" — and after this change that statement is true, which it was not before.
|
||||
|
||||
A re-delivery of an unmarked operation re-runs the whole call against **the task's current step**,
|
||||
whatever that now is: `assembleMachineState` derives `CurrentStepID` from `task.WorkflowStepID`, and
|
||||
`loadExecutionContext` loads that step's spec. Which step that is depends on whether the first
|
||||
attempt's commit landed, and the two cases are not symmetric:
|
||||
|
||||
- **Commit did not land** (the four AC-EO-11 paths). The task is still on the source step, so the
|
||||
re-delivery re-evaluates the *same* actions. Callbacks replay — at-least-once, per AC-EO-14 — and the
|
||||
transition is retried. This is the recovery the whole change exists to restore.
|
||||
- **Commit landed but the mark did not.** The task is now on the *target* step, so the re-delivery
|
||||
evaluates that step's actions instead. AC-EO-17 governs this case and permits it.
|
||||
|
||||
It does **not** reduce to "the second evaluation finds `targetStepID == state.CurrentStepID` and
|
||||
produces no transition" — that assumes the source step is re-read, and it is not. AC-EO-17 governs
|
||||
what the second evaluation does and when it terminates; only a repeatedly failing commit keeps the
|
||||
operation re-evaluating, which is the retry this change exists to restore.
|
||||
|
||||
### Concurrency
|
||||
|
||||
Two callers holding the same operation id concurrently is not newly possible, but it is newly
|
||||
consequential.
|
||||
|
||||
Today `IsOperationApplied` and `MarkOperationApplied` are separate `sync.Map` operations with no
|
||||
compare-and-set between them, so two callers can both pass the check and both proceed. The window
|
||||
between check and mark is currently the engine call. After this change, for a deferred transition,
|
||||
it widens at both ends: forward to include the caller's commit — `processOnExit`, a credential
|
||||
preflight, a DB write and a step-history write — and back over the caller's own state load, because
|
||||
the engine reads `PreloadedState` verbatim and never re-reads the store. AC-EO-13 closes the whole
|
||||
widened window for the live caller with a per-operation-id mutex, which is the same instrument
|
||||
`processOnChildrenCompleted` already uses and which is sufficient because both
|
||||
racers are in-process by construction (the marker itself is process-local, so a cross-process racer
|
||||
could never have been deduplicated by it anyway).
|
||||
|
||||
The engine SHALL NOT serialize on the caller's behalf. It does not today, its store interface has no
|
||||
claim/release verb, and adding one would make every `TransitionStore` implementation responsible for
|
||||
lock lifetime to fix a race only one caller can currently experience.
|
||||
|
||||
That decision pushes an obligation onto callers, so it is stated as a general rule rather than only
|
||||
for the one that exists: **any caller that pairs `EvaluateOnly: true` with a non-empty `OperationID`
|
||||
inherits two obligations, not one** — honour `OperationMarkDeferred` (AC-EO-10) *and* serialize the
|
||||
load → check → evaluate → commit → mark window against its own operation id (AC-EO-13). AC-EO-15's
|
||||
guard cannot verify either; it fires so a human checks both before the caller ships. A future caller that
|
||||
takes the flag but skips the lock reintroduces exactly the race this section describes, widened.
|
||||
|
||||
Two callers with *different* operation ids on the same task remain unserialized by this spec. That
|
||||
race is real and predates it — it is the race `ApplyTransitionIfAtStep` (AC-46/48) exists for — and
|
||||
it is untouched here.
|
||||
|
||||
### Nil, empty and error
|
||||
|
||||
Each case names the AC that governs it; the ACs are authoritative.
|
||||
|
||||
- Empty `OperationID`: no store calls at all (AC-EO-7), `OperationMarkDeferred` is `false` (AC-EO-4).
|
||||
This is the current behavior of the two no-id callers and must keep working. Child completion is
|
||||
the explicit deferred-mark exception.
|
||||
- `processActions` error: no mark, zero `HandleResult` (AC-EO-5). Every caller already discards the
|
||||
result on a non-nil error; this spec introduces no partial result.
|
||||
- `MarkOperationApplied` error in the engine (AC-EO-2/3 paths): returned as `HandleTrigger`'s error
|
||||
alongside a populated `HandleResult`, unchanged. Pre-existing and deliberately left alone — see
|
||||
[Out of scope](#out-of-scope).
|
||||
- `MarkOperationApplied` error in the caller: warn and continue (AC-EO-12); unreachable today.
|
||||
- Nil `TransitionStore`: out of contract. The engine already dereferences `e.store` unconditionally and
|
||||
`New` accepts no nil store from any production wiring.
|
||||
|
||||
### Defaults and boundaries
|
||||
|
||||
- `OperationMarkDeferred` defaults to `false` — the zero value is the safe one, so a caller that ignores
|
||||
it behaves exactly as it does today, and a mistakenly zero-valued `HandleResult` never claims
|
||||
ownership the caller has not accepted.
|
||||
- No new configuration, no runtime flag, no profile entry. The correct behavior is unconditional;
|
||||
a flag would mean shipping the defect as a supported mode.
|
||||
- No schema change. The marker stays in `sync.Map` (see [Out of scope](#out-of-scope)).
|
||||
- `HandleInput` gains no field. `EvaluateOnly` plus the evaluated outcome already determines
|
||||
ownership; a second input flag would let a caller ask for the broken ordering.
|
||||
|
||||
## Out of scope
|
||||
|
||||
Named exclusions, each with what a follow-up would need to know.
|
||||
|
||||
- **Persisting the operation marker.** `appliedOps` has no eviction and no durability (see
|
||||
[Blast radius](#blast-radius-measured-rather-than-assumed)). Fixing it means an
|
||||
`applied_operations` table with a retention policy, a migration, and a decision about what
|
||||
`IsOperationApplied` returns while that table is written under load — a separate durability
|
||||
requirement that changes behavior for callers this spec does not touch. This spec is correct under
|
||||
both the current in-memory store and a future persisted one, because it constrains only *when* the
|
||||
mark is issued.
|
||||
|
||||
- **Data patches dropped on the no-transition `EvaluateOnly` path.** In `EvaluateOnly` mode the
|
||||
engine skips `PersistData` (`engine.go:292`) and the caller persists it — but
|
||||
`applyEngineTransitionWithCommitMode` only persists `result.DataPatch` inside its transition path
|
||||
and only when `sessionLifecycle` is set (`event_handlers_workflow.go:5492`), and it is only called
|
||||
at all when `result.Transitioned` is true. So an `EvaluateOnly` evaluation that produces a data
|
||||
patch and no transition drops the patch entirely. This is a real defect in the same mode and the
|
||||
same function, and it was found while confirming AC-EO-2's boundary. It is excluded because it is
|
||||
a different failure (silent data loss, not retry suppression), it has a different fix (deciding
|
||||
whether the engine or the caller owns patch persistence in evaluate-only mode), and no
|
||||
`EvaluateOnly` caller demonstrably hits it today — `set_workflow_data` is the only patch-producing
|
||||
callback and the shipped steps that declare it also declare a transition. A follow-up needs:
|
||||
those two file:line anchors, the fact that `on_children_completed` never persists patches at all,
|
||||
and a survey of whether any workflow YAML declares `set_workflow_data` without a sibling
|
||||
transition action. This exclusion is why [The contract](#the-contract) scopes its invariant to
|
||||
transitions and why AC-EO-2 marks on this path anyway; a follow-up that fixes the drop should
|
||||
revisit that carve-out, not just the persistence call.
|
||||
|
||||
- **`HandleTrigger` returning a populated `HandleResult` alongside a non-nil error.** On the
|
||||
AC-EO-2/3 paths a mark failure yields a result describing a committed transition together with an
|
||||
error, and every caller discards the result and returns — so in non-`EvaluateOnly` mode the
|
||||
transition committed but the caller believes the call failed. Excluded: a wart on the *non*-deferred
|
||||
path, fixing it changes error semantics for the Office dispatcher and `switchWorkflowDispatcher`,
|
||||
and it is unreachable while `MarkOperationApplied` cannot fail. A follow-up should take it with
|
||||
the persistence work above, which is what makes it reachable.
|
||||
|
||||
- **Widening `agentErrorDispatchDeps.store` to an interface.** The field, and `Service.workflowStore`
|
||||
behind it, are the concrete `*workflowStore`, whose `MarkOperationApplied` is `return nil`
|
||||
unconditionally. That is why AC-EO-12's handler cannot be driven from a test and is enforced
|
||||
statically by `errcheck` instead. Widening the field to a `TransitionStore`-shaped interface would
|
||||
make it testable, but it is a production dependency change for a branch that is unreachable until
|
||||
the marker is persisted, and it touches wiring this spec otherwise leaves alone. A follow-up should
|
||||
do it together with the persistence work above, which is what makes the branch reachable and the
|
||||
test worth having.
|
||||
|
||||
- **Changing child-completion marker ownership or lifecycle.** Its `operationID` plus
|
||||
`DeferOperationMark` path is an explicit caller-owned exception. This spec does not change the
|
||||
outer commit-to-mark bracket.
|
||||
|
||||
- **Frontend, API and documentation surfaces.** Not observable from any user-facing surface. See
|
||||
[E2E decision](#e2e-decision).
|
||||
|
||||
## E2E decision
|
||||
|
||||
**No Playwright coverage.** No user-visible surface: no API response shape, no WS event, no DTO field,
|
||||
no rendered copy. The entire observable footprint is the *absence* of a suppressed retry inside the
|
||||
backend, which no browser-level assertion can distinguish from an ordinary successful dispatch.
|
||||
|
||||
Surfaces touched: `internal/workflow/engine` (contract) and `internal/orchestrator` (one caller).
|
||||
Nothing under `apps/web`, `docs/public`, or `pkg/api/v1`. Verification is Go unit tests only —
|
||||
commands, failing-first list and per-AC coverage mapping are in
|
||||
[`verification.md`](verification.md).
|
||||
@@ -0,0 +1,249 @@
|
||||
# Verification plan — `EvaluateOnly` operation marking
|
||||
|
||||
Companion to [`spec.md`](spec.md). Provenance and test mapping, not contract. Where the two
|
||||
disagree, `spec.md` wins.
|
||||
|
||||
## Prior art receipts
|
||||
|
||||
The unabridged receipts; `spec.md` § Prior art carries the same three legs in short form and points
|
||||
here.
|
||||
|
||||
- **Leg 1 (wiki) — DID NOT RUN.** Resolved `OBSIDIAN_VAULT_PATH=/Users/henry/Documents/henry/wiki`
|
||||
via `~/.obsidian-wiki/config` → `config.henry`, `QMD_WIKI_COLLECTION="wiki"`. Neither
|
||||
`obsidian-wiki` nor `qmd` is on `PATH`; the documented grep fallback returns
|
||||
`Operation not permitted` on the vault and a direct read of `index.md` returns `EPERM`. Sandbox
|
||||
restriction, not an empty vault.
|
||||
- **Leg 2 (`saas-kb` / `search_fsm_docs`) — DID NOT RUN.** MCP server absent from the session tool
|
||||
list; no query issued with or without `category: "ai_sdlc"`.
|
||||
- **Leg 3 (in-repo) — RAN.** `grep -rn "markOperationApplied\|IsOperationApplied"` and
|
||||
`grep -rn "OperationID:"` over `apps/backend` (non-test) at `ddcc4fc6a`. It produced the two
|
||||
precedents `spec.md` § Why dissects.
|
||||
|
||||
**What we do differently** (displaced from `spec.md` § Prior art, which is at its size ceiling):
|
||||
neither precedent generalizes — `reevaluateGuardedTransitions` commits in-call, while
|
||||
`processOnChildrenCompleted` uses the explicit caller-owned deferral path (`OperationID` plus
|
||||
`DeferOperationMark`). This spec makes the result signal part of `HandleTrigger`, so both current
|
||||
callers carry a visible commit-to-mark obligation.
|
||||
|
||||
## Measurement receipts
|
||||
|
||||
Displaced from `spec.md`, which is at its size ceiling. Contract statements stay there; the raw
|
||||
measurements that back them live here.
|
||||
|
||||
### Defect receipt
|
||||
|
||||
The tail of `handleTrigger` at `ddcc4fc6a`, `apps/backend/internal/workflow/engine/engine.go`:
|
||||
|
||||
```go
|
||||
result, err := e.processActions(ctx, in, state, step, actions, filter)
|
||||
if err != nil {
|
||||
return HandleResult{}, err
|
||||
}
|
||||
|
||||
return result, e.markOperationApplied(ctx, in.OperationID) // unconditional
|
||||
```
|
||||
|
||||
The commit this mark claims sits inside `processActions`, behind `if !in.EvaluateOnly`.
|
||||
|
||||
### Blast radius receipts
|
||||
|
||||
`grep -rn "applied_operations\|operation_id" --include=*.sql apps/backend` returns nothing — there is
|
||||
no `applied_operations` table and no operation-id column anywhere in the schema, so the marker lives
|
||||
only in `appliedOps sync.Map` (`internal/orchestrator/workflow_store.go:104`, read/written at
|
||||
`:886-899`) and suppression is process-scoped. `agentErrorOperationID`
|
||||
(`internal/orchestrator/event_handlers_agent_error.go:58-63`) is where the
|
||||
`agent_error:session:<sessionID>` fallback is built when `AgentEventData.AgentExecutionID` is empty.
|
||||
|
||||
### The fifth return path
|
||||
|
||||
Named for the path AC-EO-11's four-case table excludes, but the accounting here is over **every**
|
||||
`return false` in `applyEngineTransitionWithCommitMode`. There are **six**, not five, and the sixth
|
||||
is not a non-committing return at all. Measured at `ddcc4fc6a`,
|
||||
`internal/orchestrator/event_handlers_workflow.go`:
|
||||
|
||||
| line | path | disposition |
|
||||
|---|---|---|
|
||||
| 5411 | target step lookup error | AC-EO-11 case 1 |
|
||||
| 5419 | credential preflight failure | AC-EO-11 case 2 |
|
||||
| 5433 | source-step load failure | AC-EO-11 case 3 |
|
||||
| 5458 | commit error | AC-EO-11 case 4 |
|
||||
| 5461 | `applied == false` (CAS closure) | never committed; unreachable, see below |
|
||||
| 5524 | `maybySwitchSessionForProfile` failure | **post-commit**; unreachable, see below |
|
||||
|
||||
**The fifth, `applied == false`, is unreachable from `applyEngineTransition`.** The commit closure
|
||||
`applyEngineTransitionWithMode` supplies returns `(true, nil)` or `(false, err)` and never
|
||||
`(false, nil)`. `(false, nil)` originates only from the guarded-decision CAS closure over
|
||||
`applyTransitionIfAtStepRaw`, which AC-EO-9 carves out and which never runs in `EvaluateOnly` mode.
|
||||
|
||||
**The sixth is a different kind of return, and is the one to read carefully.** It sits *after* the
|
||||
commit at `:5458` has already succeeded, inside the `mode == transitionLifecycleOnTurnStart` branch
|
||||
opened at `:5517`, so it is a `return false` on a **committed** transition — not a non-committing
|
||||
path, and therefore outside AC-EO-11's framing rather than a fifth-and-sixth pair with the CAS
|
||||
closure. It is unreachable from this caller by construction, on the same "mode is fixed at the sole
|
||||
live call site" argument: `applyEngineTransition` (`:5343-5353`) sets
|
||||
`mode = transitionLifecycleWithOnEnter` whenever `triggerOnEnter` is true, and
|
||||
`dispatchKanbanAgentErrorTrigger` passes `true` (`event_handlers_agent_error.go:253`), so the
|
||||
`transitionLifecycleOnTurnStart` branch cannot execute for it.
|
||||
|
||||
Why this matters beyond the count: a `return false` after a successful commit is a **second
|
||||
structural opener** of AC-EO-17's commit-succeeded-but-unmarked window, alongside the panic that AC
|
||||
names and the mark failure AC-EO-12 permits. Under AC-EO-10's `if and only if` it leaves the marker
|
||||
absent on a committed transition. A future `EvaluateOnly` caller whose commit helper reaches
|
||||
`applyEngineTransitionWithCommitMode` in `transitionLifecycleOnTurnStart` mode would hit it on every
|
||||
profile-switch failure — the same stranding this spec exists to close, re-entered through the caller
|
||||
obligations the spec hands out. That caller therefore owes a **third** obligation beyond AC-EO-10 and
|
||||
AC-EO-13: confirm which lifecycle mode its commit helper selects, because the mode is what closes
|
||||
this today and nothing in the engine does.
|
||||
|
||||
## Why the contract changed rather than the call site
|
||||
|
||||
Three options were on the table. The originating comment named two.
|
||||
|
||||
**(b) Each `EvaluateOnly` caller re-opens the marker when its own commit fails.** Rejected on
|
||||
mechanism, not on taste. `TransitionStore` has no clearing verb, so this means adding one to an
|
||||
interface with production and test implementations, and the clear itself can fail. Worse, it leaves
|
||||
a crash window between the premature mark and the clear that reproduces the original bug exactly —
|
||||
the failure it is meant to fix is the failure it reintroduces. It also has to be re-applied at every
|
||||
future call site, which is the property AC-EO-15 exists to prevent.
|
||||
|
||||
**(a-full) A caller-driven two-phase commit protocol on `HandleInput`/`HandleResult`.** Rejected as
|
||||
more machinery than the problem needs. The engine does not need to learn the caller's commit
|
||||
outcome; it only needs to stop asserting one it never had.
|
||||
|
||||
**(a-narrow) — adopted.** The engine declines to mark exactly the work it deferred, and reports that
|
||||
it did so. Two conditions in the engine, one caller change, no interface growth, no new failure
|
||||
window. It also generalizes: the reason `on_children_completed` is already correct is that it does
|
||||
this by hand.
|
||||
|
||||
The invariant is not novel, and `spec.md` § Why states it in one sentence because the detail lives
|
||||
here. `Engine.reevaluateGuardedTransitions` (`internal/workflow/engine/quorum.go:667`) already states
|
||||
the rule in its own doc comment — the operation id is marked applied "only once this function has
|
||||
fully determined the outcome (transitioned, abandoned, or nothing satisfied) — never before, so a
|
||||
crash mid-evaluation does not leave a decision's re-evaluation permanently skipped" — and it commits
|
||||
through the CAS *inside* the call before marking. `EvaluateOnly` was the one mode where the outcome
|
||||
is determined outside the call, and the one mode that marked anyway. This spec closes that hole; it
|
||||
does not invent a new rule.
|
||||
|
||||
## Test mapping
|
||||
|
||||
TDD: every test below is written failing first. `TestHandleTrigger_EvaluateOnlySkipsPersistence`
|
||||
(`engine_test.go:298`) passes no `OperationID` and so does not cover any of this — do not mistake it
|
||||
for existing coverage.
|
||||
|
||||
### `apps/backend/internal/workflow/engine`
|
||||
|
||||
Extend `fakeStore` to record `MarkOperationApplied` calls (it already has an `applied` map; the
|
||||
tests need call-order or a call log, not just the final set).
|
||||
|
||||
| AC | Test |
|
||||
|---|---|
|
||||
| AC-EO-1 | `EvaluateOnly: true` + non-empty `OperationID` + a step whose trigger fires `move_to_next` → store records **no** `MarkOperationApplied`, and `Transitioned` is true |
|
||||
| AC-EO-2 | same, but the step declares only a non-transition action → `MarkOperationApplied` **is** called |
|
||||
| AC-EO-2 | same, non-transition action returning a `DataPatch` → `MarkOperationApplied` is called. Assert **only** that a patch does not change marker ownership. Do NOT assert or imply the patch was persisted — on this path it is dropped, which `spec.md` § The contract carves out and § Out of scope tracks. Name the test for marker ownership, not for patch handling, so the deferred fix does not have to reinterpret it |
|
||||
| AC-EO-3 | `EvaluateOnly: false` + transition → `MarkOperationApplied` called, `ApplyTransition` called, mark after commit |
|
||||
| AC-EO-4 | `HandleResult.OperationMarkDeferred` is `true` for the AC-EO-1 case, and `false` for each of: idempotent short-circuit, no-actions step, `EvaluateOnly: false`, deferred transition with empty `OperationID`, and a `processActions` error |
|
||||
| AC-EO-5 | callback returns an error → no mark, zero `HandleResult` |
|
||||
| AC-EO-6 | step declares no actions for the trigger, `EvaluateOnly: true` → mark called |
|
||||
| AC-EO-7 | empty `OperationID` → neither `IsOperationApplied` nor `MarkOperationApplied` called |
|
||||
| AC-EO-8 | AC-EO-2, AC-EO-4-`false` and AC-EO-7 re-run through `HandleTriggerSessionShapedOnly` with the same expectations, **plus** a structural assertion that `sessionShapedActionKinds` and the kinds `isTransitionAction` admits are disjoint sets. There is deliberately **no** AC-EO-1 case here: the filter admits no transition kind and `evaluateActions` applies it before the transition branch, so a deferred transition is unreachable through this entry point and AC-EO-1 holds vacuously (`spec.md` AC-EO-8). The disjointness assertion is the thing that fails if a later change widens the filter. Do **not** make an AC-EO-1 case pass here by adding a transition kind to the session-shaped set — that double-dispatches step entry against AC-OFFICE-STEP-ENTRY-001 |
|
||||
| AC-EO-9 | existing quorum re-evaluation coverage still marks `decision:<task>:<step>:<decision>`; add an explicit assertion if none pins the ordering today |
|
||||
|
||||
### `apps/backend/internal/orchestrator`
|
||||
|
||||
New file — `event_handlers_agent_error*_test.go` is already at six test files and the
|
||||
800-effective-line revive limit applies to test files.
|
||||
|
||||
| AC | Test |
|
||||
|---|---|
|
||||
| AC-EO-10 | `OperationMarkDeferred` result + `applyEngineTransition` succeeds → operation id present in the store afterwards |
|
||||
| AC-EO-11 | one case per **reachable** non-committing path: target step missing, credential preflight failure, source-step load failure, commit error. **Four cases, not five** — `applied == false` is unreachable from `applyEngineTransition` by construction (its commit closure never returns `(false, nil)`), so there is no fifth test and its absence is deliberate. Each case asserts the operation id is **absent** afterwards, then re-dispatches the same `AgentEventData` and asserts the engine re-evaluated rather than returning `Idempotent` |
|
||||
| AC-EO-12 | **No test.** The branch is unreachable: `agentErrorDispatchDeps.store` is the concrete `*workflowStore`, whose `MarkOperationApplied` is `return nil` unconditionally, and no fake substitutes without widening a production field (deferred — `spec.md` § Out of scope). Enforcement is `errcheck` — active via golangci-lint v2's **default** linter set, not via `apps/backend/.golangci.yml`'s `enable:` list (that file sets no `linters.default`); confirm with `golangci-lint linters` rather than by grepping it — plus code review of the warn-and-continue handler. Do not manufacture a seam, and do not drop the handler |
|
||||
| AC-EO-13 | two concurrent `dispatchKanbanAgentErrorTrigger` calls with the same `(SessionID, AgentExecutionID)` → exactly one commit. Run under `-race`. Assert against the **new** per-operation-id helper, not `lockChildCompletionOperation` — AC-EO-13 requires a separate map, so a test that reaches into `childCompletionLocks` is testing the wrong thing |
|
||||
| AC-EO-13 | **lock SPAN through the commit, the case "exactly one commit" cannot see.** `TestDispatchKanbanAgentErrorTrigger_ConcurrentSameOperationLockSpansThroughCommit` (`event_handlers_agent_error_evaluate_only_test.go`) blocks the first dispatch **inside** its `UpdateTaskWithWorkflowStepAdmission` commit call (via `agentErrorBlockingCommitRepo`) and asserts the second, concurrent dispatch has not yet re-read `GetTaskSession` or observed the operation as applied while the first is still inside its own commit — pinning that the lock is held from before state load through the commit→mark window, not just up to the engine call. Mutation-verified: releasing the lock right after `HandleTrigger` returns (before `applyEngineTransition`/mark) made the *old* one-commit-only assertion fail just 1-in-20 runs at `-count=20`; this test fails deterministically (5/5) under the same mutation, closing the gap a scheduler-dependent assertion could not |
|
||||
| AC-EO-14 | after a failed commit (task still on the **source** step), re-delivery re-executes that step's callbacks — assert the callback ran twice. Pins at-least-once as intended, so a later reader does not "fix" it |
|
||||
| AC-EO-16 | `TestProcessOnChildrenCompleted_StillIdempotentOnRedelivery` (`event_handlers_children_completed_test.go`): a 3-step chain where the target step **also** declares an `OnChildrenCompleted` action, so the marker check is load-bearing — without it, redelivery would re-fire that action and advance a second time. Asserts `IsOperationApplied` is true after the first delivery and that redelivery neither transitions again nor moves the parent past its post-first-delivery step. Mutation-verified: deleting `childCompletionAlreadyApplied`'s short-circuit makes this test fail. The child-completion caller passes `OperationID` with `DeferOperationMark: true` and remains in the AC-EO-15 registered set; the `on_turn_start` / `on_turn_complete` callers pass no `OperationID`, so the pin test flags either if it later pairs the two fields. |
|
||||
| AC-EO-17 | commit succeeds, marker left absent → re-delivery evaluates the **target** step's actions, not the source step's. Assert the step id the second evaluation loaded, and that a mark lands by the end of it (via AC-EO-10 or AC-EO-2) so a third delivery short-circuits. Drive the missing mark from the test rather than by panicking, and do not assert a specific second transition — the AC permits one, it does not require one |
|
||||
|
||||
The AC-EO-11 rows are the ones that would have caught the original defect. Prefer the credential
|
||||
preflight case as the primary regression test: it is the most ordinary of the four and the least
|
||||
likely to be dismissed as a synthetic DB fault.
|
||||
|
||||
### Regression guard (AC-EO-15)
|
||||
|
||||
`spec.md` AC-EO-15 fixes the mechanism, the detection predicate and the remediation; this section only
|
||||
says how to build it. Model on `agent_error_fire_site_pin_test.go`, which is the same kind of artifact:
|
||||
a `go/parser` walk rooted at `apps/backend`, skipping `_test.go`, keyed
|
||||
`"pkgRelDir/ReceiverType.FuncName"`, failing on any key absent from a registered set.
|
||||
|
||||
- **It is a closed-set allowlist, not a data-flow check.** Do not try to verify that
|
||||
`OperationMarkDeferred` is read — that is undecidable and false-fires on a caller that delegates the
|
||||
check into a helper.
|
||||
- **Detection predicate:** a `HandleInput` composite literal with both an `EvaluateOnly:` key whose
|
||||
value is the literal `true` and an `OperationID:` key whose value is not the empty-string literal.
|
||||
Nothing more; runtime non-emptiness is not inferable and must not be attempted.
|
||||
- **Seed the set with two entries:** `internal/orchestrator/Service.dispatchKanbanAgentErrorTrigger` and
|
||||
`internal/orchestrator/Service.evaluateChildrenCompleted` (the explicit `DeferOperationMark` path).
|
||||
- **Put it in a new file** rather than extending `agent_error_fire_site_pin_test.go`. Either satisfies
|
||||
every AC-EO-15 observable, so this is a steer, not a requirement: the two guards pin unrelated
|
||||
predicates, and a shared walk helper couples their lifetimes for no gain.
|
||||
- **Editing the set IS the remediation**, not a workaround — it is the review gate, exactly as in the
|
||||
fire-site pin. Point the failure message at AC-EO-10, AC-EO-13 and AC-EO-15 together, so the next
|
||||
author reads all three caller obligations before adding their entry rather than after: honour the
|
||||
flag, serialize the window, and check which lifecycle mode their commit helper selects (§ The fifth
|
||||
return path — in `transitionLifecycleOnTurnStart` mode the helper can return `false` on a committed
|
||||
transition, which AC-EO-10's `if and only if` would then leave unmarked).
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# focused, during TDD
|
||||
go test ./internal/workflow/engine/... -run 'EvaluateOnly|OperationApplied|MarkOperation' -race -count=1
|
||||
go test ./internal/orchestrator/... -run 'AgentError' -race -count=1
|
||||
|
||||
# before commit — internal/orchestrator carries goleak.VerifyTestMain; the engine package does not
|
||||
go test ./internal/workflow/engine/... ./internal/orchestrator/... -race -count=1
|
||||
|
||||
# changed-file lint, per apps/backend/CLAUDE.md
|
||||
golangci-lint run ./... --new-from-rev="$(git merge-base HEAD origin/main)" --timeout=5m
|
||||
```
|
||||
|
||||
All from `apps/backend`. `internal/orchestrator` carries `goleak.VerifyTestMain`, so the AC-EO-13
|
||||
concurrency test must join its goroutines rather than leaving them to the race detector.
|
||||
|
||||
Specification lint, from the repo root:
|
||||
|
||||
```bash
|
||||
python3 scripts/lint-spec-files.py --all
|
||||
```
|
||||
|
||||
`docs/specs/<slug>/` classifies as `legacy` for the linter, whose only check on it is the 32768-byte
|
||||
ceiling plus the size ratchet. **`spec.md` is at 32689 / 32768 bytes — 79 bytes of headroom, which is
|
||||
effectively full.** A future edit must DISPLACE prose into this file, which has no ceiling, rather than
|
||||
append to `spec.md`; § Measurement receipts above exists because three rounds of edits already had to.
|
||||
Re-measure with `wc -c` after every edit and re-run the lint. Do not add a
|
||||
`docs/specs/spec-lint-exceptions.tsv` entry: exceptions only ratchet downward and a new file has no
|
||||
business needing one.
|
||||
|
||||
## Risks
|
||||
|
||||
- **The AC-EO-14 / AC-EO-17 trade is the one a reviewer will push back on.** Deferring the mark means
|
||||
callbacks can run twice when a commit fails (AC-EO-14), and — in the narrower window where the
|
||||
commit landed but the mark did not — that the re-delivery evaluates the *target* step and may
|
||||
transition again (AC-EO-17). The alternative is the current behavior, where neither happens and the
|
||||
task is stranded. Both are stated as ACs rather than left implicit precisely so the push-back lands
|
||||
on the decision instead of on the implementation.
|
||||
- **AC-EO-13's lock must span load → engine → commit → mark, not engine → commit → mark.** This is
|
||||
the trap of the whole spec. The engine consumes `HandleInput.PreloadedState` verbatim and never
|
||||
re-reads the store, and the live caller builds that state *before* it even computes the operation
|
||||
id — so a lock that starts at the engine call lets a blocked racer wake holding pre-commit state
|
||||
and re-evaluate the **source** step, which AC-EO-17 forbids. Because `ApplyTransition` is a plain
|
||||
write with no compare-and-set, that second commit re-runs `processOnExit` for a step the task has
|
||||
already left and re-enters the target: a step-entry double-dispatch. A naive concurrency test that
|
||||
only counts commits or marks passes anyway, which is why the second AC-EO-13 row above asserts the
|
||||
step id instead. The lock must also be a *separate* map from `childCompletionLocks`, per AC-EO-13.
|
||||
- **AC-EO-12 has no test, on purpose.** `sync.Map` makes `MarkOperationApplied` infallible and the
|
||||
caller's dependency is a concrete `*workflowStore`, so the error branch is neither reachable nor
|
||||
injectable without a production change this spec defers. `errcheck` keeps the error from being
|
||||
dropped; the handler ships untested and becomes testable when the marker is persisted (`spec.md`
|
||||
§ Out of scope). Reviewers should not read the missing test as an omission — but should reject any
|
||||
attempt to delete the handler because it lacks one.
|
||||
Reference in New Issue
Block a user