Skip to content

SuspendTask reports success and persists Suspended when Substrate suspension fails #441

Closed

Description

@rich7420

Problem

SuspendTask returns a successful gRPC response and stores phase: Suspended when Substrate's SuspendActor RPC fails. It also clears the recorded worker IP and writes Ready=False with reason TaskSuspended, even though the actor has not been suspended.

This can cause a caller to believe execution has stopped while the actor is still running.

Environment and scope

  • AX main at ac2332829f22360ff97b0ba34d94dd0dd782f17e.
  • Go 1.27.1, macOS/arm64.
  • Executed locally through the AX gRPC API, the real Task reconciler and Substrate client, an in-process mock Substrate gRPC server, and the in-memory store.
  • No real Kubernetes cluster, sandbox, or Redis was used. The mock models a suspension rejected without changing the actor's running state.

Reproduction

  1. Seed a running Task in the store, with worker IP 10.244.1.42 and Ready=True.
  2. Provide an existing running actor and template through the mock Substrate API, so preceding reconciliation calls succeed.
  3. Make SuspendActor return codes.Unavailable or codes.PermissionDenied, leaving the mock actor running.
  4. Call SuspendTask over gRPC, then read the stored Task and inspect the mock actor state.

Save the test below as internal/server/suspend_failure_test.go and run:

go test -race -count=1 -v -run '^TestSuspendTask_SubstrateResult$' ./internal/server

Actual result

Both injected failures returned OK from the AX API and persisted a successful suspension:

substrate_code=Unavailable api_code=OK response_phase="Suspended" stored_phase="Suspended" stored_worker_ip="" actor_state=ACTOR_STATE_RUNNING suspend_calls=1
substrate_code=PermissionDenied api_code=OK response_phase="Suspended" stored_phase="Suspended" stored_worker_ip="" actor_state=ACTOR_STATE_RUNNING suspend_calls=1

The log contains could not suspend actor on Substrate, followed by task successfully suspended.

The successful-suspension control case passed. The two regression cases failed on the current code, checking the API error, stored phase, worker IP, and suspension condition. Existing server tests passed separately:

go test -race -count=1 -skip '^TestSuspendTask_SubstrateResult$' ./internal/server
# ok github.com/google/ax/internal/server

Expected result

AX should surface the suspension error and avoid recording a confirmed Suspended state when suspension was rejected. In this reproduction, the actor remains running, so its stored running state and worker IP should remain intact.

For ambiguous timeout or cancellation failures, the actual actor state may need to be checked; this reproduction does not establish that every failed RPC leaves an actor running.

Cause and proposed scope

Client.SuspendActor propagates the RPC error, but the suspend branch of TaskReconciler.Reconcile only logs it and returns task, nil after setting the suspended status. Server.SuspendTask consequently persists the status and returns success.

A focused fix would propagate genuine suspension failures and only persist confirmed lifecycle results. Coverage should include successful suspension, rejected suspension, already suspended actors, and Task creation, since creation shares this reconciliation branch.

The pinned Substrate implementation already returns success for an already suspended actor; repeated suspension should retain that behavior.

Related: #433, Task-to-Actor lifecycle alignment.

Complete regression test
// 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 server_test

import (
	"context"
	"net"
	"sync/atomic"
	"testing"
	"time"

	"github.com/agent-substrate/substrate/pkg/proto/ateapipb"
	"github.com/google/ax/internal/controller"
	"github.com/google/ax/internal/server"
	"github.com/google/ax/internal/store/memory"
	"github.com/google/ax/internal/substrate"
	"github.com/google/ax/pkg/apis/v1alpha1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)

// The actor and its template already exist. Failed suspension leaves the actor
// running, so the test isolates error propagation rather than provisioning.
type suspendFailureControl struct {
	ateapipb.UnimplementedControlServer
	suspendError error
	suspendCalls atomic.Int32
	actorState   atomic.Int32
}

func (m *suspendFailureControl) CreateAtespace(context.Context, *ateapipb.CreateAtespaceRequest) (*ateapipb.Atespace, error) {
	return nil, status.Error(codes.AlreadyExists, "atespace exists")
}

func (m *suspendFailureControl) GetActorTemplate(_ context.Context, req *ateapipb.GetActorTemplateRequest) (*ateapipb.ActorTemplate, error) {
	ref := req.GetActorTemplate()
	return &ateapipb.ActorTemplate{Metadata: &ateapipb.ResourceMetadata{
		Name: ref.GetName(), Atespace: ref.GetAtespace(),
	}}, nil
}

func (m *suspendFailureControl) CreateActor(context.Context, *ateapipb.CreateActorRequest) (*ateapipb.Actor, error) {
	return nil, status.Error(codes.AlreadyExists, "actor exists")
}

func (m *suspendFailureControl) GetActor(_ context.Context, req *ateapipb.GetActorRequest) (*ateapipb.Actor, error) {
	ref := req.GetActor()
	return &ateapipb.Actor{
		Metadata: &ateapipb.ResourceMetadata{Name: ref.GetName(), Atespace: ref.GetAtespace()},
		Status: &ateapipb.ActorStatus{
			State:            ateapipb.ActorState(m.actorState.Load()),
			WorkerAssignment: &ateapipb.WorkerAssignment{WorkerPodIp: "10.244.1.42"},
		},
	}, nil
}

func (m *suspendFailureControl) SuspendActor(context.Context, *ateapipb.SuspendActorRequest) (*ateapipb.SuspendActorResponse, error) {
	m.suspendCalls.Add(1)
	if m.suspendError != nil {
		return nil, m.suspendError
	}
	m.actorState.Store(int32(ateapipb.ActorState_ACTOR_STATE_SUSPENDED))
	return &ateapipb.SuspendActorResponse{}, nil
}

func TestSuspendTask_SubstrateResult(t *testing.T) {
	for _, tc := range []struct {
		name string
		code codes.Code
	}{
		{name: "success", code: codes.OK},
		{name: "unavailable", code: codes.Unavailable},
		{name: "permission_denied", code: codes.PermissionDenied},
	} {
		t.Run(tc.name, func(t *testing.T) {
			ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()
			mock := &suspendFailureControl{}
			mock.actorState.Store(int32(ateapipb.ActorState_ACTOR_STATE_RUNNING))
			if tc.code != codes.OK {
				mock.suspendError = status.Error(tc.code, "injected suspension failure")
			}
			dialOptions := func(listener *bufconn.Listener) []grpc.DialOption {
				return []grpc.DialOption{
					grpc.WithTransportCredentials(insecure.NewCredentials()),
					grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
						return listener.DialContext(ctx)
					}),
				}
			}
			substrateListener := bufconn.Listen(1024 * 1024)
			defer substrateListener.Close()
			substrateServer := grpc.NewServer()
			ateapipb.RegisterControlServer(substrateServer, mock)
			go substrateServer.Serve(substrateListener)
			defer substrateServer.Stop()
			substrateClient, err := substrate.NewClient("passthrough:///substrate", dialOptions(substrateListener)...)
			if err != nil {
				t.Fatal(err)
			}
			defer substrateClient.Close()
			reconciler := controller.NewTaskReconciler(substrateClient, "test-template", "ax-system")
			reconciler.SecretResolver = func(context.Context, string, string, string) (string, error) {
				return "", nil
			}
			store := memory.NewStore()
			defer store.Close()
			if err := store.SaveTask(ctx, &v1alpha1.Task{
				Metadata: &v1alpha1.ObjectMeta{Name: "suspend-repro", Atespace: "default"},
				Spec:     &v1alpha1.TaskSpec{Image: "example.invalid/runner@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
				Status: &v1alpha1.TaskStatus{
					Phase: "Running", Actor: "suspend-repro", Id: "existing-task-id", WorkerIp: "10.244.1.42",
					Conditions: []*v1alpha1.Condition{{Type: "Ready", Status: "True", Reason: "TaskRunning"}},
				},
			}); err != nil {
				t.Fatal(err)
			}
			axServer := server.NewServer(store, server.Options{Reconciler: reconciler})
			axListener := bufconn.Listen(1024 * 1024)
			defer axListener.Close()
			go axServer.GRPCServer().Serve(axListener)
			defer axServer.GRPCServer().Stop()
			axConn, err := grpc.NewClient("passthrough:///ax", dialOptions(axListener)...)
			if err != nil {
				t.Fatal(err)
			}
			defer axConn.Close()
			response, rpcErr := v1alpha1.NewAXClient(axConn).SuspendTask(ctx, &v1alpha1.SuspendTaskRequest{
				Atespace: "default", Name: "suspend-repro",
			})
			stored, err := store.GetTask(ctx, "default", "suspend-repro")
			if err != nil {
				t.Fatal(err)
			}
			actorState := ateapipb.ActorState(mock.actorState.Load())
			t.Logf("substrate_code=%s api_code=%s response_phase=%q stored_phase=%q stored_worker_ip=%q actor_state=%s suspend_calls=%d",
				tc.code, status.Code(rpcErr), response.GetStatus().GetPhase(), stored.GetStatus().GetPhase(),
				stored.GetStatus().GetWorkerIp(), actorState, mock.suspendCalls.Load())
			if mock.suspendCalls.Load() != 1 {
				t.Fatalf("SuspendActor calls = %d, want 1", mock.suspendCalls.Load())
			}
			if tc.code == codes.OK {
				if rpcErr != nil || stored.GetStatus().GetPhase() != "Suspended" || stored.GetStatus().GetWorkerIp() != "" {
					t.Fatalf("successful suspension: error=%v, status=%v", rpcErr, stored.GetStatus())
				}
				if actorState != ateapipb.ActorState_ACTOR_STATE_SUSPENDED {
					t.Fatalf("successful suspension left actor in %s", actorState)
				}
				return
			}
			if actorState != ateapipb.ActorState_ACTOR_STATE_RUNNING {
				t.Fatalf("fault injection changed actor state to %s", actorState)
			}
			if rpcErr == nil {
				t.Error("SuspendTask returned success after Substrate rejected suspension")
			}
			if stored.GetStatus().GetPhase() != "Running" {
				t.Errorf("stored phase = %q, want Running after rejected suspension", stored.GetStatus().GetPhase())
			}
			if stored.GetStatus().GetWorkerIp() != "10.244.1.42" {
				t.Errorf("stored worker IP = %q, want original worker IP", stored.GetStatus().GetWorkerIp())
			}
			for _, condition := range stored.GetStatus().GetConditions() {
				if condition.GetReason() == "TaskSuspended" {
					t.Error("stored condition reports TaskSuspended after rejected suspension")
				}
			}
		})
	}
}

Activity

  1. rich7420 commented on Sep 30, 2026

    @rich7420
    ContributorAuthor

    @rakyll I'd like to contribute a focused fix for this, aligned with the lifecycle work in #433.

    The attached gRPC regression test reproduces the false success for both Unavailable and PermissionDenied; successful suspension and the existing server tests pass. My proposed patch would propagate suspension failures and avoid persisting an unconfirmed suspended state, with coverage for repeated suspension and initial Task creation as well.

    Does that scope fit the current lifecycle direction? Since PR creation appears restricted, what submission route should I use once the patch is ready?

  2. aetherxeg-source commented on Oct 2, 2026

    @aetherxeg-source

    The core invariant here looks like requested lifecycle transition != confirmed lifecycle transition.

    "SuspendTask" should not commit "Suspended" merely because the reconciliation path reached the suspension branch. The persisted state should be derived from evidence that the authoritative actor transition actually completed.

    I would model the transition more explicitly as:

    "requested -> dispatched -> confirmed"
    with separate outcomes for
    "rejected", "unknown", and "confirmed".

    In particular, an RPC error such as "PermissionDenied" is a confirmed rejection, while timeout/cancellation may be an unknown outcome and require reconciliation against the actor's observed state before committing either "Running" or "Suspended".

    A strong regression matrix would include:

    • successful suspend -> persist "Suspended";
    • explicit provider rejection -> preserve prior confirmed running state;
    • already-suspended -> idempotent success;
    • timeout after dispatch -> do not infer either state until reconciled;
    • retry after an unknown result -> avoid issuing a second effect blindly unless the operation is proven idempotent or the current actor state is first checked.

    The important property is:

    a control-plane intent must not become an authoritative runtime fact without effect confirmation.

    That also prevents downstream consumers from treating cleared worker identity / "Ready=False" as evidence that execution has actually stopped when the actor may still be running.

  3. rich7420 commented on Oct 2, 2026

    @rich7420
    ContributorAuthor

    Thanks @aetherxeg-source. I tested this on ac23328. After timeout/cancellation, AX still stores Suspended without checking actor state, even when the mock actor is still runing.

    Canceling the AX RPC after dispatch gives:

    api_code=Canceled handler_code=OK stored_phase="Suspended"
    actor_state=ACTOR_STATE_RUNNING reads_after_dispatch=0
    

    Already-suspended and retry controls pass; retry reads the actor first. These were -race tests with mock Substrate and the in-memory store. I haven't tested Redis or a live cluster.

  4. aetherxeg-source commented on Oct 3, 2026

    @aetherxeg-source

    Thanks — that result isolates the unsafe transition very clearly.

    The critical observation is:

    "stored_phase="Suspended"" while "actor_state=ACTOR_STATE_RUNNING"

    which means the control-plane state has become more authoritative than the runtime evidence after an indeterminate effect outcome.

    I would make timeout/cancellation after dispatch enter an explicit unknown/reconciliation state rather than committing either terminal interpretation.

    Something like:

    "SuspendRequested -> Dispatched -> OutcomeUnknown -> ReconciledRunning | ReconciledSuspended"

    A useful next regression would be:

    1. dispatch suspend;
    2. force timeout/cancellation after the effect may have reached the actor;
    3. verify no "Suspended" state is persisted yet;
    4. require an authoritative actor-state read;
    5. persist "Suspended" only if the actor confirms suspension;
    6. otherwise preserve/recover the confirmed running state.

    It would also be useful to assert that retry from "OutcomeUnknown" performs reconciliation before issuing another suspend effect, so an ambiguous first attempt cannot silently become a duplicate effect.

    The invariant becomes:

    "unknown effect outcome must remain unknown until runtime evidence resolves it"

    That would prevent downstream consumers from treating a control-plane write as proof that execution has actually stopped.

    Related runtime-verification work:
    https://github.com/AETHERXGLOBAL/execsurface

  5. self-assigned this
    on Oct 13, 2026
  6. rich7420 commented on Oct 13, 2026

    @rich7420
    ContributorAuthor

    @YoyinZyc I'd like to work on the fix for this issue. I opened the report and have regression tests ready. Have you started an implementation, or would you be happy for me to take it on?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions