Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions cmd/ateapi/internal/controlapi/workflow.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ type WorkflowStep[Params any, Context any] interface {
// If it returns true, the engine skips Execute() and fast-forwards to the next step.
IsComplete(ctx context.Context, params Params, wCtx Context) (bool, error)

// CheckPrerequisite validates that the current state permits executing this
// step (e.g. the actor's status allows this state-machine edge). The engine
// calls it only when IsComplete returned false, immediately before Execute,
// so completed steps of a retried workflow fast-forward without
// re-validation. Return a gRPC status error with
// codes.FailedPrecondition to abort the workflow if prereqs are not met.
CheckPrerequisite(ctx context.Context, params Params, wCtx Context) error

// Execute performs the step's business logic and persists any state changes.
// If an error is returned, the workflow stops and relies on the client to retry.
Execute(ctx context.Context, params Params, wCtx Context) error
Expand Down Expand Up @@ -79,6 +87,13 @@ func RunWorkflow[Params any, Context any](ctx context.Context, params Params, wC
continue
}

if err := step.CheckPrerequisite(ctx, params, wCtx); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
span.End()
return fmt.Errorf("prerequisite not met at step %s: %w", step.Name(), err)
}

err = runStep(ctx, params, wCtx, step)
if err != nil {
span.RecordError(err)
Expand Down
29 changes: 24 additions & 5 deletions cmd/ateapi/internal/controlapi/workflow_pause.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import (
atev1alpha1 "github.com/agent-substrate/substrate/pkg/api/v1alpha1"
listersv1alpha1 "github.com/agent-substrate/substrate/pkg/client/listers/api/v1alpha1"
"github.com/agent-substrate/substrate/pkg/proto/ateapipb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/apimachinery/pkg/util/wait"
)

Expand All @@ -52,6 +54,9 @@ func (s *LoadActorForPauseStep) IsComplete(ctx context.Context, input *PauseInpu
// Always run to get the freshest state
return false, nil
}
func (s *LoadActorForPauseStep) CheckPrerequisite(ctx context.Context, input *PauseInput, state *PauseState) error {
return nil
}
func (s *LoadActorForPauseStep) Execute(ctx context.Context, input *PauseInput, state *PauseState) error {
actor, err := s.store.GetActor(ctx, input.Atespace, input.ActorName)
if err != nil {
Expand Down Expand Up @@ -79,11 +84,14 @@ func (s *MarkPausingStep) IsComplete(ctx context.Context, input *PauseInput, sta
// Fast forward if we've already marked our intent or if we are further along.
return state.Actor.GetStatus() == ateapipb.Actor_STATUS_PAUSING || state.Actor.GetStatus() == ateapipb.Actor_STATUS_PAUSED, nil
}
func (s *MarkPausingStep) Execute(ctx context.Context, input *PauseInput, state *PauseState) error {
func (s *MarkPausingStep) CheckPrerequisite(ctx context.Context, input *PauseInput, state *PauseState) error {
// The pause edge only exists from RUNNING; PAUSING/PAUSED are fast-forwarded by IsComplete.
if state.Actor.GetStatus() != ateapipb.Actor_STATUS_RUNNING {
return nil
return status.Errorf(codes.FailedPrecondition, "MarkPausingStep prerequisite not met for Actor: %s (got: %v, want %s)", input.ActorName, state.Actor.GetStatus(), ateapipb.Actor_STATUS_RUNNING)
}

return nil
}
func (s *MarkPausingStep) Execute(ctx context.Context, input *PauseInput, state *PauseState) error {
state.Actor.Status = ateapipb.Actor_STATUS_PAUSING
state.Actor.InProgressSnapshot = fmt.Sprintf("%s-%s-%s", state.Actor.GetMetadata().GetName(), time.Now().Format(time.RFC3339), rand.Text())
updatedActor, err := s.store.UpdateActor(ctx, state.Actor, state.Actor.GetMetadata().GetVersion())
Expand All @@ -106,6 +114,12 @@ func (s *CallAteletPauseStep) IsComplete(ctx context.Context, input *PauseInput,
// If we are already PAUSED, we've already called Atelet
return state.Actor.GetStatus() == ateapipb.Actor_STATUS_PAUSED, nil
}
func (s *CallAteletPauseStep) CheckPrerequisite(ctx context.Context, input *PauseInput, state *PauseState) error {
if state.Actor.GetStatus() != ateapipb.Actor_STATUS_PAUSING {
return status.Errorf(codes.FailedPrecondition, "CallAteletPauseStep prerequisite not met for Actor: %s (got: %v, want %s)", input.ActorName, state.Actor.GetStatus(), ateapipb.Actor_STATUS_PAUSING)
}
return nil
}
func (s *CallAteletPauseStep) Execute(ctx context.Context, input *PauseInput, state *PauseState) error {
if state.Actor.GetAteomPodNamespace() == "" || state.Actor.GetAteomPodName() == "" {

@dberkov Dmitry Berkovich (dberkov) Jul 10, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a pre-requisite too, however function in current implementation does not support transition to crashActor.

Might be rename the "CheckPrerequisite" to different name? might be allow transition to crash? or might be from the beginning we were not supposed to be in this state, that actor does not have pod or namespace?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should crash the actor here. We can only get here if MarkPausing has succeeded, not having the ateom pod or namespace should crash the actor. I changed the implementation.

if err := crashActor(ctx, s.store, state.Actor.GetMetadata().GetAtespace(), state.Actor.GetMetadata().GetName()); err != nil {
Expand Down Expand Up @@ -157,8 +171,13 @@ type FinalizePausedStep struct {

func (s *FinalizePausedStep) Name() string { return "FinalizePaused" }
func (s *FinalizePausedStep) IsComplete(ctx context.Context, input *PauseInput, state *PauseState) (bool, error) {
// The workflow is completely done ONLY if the status is PAUSED *and* we've successfully freed the worker.
return state.Actor.GetStatus() == ateapipb.Actor_STATUS_PAUSED && state.Actor.GetAteomPodNamespace() == "", nil
return state.Actor.GetStatus() == ateapipb.Actor_STATUS_PAUSED, nil
}
func (s *FinalizePausedStep) CheckPrerequisite(ctx context.Context, input *PauseInput, state *PauseState) error {
if state.Actor.GetStatus() != ateapipb.Actor_STATUS_PAUSING {
return status.Errorf(codes.FailedPrecondition, "FinalizePausedStep prerequisite not met for Actor: %s (got: %v, want %s)", input.ActorName, state.Actor.GetStatus(), ateapipb.Actor_STATUS_PAUSING)
}
return nil
}
func (s *FinalizePausedStep) Execute(ctx context.Context, input *PauseInput, state *PauseState) error {
latestActor, err := s.store.GetActor(ctx, input.Atespace, input.ActorName)
Expand Down
144 changes: 144 additions & 0 deletions cmd/ateapi/internal/controlapi/workflow_pause_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package controlapi

import (
"context"
"testing"

"github.com/agent-substrate/substrate/cmd/ateapi/internal/store/storetest"
"github.com/agent-substrate/substrate/pkg/proto/ateapipb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)

// TestPauseActorWorkflow exercises the pause workflow end-to-end against
// seeded actor statuses, covering both the rejected and the idempotent-success
// paths. The atelet dialer is nil, so any step that unexpectedly reaches it
// panics.
func TestPauseActorWorkflow(t *testing.T) {
Comment thread
zoez7 marked this conversation as resolved.
Outdated
tests := []struct {
name string
seedStatus ateapipb.Actor_Status
// wantErr true means PauseActor must fail with FailedPrecondition.
wantErr bool
// wantStatus is the stored status after the call.
wantStatus ateapipb.Actor_Status
}{
{
// Pausing a SUSPENDED actor is rejected by MarkPausingStep's
// CheckPrerequisite and the actor's status is left untouched.
name: "not running rejected",
seedStatus: ateapipb.Actor_STATUS_SUSPENDED,
wantErr: true,
wantStatus: ateapipb.Actor_STATUS_SUSPENDED,
},
{
// Pausing a PAUSED actor succeeds idempotently via IsComplete
// fast-forward without calling atelet.
name: "already paused succeeds",
seedStatus: ateapipb.Actor_STATUS_PAUSED,
wantStatus: ateapipb.Actor_STATUS_PAUSED,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
st, cleanup := storetest.SetupTestStore(t)
defer cleanup()
w := newTestActorWorkflow(t, st, "ns", "tmpl1")

seedWorkflowActor(t, ctx, st, "team-a", "id1", "ns", "tmpl1", tc.seedStatus)

actor, err := w.PauseActor(ctx, "team-a", "id1")
if tc.wantErr {
if got := status.Code(err); got != codes.FailedPrecondition {
t.Fatalf("status.Code(err) = %v, want %v (err: %v)", got, codes.FailedPrecondition, err)
}
} else {
if err != nil {
t.Fatalf("PauseActor failed: %v", err)
}
if actor.GetStatus() != tc.wantStatus {
t.Errorf("returned status = %v, want %v", actor.GetStatus(), tc.wantStatus)
}
}

got, err := st.GetActor(ctx, "team-a", "id1")
if err != nil {
t.Fatalf("GetActor failed: %v", err)
}
if got.GetStatus() != tc.wantStatus {
t.Errorf("stored status = %v, want %v", got.GetStatus(), tc.wantStatus)
}
})
}
}

// TestPauseSteps_CheckPrerequisite verifies each pause step's CheckPrerequisite
// against every actor status: nil for the step's allowed statuses,
// FailedPrecondition for all others.
func TestPauseSteps_CheckPrerequisite(t *testing.T) {
tests := []struct {
name string
step WorkflowStep[*PauseInput, *PauseState]
// allowed lists the statuses CheckPrerequisite accepts; nil means
// every status is accepted.
allowed map[ateapipb.Actor_Status]bool
}{
{
// Loading has no prerequisite: it is allowed from every status.
name: "LoadActorForPauseStep",
step: &LoadActorForPauseStep{},
allowed: nil,
},
{
// Pausing is allowed only from RUNNING.
name: "MarkPausingStep",
step: &MarkPausingStep{},
allowed: map[ateapipb.Actor_Status]bool{
ateapipb.Actor_STATUS_RUNNING: true,
},
},
{
// The checkpoint call is allowed only from PAUSING (PAUSED is
// fast-forwarded by IsComplete).
name: "CallAteletPauseStep",
step: &CallAteletPauseStep{},
allowed: map[ateapipb.Actor_Status]bool{
ateapipb.Actor_STATUS_PAUSING: true,
},
},
{
// Finalizing is allowed only from PAUSING: a persisted PAUSED
// actor always has its worker pod fields cleared and is
// fast-forwarded by IsComplete.
name: "FinalizePausedStep",
step: &FinalizePausedStep{},
allowed: map[ateapipb.Actor_Status]bool{
ateapipb.Actor_STATUS_PAUSING: true,
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
for _, st := range allActorStatuses {
err := tc.step.CheckPrerequisite(ctx, &PauseInput{ActorName: "id1"}, &PauseState{Actor: &ateapipb.Actor{Status: st}})
assertPrerequisiteResult(t, st, err, tc.allowed == nil || tc.allowed[st])
}
})
}
}
29 changes: 29 additions & 0 deletions cmd/ateapi/internal/controlapi/workflow_resume.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ func (s *LoadActorForResumeStep) IsComplete(ctx context.Context, input *ResumeIn
// Always run this step to get the latest state from the DB
return false, nil
}
func (s *LoadActorForResumeStep) CheckPrerequisite(ctx context.Context, input *ResumeInput, state *ResumeState) error {
return nil
}
func (s *LoadActorForResumeStep) Execute(ctx context.Context, input *ResumeInput, state *ResumeState) error {
actor, err := s.store.GetActor(ctx, input.Atespace, input.ActorName)
if err != nil {
Expand Down Expand Up @@ -113,8 +116,22 @@ type AssignWorkerStep struct {
func (s *AssignWorkerStep) Name() string { return "AssignWorker" }

func (s *AssignWorkerStep) IsComplete(ctx context.Context, input *ResumeInput, state *ResumeState) (bool, error) {
// Only RUNNING is past this step. RESUMING intentionally re-runs because
// a retry must be able to release a stale worker whose pool became
// ineligible and pick a fresh one.
return state.Actor.GetStatus() == ateapipb.Actor_STATUS_RUNNING, nil
}
func (s *AssignWorkerStep) CheckPrerequisite(ctx context.Context, input *ResumeInput, state *ResumeState) error {
// The resume edge exists from SUSPENDED and PAUSED.
// RESUMING is allowed for retrying this step.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is because of line 168 below.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you please clarify what is special at line 168? Is it for cases it was an error in resuming process and we are OK to try resuming one more time?

Same case might happening with Pausing and the CheckPrerequisite for CallAteletPauseStep does not accept pausing state.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated the logic here and stopped allowing resuming state to reenter the AssignWorkerStep. Because setting the state to Resuming is the last step of AssignWorkerStep, if the actor is already in resuming, we know it has completed all the steps and don't need to retry.

On line 168, we would check which worker is assigned and if the worker is no longer eligible, we will pick another one, but this is for cleaning up and doesn't have to be retried during this operation.

switch state.Actor.GetStatus() {
case ateapipb.Actor_STATUS_SUSPENDED, ateapipb.Actor_STATUS_PAUSED, ateapipb.Actor_STATUS_RESUMING:
return nil
default:
return status.Errorf(codes.FailedPrecondition, "AssignWorkerStep prerequisite not met for Actor: %s (got: %v, want %s, %s or %s)", input.ActorName, state.Actor.GetStatus(), ateapipb.Actor_STATUS_SUSPENDED, ateapipb.Actor_STATUS_PAUSED, ateapipb.Actor_STATUS_RESUMING)
}
}

func (s *AssignWorkerStep) Execute(ctx context.Context, input *ResumeInput, state *ResumeState) error {
workers, err := s.workerCache.Workers()
if err != nil {
Expand Down Expand Up @@ -254,6 +271,12 @@ func (s *CallAteletRestoreStep) Name() string { return "CallAteletRestore" }
func (s *CallAteletRestoreStep) IsComplete(ctx context.Context, input *ResumeInput, state *ResumeState) (bool, error) {
return state.Actor.GetStatus() == ateapipb.Actor_STATUS_RUNNING, nil
}
func (s *CallAteletRestoreStep) CheckPrerequisite(ctx context.Context, input *ResumeInput, state *ResumeState) error {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added more checks in CheckPrerequisite to make sure that, if we retry ResumeActor, the Worker assignment and eligibility are still correct for the actor.

if state.Actor.GetStatus() != ateapipb.Actor_STATUS_RESUMING {
return status.Errorf(codes.FailedPrecondition, "CallAteletRestoreStep prerequisite not met for Actor: %s (got: %v, want %s)", input.ActorName, state.Actor.GetStatus(), ateapipb.Actor_STATUS_RESUMING)
}
return nil
}
func (s *CallAteletRestoreStep) Execute(ctx context.Context, input *ResumeInput, state *ResumeState) error {
ateletConn, err := s.dialer.DialForWorker(state.Actor.GetAteomPodNamespace(), state.Actor.GetAteomPodName())
if err != nil {
Expand Down Expand Up @@ -358,6 +381,12 @@ func (s *FinalizeRunningStep) Name() string { return "FinalizeRunning" }
func (s *FinalizeRunningStep) IsComplete(ctx context.Context, input *ResumeInput, state *ResumeState) (bool, error) {
return state.Actor.GetStatus() == ateapipb.Actor_STATUS_RUNNING, nil
}
func (s *FinalizeRunningStep) CheckPrerequisite(ctx context.Context, input *ResumeInput, state *ResumeState) error {
if state.Actor.GetStatus() != ateapipb.Actor_STATUS_RESUMING {
return status.Errorf(codes.FailedPrecondition, "FinalizeRunningStep prerequisite not met for Actor: %s (got: %v, want %s)", input.ActorName, state.Actor.GetStatus(), ateapipb.Actor_STATUS_RESUMING)
}
return nil
}
func (s *FinalizeRunningStep) Execute(ctx context.Context, input *ResumeInput, state *ResumeState) error {
latestActor, err := s.store.GetActor(ctx, input.Atespace, input.ActorName)
if err != nil {
Expand Down
Loading
Loading