diff --git a/docs/architecture/runtime-and-lifecycle.md b/docs/architecture/runtime-and-lifecycle.md index 9c6fec8f15..dfcd7a7705 100644 --- a/docs/architecture/runtime-and-lifecycle.md +++ b/docs/architecture/runtime-and-lifecycle.md @@ -153,6 +153,22 @@ changing it creates a new ActorTemplate. Pausing for INPUT_REQUIRED/AUTH_REQUIRE is always Full, regardless of this field. Forking requires a Data checkpoint, so a checkpoint whose snapshot is Full cannot be forked. +The workflow reads `SnapshotConfig.OnCommit` from the prepared revision's pinned +ActorTemplate and verifies its name, atespace, and UID. Automatic quiescence and +explicit suspension that captures runtime state require the returned external +snapshot to match that scope and template UID. An unclaimed explicit suspension +of an already SUSPENDED Actor verifies its lifecycle identity and atomically +settles without claiming or issuing runtime work. A newly created Actor may have +no snapshot or borrow golden FULL state even under an OnCommit DATA policy. +Once a suspension has been claimed, its durable executor ID marks possibly issued +capture. Every retry validates the captured snapshot, even if the Actor is now +SUSPENDED; invalid capture retains the operation fence. Completed task boundaries +always retain strict Quiesce validation. Checkpoint Tags preserve the recorded scope; +they accept either DATA or FULL. Same-Actor resume delegates snapshot restoration +to Substrate. The DATA restriction applies to creating a new Actor from a +checkpoint, because a FULL fork would restore the source process state and +runtime identity. + Unfinished native cleanup blocks new task writes and explicit lifecycle changes. After publication, a new turn may supersede idle work before it is claimed. Once claimed, idle work blocks new execution, explicit lifecycle changes, and checkpoint @@ -167,6 +183,90 @@ claims still block new work, but completed results remain readable. The recorded actor UID is checked before lifecycle calls; a same-name replacement cannot be adopted implicitly. +### Recovering a claim held after snapshot scope rejection + +An older controller could successfully suspend an Actor with an `onQuiesce: Full` +policy, then reject its FULL snapshot and leave its task boundary claimed. Merely +restarting the controller does not release that claim. No claim-expiry migration +is required for the scope fix, and a timeout does not authorize takeover. + +For this specific failure, an operator must: + +1. Hold dispatch and lifecycle traffic for the affected Sessions, including queued + requests, until step 6 verifies their original boundaries. Clearing the executor + reopens admission before the idle worker claims; a new task could supersede + unclaimed idle work without recording its snapshot. + Stop all controller replicas through GitOps and verify their workers have + exited. Do not release claims while a worker could still issue runtime work. +2. Read the affected Session's pinned revision and generation, then observe the + Substrate Actor and ActorTemplate. Require the recorded Actor UID, SUSPENDED + state, a nonempty external snapshot URI, and the pinned template UID/scope. + A missing/replaced Actor, SUSPENDING state, or mismatched scope is unresolved + work; leave its claim fenced. Record the observed snapshot atespace, URI, and + scope (DATA or FULL). Correlate the terminal task ID and event sequence with the + original scope-rejection log; these identify the boundary to recover. +3. Read the claim using the affected Session ID (psql variable `session_id`). + Confirm its task ID and sequence identify the original rejected boundary: + + ```sql + SELECT e.task_id, e.sequence, e.quiescence_executor_id + FROM session_task_event e + JOIN session_record s ON s.history_id = e.history_id + WHERE s.id = :'session_id'::uuid + AND s.state = 'RUNTIME_STATE_READY' + AND s.operation = 'RUNTIME_OPERATION_NONE' + AND e.published AND e.quiescence_pending = TRUE + AND e.quiescence_executor_id IS NOT NULL; + ``` + +4. Release only that executor's claim, using the observed `sequence` and + `executor_id` as psql variables. Require exactly one returned row: + + ```sql + UPDATE session_task_event e SET quiescence_executor_id = NULL + FROM session_record s + WHERE s.history_id = e.history_id AND s.id = :'session_id'::uuid + AND s.state = 'RUNTIME_STATE_READY' + AND s.operation = 'RUNTIME_OPERATION_NONE' + AND e.sequence = :'sequence'::bigint + AND e.quiescence_executor_id = :'executor_id'::uuid + AND e.published AND e.quiescence_pending = TRUE + RETURNING e.sequence; + ``` + +5. Start the fixed controller through GitOps. Its idle worker claims the same + boundary and validates the already suspended snapshot without another suspend + request. It stores the snapshot and clears `quiescence_pending` atomically. +6. Keep traffic held while verifying that exact terminal task and event sequence. + Using the recorded `task_id`, `sequence`, `snapshot_atespace`, `snapshot_uri`, + and `snapshot_scope` as psql variables, require exactly one returned row: + + ```sql + SELECT e.task_id, e.sequence, t.history_sequence, e.quiescence_executor_id + FROM session_record s + JOIN session_task_event e ON e.history_id = s.history_id + JOIN session_task t ON t.history_id = e.history_id AND t.id = e.task_id + WHERE s.id = :'session_id'::uuid + AND e.task_id = :'task_id' AND e.sequence = :'sequence'::bigint + AND e.published AND e.quiescence_pending = FALSE + AND t.history_sequence = e.sequence + AND e.snapshot_atespace = :'snapshot_atespace' + AND t.snapshot_atespace = e.snapshot_atespace + AND e.snapshot_uri = :'snapshot_uri' AND t.snapshot_uri = e.snapshot_uri + AND e.snapshot_content_scope = :'snapshot_scope' + AND t.snapshot_content_scope = e.snapshot_content_scope; + ``` + + `quiescence_pending=FALSE` alone is insufficient: superseded idle work also has + that value without a snapshot. Successful finish retains the new executor ID; + it need not be NULL. Restore traffic only after the original task/event's exact + snapshot and matching `history_sequence` are recorded. Then retry SuspendSession + or checkpoint creation. + +This procedure changes neither task history nor snapshot scope. It is an operator +recovery procedure, not an automatic adoption API. The controller continues to +reject mismatched snapshots and preserves the claim when verification fails. + ```mermaid sequenceDiagram participant Client diff --git a/docs/architecture/runtime-generation-identity.md b/docs/architecture/runtime-generation-identity.md index 8fbe6bd2dc..fbc2ddfb12 100644 --- a/docs/architecture/runtime-generation-identity.md +++ b/docs/architecture/runtime-generation-identity.md @@ -47,8 +47,9 @@ source authority is never inherited. A fresh eligible Session deleted before ledger allocation can complete database-only deletion; it has issued no runtime effects. Unledgered pre-cutover rows have no such provenance. Resume preserves the same UID/generation. There is no automatic same-Session Actor replacement, old-session migration, -legacy enrollment or Full process-memory restore. Quiescence/checkpoint creation -requires DATA state. An uncertain original issuance is deliberately unavailable +legacy enrollment or Full checkpoint forks. Same-Actor resume supports both DATA +and FULL state. Quiescence verifies the snapshot scope configured by the pinned +ActorTemplate; checkpoint creation retains that exact scope. An uncertain original issuance is deliberately unavailable until separately reviewed reconciliation; source preparation does not add an operator recovery/adoption API. diff --git a/go/core/internal/database/session_operations.go b/go/core/internal/database/session_operations.go index f8076cd7a4..ad830ae756 100644 --- a/go/core/internal/database/session_operations.go +++ b/go/core/internal/database/session_operations.go @@ -112,13 +112,13 @@ func (c *Client) ClaimSessionOperation(ctx context.Context, sessionID string, id return c.claimRuntimeOperation(ctx, sessionID, runtimeKindAgent, id, executorID) } -// FinishSessionOperation publishes known success only for the claiming -// executor. A nonempty failure releases only unclaimed preparation and invalidates -// its generation. Uncertain issued work must remain pending. Stale completion or -// release returns ErrConflict. Deletion revokes shares and releases resource -// pins atomically. Explicit deletion retains a tombstone; idle deletion also -// removes the session and creation receipt in this transaction. -func (c *Client) FinishSessionOperation(ctx context.Context, sessionID string, id, executorID uuid.UUID, authority, actorUID, failure string) (*apiv1alpha1.Session, error) { +// FinishObservedSessionSuspension settles a verified already-suspended Actor +// without granting permission to issue runtime work. The caller observes the +// Actor outside this transaction. Under the Session then generation locks, the +// operation must still be the same never-claimed READY/SUSPEND, with the same +// prepared revision and active Actor UID. A concurrent claim or supersession +// returns ErrConflict; callers reconcile completed work through Begin/Get. +func (c *Client) FinishObservedSessionSuspension(ctx context.Context, sessionID string, id uuid.UUID, preparedRevision, actorUID string) (*apiv1alpha1.Session, error) { var result *apiv1alpha1.Session err := c.withTx(ctx, func(tx pgx.Tx) error { row, err := lockSession(ctx, tx, sessionID) @@ -128,65 +128,58 @@ func (c *Client) FinishSessionOperation(ctx context.Context, sessionID string, i if err != nil { return err } - next, err := completeRuntimeOperation(row.runtimeInstanceRow, id, executorID, failure) - if err != nil { - return err - } - result, err = toSession(row) - if err != nil { - return err + if id == uuid.Nil || row.OperationID == nil || *row.OperationID != id || row.ExecutorID != nil || + row.State != apiv1alpha1.RuntimeState_RUNTIME_STATE_READY.String() || + row.Operation != apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_SUSPEND.String() || + preparedRevision == "" || derefStr(row.PreparedRevision) != preparedRevision || actorUID == "" { + return ErrConflict } - if failure == "" { - switch result.Operation { - case apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_CREATE: - if authority == "" || actorUID == "" { - return fmt.Errorf("created Session requires runtime authority and actor UID") - } - result.A2AAuthority = authority - case apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_DELETE: - result.A2AAuthority = "" - if err := releaseAgentRuntimeReferences(ctx, tx, row.ID); err != nil { - return err - } - } + uid, err := queryOne(ctx, tx, ` + SELECT actor_uid FROM runtime_generation WHERE session_id = $1 AND phase = 'active' FOR UPDATE + `, pgx.RowTo[string], row.ID) + if errors.Is(err, pgx.ErrNoRows) { + return ErrConflict } - result.State, result.Operation, err = next.lifecycle() if err != nil { return err } - result.PreparedRevision = derefStr(next.PreparedRevision) - result.UpdatedAt = timestamppb.Now() - result.Failure = nil - if failure != "" { - result.Failure = &apiv1alpha1.Failure{Reason: "PreparationFailed", Message: failure} - } - row.Data, err = marshalSession(result) - if err != nil { - return err + if uid != actorUID { + return ErrConflict } - if err := saveRuntimeLifecycle(ctx, tx, next, runtimeKindAgent); err != nil { - return err + next := row.runtimeInstanceRow + next.State = apiv1alpha1.RuntimeState_RUNTIME_STATE_SUSPENDED.String() + next.Operation = apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_NONE.String() + result, err = persistSessionOperationResult(ctx, tx, row, next, "", actorUID, "") + return err + }) + if err != nil { + return nil, fmt.Errorf("finish observed Session suspension: %w", err) + } + return result, nil +} + +// FinishSessionOperation publishes known success only for the claiming +// executor. A nonempty failure releases only unclaimed preparation and invalidates +// its generation. Uncertain issued work must remain pending. Stale completion or +// release returns ErrConflict. Deletion revokes shares and releases resource +// pins atomically. Explicit deletion retains a tombstone; idle deletion also +// removes the session and creation receipt in this transaction. +func (c *Client) FinishSessionOperation(ctx context.Context, sessionID string, id, executorID uuid.UUID, authority, actorUID, failure string) (*apiv1alpha1.Session, error) { + var result *apiv1alpha1.Session + err := c.withTx(ctx, func(tx pgx.Tx) error { + row, err := lockSession(ctx, tx, sessionID) + if errors.Is(err, pgx.ErrNoRows) { + return ErrConflict } - tag, err := tx.Exec(ctx, ` - UPDATE session SET data = $2, - actor_uid = CASE WHEN $4 THEN $3 ELSE actor_uid END - WHERE id = $1 AND ($3::text = '' OR actor_uid = $3 OR (actor_uid IS NULL AND $4)) - `, row.ID, row.Data, actorUID, failure == "" && row.Operation == apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_CREATE.String()) if err != nil { return err } - if tag.RowsAffected() != 1 { - return fmt.Errorf("runtime actor UID changed: %w", ErrConflict) - } - row.runtimeInstanceRow = next - result, err = toSession(row) + next, err := completeRuntimeOperation(row.runtimeInstanceRow, id, executorID, failure) if err != nil { return err } - if result.State == apiv1alpha1.RuntimeState_RUNTIME_STATE_DELETED && failure == "" { - return finishSessionDeletion(ctx, tx, row.ID) - } - return nil + result, err = persistSessionOperationResult(ctx, tx, row, next, authority, actorUID, failure) + return err }) if err != nil { return nil, fmt.Errorf("finish Session operation: %w", err) @@ -194,6 +187,68 @@ func (c *Client) FinishSessionOperation(ctx context.Context, sessionID string, i return result, nil } +// persistSessionOperationResult publishes lifecycle and Session data together. +// The caller holds the Session lock and has verified completion authority. +func persistSessionOperationResult(ctx context.Context, tx pgx.Tx, row sessionRow, next runtimeInstanceRow, authority, actorUID, failure string) (*apiv1alpha1.Session, error) { + result, err := toSession(row) + if err != nil { + return nil, err + } + if failure == "" { + switch result.Operation { + case apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_CREATE: + if authority == "" || actorUID == "" { + return nil, fmt.Errorf("created Session requires runtime authority and actor UID") + } + result.A2AAuthority = authority + case apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_DELETE: + result.A2AAuthority = "" + if err := releaseAgentRuntimeReferences(ctx, tx, row.ID); err != nil { + return nil, err + } + } + } + result.State, result.Operation, err = next.lifecycle() + if err != nil { + return nil, err + } + result.PreparedRevision = derefStr(next.PreparedRevision) + result.UpdatedAt = timestamppb.Now() + result.Failure = nil + if failure != "" { + result.Failure = &apiv1alpha1.Failure{Reason: "PreparationFailed", Message: failure} + } + row.Data, err = marshalSession(result) + if err != nil { + return nil, err + } + if err := saveRuntimeLifecycle(ctx, tx, next, runtimeKindAgent); err != nil { + return nil, err + } + tag, err := tx.Exec(ctx, ` + UPDATE session SET data = $2, + actor_uid = CASE WHEN $4 THEN $3 ELSE actor_uid END + WHERE id = $1 AND ($3::text = '' OR actor_uid = $3 OR (actor_uid IS NULL AND $4)) + `, row.ID, row.Data, actorUID, failure == "" && row.Operation == apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_CREATE.String()) + if err != nil { + return nil, err + } + if tag.RowsAffected() != 1 { + return nil, fmt.Errorf("runtime actor UID changed: %w", ErrConflict) + } + row.runtimeInstanceRow = next + result, err = toSession(row) + if err != nil { + return nil, err + } + if result.State == apiv1alpha1.RuntimeState_RUNTIME_STATE_DELETED && failure == "" { + if err := finishSessionDeletion(ctx, tx, row.ID); err != nil { + return nil, err + } + } + return result, nil +} + // GetSessionOperation observes this generation only while it remains current, // including its deletion tombstone. A superseded or missing generation returns // ErrConflict. Callers must have authorized the session at admission. It never diff --git a/go/core/internal/database/session_operations_test.go b/go/core/internal/database/session_operations_test.go index e2a43c8d47..9c98625216 100644 --- a/go/core/internal/database/session_operations_test.go +++ b/go/core/internal/database/session_operations_test.go @@ -1,13 +1,201 @@ package database import ( + "context" "testing" + "time" "github.com/google/uuid" apiv1alpha1 "github.com/kagent-dev/kagent/go/api/gen/kagent/api/v1alpha1" "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" ) +func observedSuspensionFixture(t *testing.T) (*Client, *SessionOperation, *RuntimeGeneration) { + t.Helper() + client, session, generation := generationFixture(t) + activateGeneration(t, client, generation) + creation, err := client.BeginSessionOperation(t.Context(), session.Id, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_CREATE) + require.NoError(t, err) + executor := uuid.New() + claimed, err := client.ClaimSessionOperation(t.Context(), session.Id, creation.ID, executor) + require.NoError(t, err) + require.True(t, claimed) + _, err = client.FinishSessionOperation(t.Context(), session.Id, creation.ID, executor, "runtime.example", generation.ActorUID, "") + require.NoError(t, err) + operation, err := client.BeginSessionOperation(t.Context(), session.Id, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_SUSPEND) + require.NoError(t, err) + return client, operation, generation +} + +func TestFinishObservedSessionSuspension(t *testing.T) { + client, operation, generation := observedSuspensionFixture(t) + _, err := client.UpdateSessionName(t.Context(), operation.Instance.Id, "alice", "renamed during observation") + require.NoError(t, err) + finished, err := client.FinishObservedSessionSuspension(t.Context(), operation.Instance.Id, operation.ID, operation.Instance.PreparedRevision, generation.ActorUID) + require.NoError(t, err) + require.Equal(t, "renamed during observation", finished.Name) + require.Equal(t, apiv1alpha1.RuntimeState_RUNTIME_STATE_SUSPENDED, finished.State) + require.Equal(t, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_NONE, finished.Operation) + require.Equal(t, operation.Instance.A2AAuthority, finished.A2AAuthority) + // Reconcile a lost completion reply through admission, without a new claim. + observed, err := client.BeginSessionOperation(t.Context(), finished.Id, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_SUSPEND) + require.NoError(t, err) + require.Equal(t, operation.ID, observed.ID) + require.Equal(t, uuid.Nil, observed.ExecutorID) + require.True(t, proto.Equal(finished, observed.Instance)) + claimed, err := client.ClaimSessionOperation(t.Context(), finished.Id, operation.ID, uuid.New()) + require.NoError(t, err) + require.False(t, claimed) + _, err = client.FinishObservedSessionSuspension(t.Context(), finished.Id, operation.ID, finished.PreparedRevision, generation.ActorUID) + require.ErrorIs(t, err, ErrConflict, "direct stale completion is not new authority") +} + +func TestObservedSessionSuspensionRejectsChangedAuthority(t *testing.T) { + for _, name := range []string{"nil operation", "stale operation", "wrong revision", "empty revision", "wrong Actor UID", "empty Actor UID", "claimed", "released claim", "superseded by delete", "revoked generation", "Session UID changed"} { + t.Run(name, func(t *testing.T) { + client, operation, generation := observedSuspensionFixture(t) + id, revision, uid := operation.ID, operation.Instance.PreparedRevision, generation.ActorUID + switch name { + case "nil operation": + id = uuid.Nil + case "stale operation": + id = uuid.New() + case "wrong revision": + revision = "different-revision" + case "empty revision": + revision = "" + case "wrong Actor UID": + uid = "replacement-actor" + case "empty Actor UID": + uid = "" + case "claimed", "released claim": + executor := uuid.New() + claimed, err := client.ClaimSessionOperation(t.Context(), operation.Instance.Id, id, executor) + require.NoError(t, err) + require.True(t, claimed) + if name == "released claim" { + require.NoError(t, client.ReleaseRuntimeOperation(t.Context(), operation.Instance.Id, id, executor)) + } + case "superseded by delete": + deletion, err := client.BeginSessionOperation(t.Context(), operation.Instance.Id, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_DELETE) + require.NoError(t, err) + id = deletion.ID // Even a current ID cannot finish the wrong kind. + case "revoked generation": + require.NoError(t, client.RevokeRuntimeGeneration(t.Context(), operation.Instance.Id)) + case "Session UID changed": + _, err := client.db.Exec(t.Context(), `UPDATE session SET actor_uid = 'replacement-actor' WHERE id = $1`, operation.Instance.Id) + require.NoError(t, err) + } + kind := apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_SUSPEND + if name == "superseded by delete" { + kind = apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_DELETE + } + before, err := client.BeginSessionOperation(t.Context(), operation.Instance.Id, kind) + require.NoError(t, err) + _, err = client.FinishObservedSessionSuspension(t.Context(), operation.Instance.Id, id, revision, uid) + require.ErrorIs(t, err, ErrConflict) + after, err := client.GetSessionOperation(t.Context(), operation.Instance.Id, before.ID) + require.NoError(t, err) + require.Equal(t, before.ID, after.ID) + require.Equal(t, before.ExecutorID, after.ExecutorID) + require.Equal(t, before.SourceCheckpointID, after.SourceCheckpointID) + require.True(t, proto.Equal(before.Instance, after.Instance), "a rejected observation must retain lifecycle data, including after a late SQL predicate failure") + }) + } +} + +func TestObservedSessionSuspensionRollsBackDatabaseFailure(t *testing.T) { + client, operation, generation := observedSuspensionFixture(t) + _, err := client.db.Exec(t.Context(), ` + CREATE FUNCTION reject_observed_suspension() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION 'injected Session write failure'; END $$; + CREATE TRIGGER reject_observed_suspension BEFORE UPDATE ON session + FOR EACH ROW EXECUTE FUNCTION reject_observed_suspension() + `) + require.NoError(t, err) + t.Cleanup(func() { + _, _ = client.db.Exec(context.Background(), `DROP TRIGGER IF EXISTS reject_observed_suspension ON session; DROP FUNCTION IF EXISTS reject_observed_suspension()`) + }) + _, err = client.FinishObservedSessionSuspension(t.Context(), operation.Instance.Id, operation.ID, operation.Instance.PreparedRevision, generation.ActorUID) + require.ErrorContains(t, err, "injected Session write failure") + held, err := client.GetSessionOperation(t.Context(), operation.Instance.Id, operation.ID) + require.NoError(t, err) + require.Equal(t, operation.ID, held.ID) + require.Equal(t, uuid.Nil, held.ExecutorID) + require.Equal(t, operation.SourceCheckpointID, held.SourceCheckpointID) + require.True(t, proto.Equal(operation.Instance, held.Instance), "the earlier runtime lifecycle update must roll back with the Session write") + _, err = client.db.Exec(t.Context(), `DROP TRIGGER reject_observed_suspension ON session; DROP FUNCTION reject_observed_suspension()`) + require.NoError(t, err) + _, err = client.FinishObservedSessionSuspension(t.Context(), operation.Instance.Id, operation.ID, operation.Instance.PreparedRevision, generation.ActorUID) + require.NoError(t, err, "rollback leaves the same never-claimed observation retryable") +} + +func TestObservedSessionSuspensionContendsWithClaim(t *testing.T) { + for _, first := range []string{"claim", "observation"} { + t.Run(first, func(t *testing.T) { + client, operation, generation := observedSuspensionFixture(t) + tx, err := sharedDB.Begin(t.Context()) + require.NoError(t, err) + t.Cleanup(func() { _ = tx.Rollback(context.Background()) }) + _, err = lockSession(t.Context(), tx, operation.Instance.Id) + require.NoError(t, err) + executor := uuid.New() + type claimResult struct { + won bool + err error + } + claims, observations := make(chan claimResult, 1), make(chan error, 1) + claim := func() { + won, err := client.ClaimSessionOperation(t.Context(), operation.Instance.Id, operation.ID, executor) + claims <- claimResult{won, err} + } + observe := func() { + _, err := client.FinishObservedSessionSuspension(t.Context(), operation.Instance.Id, operation.ID, operation.Instance.PreparedRevision, generation.ActorUID) + observations <- err + } + waitBlocked := func(count int) { + t.Helper() + require.Eventually(t, func() bool { + var blocked int + err := sharedDB.QueryRow(t.Context(), `SELECT count(*) FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock' AND cardinality(pg_blocking_pids(pid)) > 0`).Scan(&blocked) + return err == nil && blocked >= count + }, 5*time.Second, 10*time.Millisecond, "observe actual PostgreSQL contention") + } + if first == "claim" { + go claim() + waitBlocked(1) + go observe() + } else { + go observe() + waitBlocked(1) + go claim() + } + waitBlocked(2) + require.NoError(t, tx.Commit(t.Context())) + claimed, observedErr := <-claims, <-observations + require.NoError(t, claimed.err) + current, err := client.GetSessionOperation(t.Context(), operation.Instance.Id, operation.ID) + require.NoError(t, err) + if claimed.won { + require.ErrorIs(t, observedErr, ErrConflict) + require.Equal(t, executor, current.ExecutorID) + require.Equal(t, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_SUSPEND, current.Instance.Operation) + // Existing claimed completion still requires the winning executor. + _, err = client.FinishSessionOperation(t.Context(), operation.Instance.Id, operation.ID, uuid.New(), "", generation.ActorUID, "") + require.ErrorIs(t, err, ErrConflict) + _, err = client.FinishSessionOperation(t.Context(), operation.Instance.Id, operation.ID, executor, "", generation.ActorUID, "") + require.NoError(t, err) + } else { + require.NoError(t, observedErr) + require.Equal(t, uuid.Nil, current.ExecutorID) + require.Equal(t, apiv1alpha1.RuntimeState_RUNTIME_STATE_SUSPENDED, current.Instance.State) + require.Equal(t, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_NONE, current.Instance.Operation) + } + }) + } +} + func TestSessionOperationGenerationAndTombstone(t *testing.T) { client := NewClient(setupTestDB(t)) sessionFixture(t, client, t.Context(), "team-a", "revision", "assistant", "kagent") diff --git a/go/core/internal/grpcserver/session_credentials_test.go b/go/core/internal/grpcserver/session_credentials_test.go index 1350a06cd0..9bf0314a47 100644 --- a/go/core/internal/grpcserver/session_credentials_test.go +++ b/go/core/internal/grpcserver/session_credentials_test.go @@ -90,6 +90,7 @@ func TestSessionCredentialsThroughGRPC(t *testing.T) { type proxyControlledActors struct { mu sync.Mutex actor *ateapipb.Actor + templateUID string policy *ateapipb.EgressPolicy creates, resumes, suspends int } @@ -102,6 +103,17 @@ func (a *proxyControlledActors) GetActor(context.Context, string, string) (*atea } return proto.CloneOf(a.actor), nil } + +func (a *proxyControlledActors) GetActorTemplate(_ context.Context, atespace, name string) (*ateapipb.ActorTemplate, error) { + return &ateapipb.ActorTemplate{ + Metadata: &ateapipb.ResourceMetadata{Atespace: atespace, Name: name, Uid: a.templateUID}, + SnapshotConfig: &ateapipb.SnapshotConfig{ + OnPause: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL, + OnCommit: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, + }, + }, nil +} + func (a *proxyControlledActors) CreateActor(_ context.Context, at, name, templateAt, templateName string) (*ateapipb.Actor, error) { a.mu.Lock() defer a.mu.Unlock() @@ -130,6 +142,9 @@ func (a *proxyControlledActors) SuspendActor(context.Context, string, string) (* defer a.mu.Unlock() a.suspends++ a.actor.Status.State = ateapipb.ActorState_ACTOR_STATE_SUSPENDED + a.actor.Status.ExternalSnapshot = &ateapipb.ExternalSnapshot{ + SnapshotUri: "s3://snapshots/controlled-actor", ContentScope: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, ActorTemplateUid: a.templateUID, + } return proto.CloneOf(a.actor), nil } func (a *proxyControlledActors) PauseActor(context.Context, string, string) (*ateapipb.Actor, error) { @@ -170,7 +185,7 @@ func TestGitProxyReferenceOnlyGRPCReadiness(t *testing.T) { scheme := runtime.NewScheme() require.NoError(t, corev1.AddToScheme(scheme)) kube := fake.NewClientBuilder().WithScheme(scheme).Build() - actors := &proxyControlledActors{} + actors := &proxyControlledActors{templateUID: revision.ActorTemplateUID} workflow := sessionsvc.NewActorWorkflow(store, actors, substrate.NewRuntimeCredentialIssuer(kube, "kagent"), "http://kagent-controller.kagent:8083") listener := bufconn.Listen(DefaultMaxMessageSize) server, err := New(Config{Listener: listener, Authenticator: authenticator, SystemService: testSystemService(), SessionService: sessionsvc.NewService(store, policy, workflow)}) diff --git a/go/core/internal/grpcserver/session_native_handoff_test.go b/go/core/internal/grpcserver/session_native_handoff_test.go index 0333228548..0ec8db19df 100644 --- a/go/core/internal/grpcserver/session_native_handoff_test.go +++ b/go/core/internal/grpcserver/session_native_handoff_test.go @@ -243,7 +243,11 @@ func nativePreparationInstalled(t *testing.T, provider, scenario string) { prepared.SourceSnapshot, err = json.Marshal(database.EnvironmentRevisionSnapshot{BaseRevision: base.Revision, Environment: environment, Composition: composition}) require.NoError(t, err) require.NoError(t, store.RecordRuntimeRevision(ctx, prepared, false)) - actors := &preparationActors{proxyControlledActors: &proxyControlledActors{}, template: &ateapipb.ActorTemplate{Metadata: &ateapipb.ResourceMetadata{Atespace: prepared.ActorTemplateAtespace, Name: prepared.ActorTemplateName, Uid: prepared.ActorTemplateUID}, Containers: []*ateapipb.Container{{Name: "native", Image: environment.Image, Env: []*ateapipb.EnvVar{{Name: "KAGENT_CONFIG_JSON", Value: string(raw)}, {Name: "MAINLOOP_RUNTIME_PLATFORM", Value: environment.Platform}}}}, Volumes: []*ateapipb.Volume{{Name: "runtime-payload", Image: &ateapipb.ImageVolumeSource{Reference: composition.PayloadImage}}}}} + actors := &preparationActors{proxyControlledActors: &proxyControlledActors{templateUID: prepared.ActorTemplateUID}, template: &ateapipb.ActorTemplate{Metadata: &ateapipb.ResourceMetadata{Atespace: prepared.ActorTemplateAtespace, Name: prepared.ActorTemplateName, Uid: prepared.ActorTemplateUID}, Containers: []*ateapipb.Container{{Name: "native", Image: environment.Image, Env: []*ateapipb.EnvVar{{Name: "KAGENT_CONFIG_JSON", Value: string(raw)}, {Name: "MAINLOOP_RUNTIME_PLATFORM", Value: environment.Platform}}}}, Volumes: []*ateapipb.Volume{{Name: "runtime-payload", Image: &ateapipb.ImageVolumeSource{Reference: composition.PayloadImage}}}}} + actors.template.SnapshotConfig = &ateapipb.SnapshotConfig{ + OnPause: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL, + OnCommit: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, + } policy, err := controlauth.New(controlauth.Config{Namespace: "kagent", Agents: []string{"mainloop-main"}, DevelopmentEnvironmentRegistries: []string{"fixture.test"}, CleartextMCPOrigins: []string{"http://mainloop-mcp.mainloop.svc.cluster.local"}, Credentials: []controlauth.CredentialRule{ {Namespace: "kagent", SecretNamePattern: "mainloop-mcp-binding-*", Key: "authorization", Header: "authorization", Origin: "http://mainloop-mcp.mainloop.svc.cluster.local", Purpose: "mcp"}, {Namespace: "kagent", SecretNamePattern: "mainloop-git-read-*", Key: "authorization", Header: "authorization", Origin: apiworkspace.ReadProxyOrigin, Purpose: "git-read"}, diff --git a/go/core/internal/service/checkpoint/service.go b/go/core/internal/service/checkpoint/service.go index 3a712cafa5..7af0888e6f 100644 --- a/go/core/internal/service/checkpoint/service.go +++ b/go/core/internal/service/checkpoint/service.go @@ -151,8 +151,8 @@ func (s *Service) create(ctx context.Context, userID, sessionID, requestID, expe // because ate-api also permits Actors to be changed outside kagent. func (s *Service) ensureTag(ctx context.Context, checkpoint *apiv1alpha1.Checkpoint, reference *database.SessionTaskSnapshot) (*ateapipb.Tag, error) { generation, err := s.store.GetRuntimeGeneration(ctx, checkpoint.GetSessionId()) - if err != nil || generation.Phase != "active" || generation.ActorUID == "" || reference.ContentScope != "DATA" { - return nil, fmt.Errorf("checkpoint requires an active ledger-issued DATA generation") + if err != nil || generation.Phase != "active" || generation.ActorUID == "" || (reference.ContentScope != "DATA" && reference.ContentScope != "FULL") { + return nil, fmt.Errorf("checkpoint requires an active ledger-issued generation and a recorded snapshot scope") } actorName := generation.ActorName actor, err := s.verifySnapshot(ctx, actorName, reference) diff --git a/go/core/internal/service/checkpoint/service_test.go b/go/core/internal/service/checkpoint/service_test.go index 7ca373e910..9f687db806 100644 --- a/go/core/internal/service/checkpoint/service_test.go +++ b/go/core/internal/service/checkpoint/service_test.go @@ -40,6 +40,7 @@ type testStore struct { deleted bool finalizeErr error reserveErr error + scope string } func (s *testStore) ReserveSessionCheckpoint(_ context.Context, checkpoint *apiv1alpha1.Checkpoint, _, _ string) (*apiv1alpha1.Checkpoint, *database.SessionTaskSnapshot, error) { @@ -51,7 +52,11 @@ func (s *testStore) ReserveSessionCheckpoint(_ context.Context, checkpoint *apiv } checkpoint.HeadTaskId = "task-1" checkpoint.HistorySequence = 7 - s.snapshot = &database.SessionTaskSnapshot{Atespace: "team-a", URI: "s3://snapshots/snapshot-1", ContentScope: "DATA"} + scope := s.scope + if scope == "" { + scope = "DATA" + } + s.snapshot = &database.SessionTaskSnapshot{Atespace: "team-a", URI: "s3://snapshots/snapshot-1", ContentScope: scope} checkpoint.State = apiv1alpha1.CheckpointState_CHECKPOINT_STATE_CREATING checkpoint.CreatedAt = timestamppb.Now() s.prepared = checkpoint @@ -146,6 +151,14 @@ type testTags struct { deleteErr error actorErr error mutateTag func(*ateapipb.Tag) + scope ateapipb.SnapshotContentScope +} + +func (t *testTags) contentScope() ateapipb.SnapshotContentScope { + if t.scope == ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_UNSPECIFIED { + return ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA + } + return t.scope } func (t *testTags) GetActor(_ context.Context, atespace, name string) (*ateapipb.Actor, error) { @@ -156,6 +169,7 @@ func (t *testTags) GetActor(_ context.Context, atespace, name string) (*ateapipb if t.created != nil && t.snapshotURIAfterCreate != "" { uri = t.snapshotURIAfterCreate } + scope := t.contentScope() actorUID := "actor-uid" if t.created != nil && t.actorUIDAfterCreate != "" { actorUID = t.actorUIDAfterCreate @@ -163,7 +177,7 @@ func (t *testTags) GetActor(_ context.Context, atespace, name string) (*ateapipb return &ateapipb.Actor{ Metadata: &ateapipb.ResourceMetadata{Atespace: atespace, Name: name, Uid: actorUID}, Status: &ateapipb.ActorStatus{State: ateapipb.ActorState_ACTOR_STATE_SUSPENDED, - ExternalSnapshot: &ateapipb.ExternalSnapshot{SnapshotUri: uri, ContentScope: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, ActorTemplateUid: "template-uid"}}, + ExternalSnapshot: &ateapipb.ExternalSnapshot{SnapshotUri: uri, ContentScope: scope, ActorTemplateUid: "template-uid"}}, }, nil } @@ -187,7 +201,7 @@ func (t *testTags) CreateTag(_ context.Context, atespace, name, actorName string SourceActor: &ateapipb.ObjectRef{Atespace: atespace, Name: actorName}, Scope: ateapipb.TagScope_TAG_SCOPE_ATESPACE, Status: &ateapipb.TagStatus{ActorTemplateUid: "template-uid", - Snapshot: &ateapipb.ExternalSnapshot{SnapshotUri: "s3://tags/checkpoint", ContentScope: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA}}, + Snapshot: &ateapipb.ExternalSnapshot{SnapshotUri: "s3://tags/checkpoint", ContentScope: t.contentScope()}}, } if t.mutateTag != nil { t.mutateTag(t.created) @@ -324,6 +338,32 @@ func TestDeleteHidesCheckpointBeforeDeletingTag(t *testing.T) { t.Fatalf("checkpoint state = %s, tag deletes = %d, row deleted = %v", checkpoint.State, tags.deleteCalls, store.deleted) } } + +// A Full onQuiesce policy records FULL boundaries. They can be checkpointed but +// not forked, because a fork restores only durable data. +func TestFullSnapshotCheckpointsButCannotFork(t *testing.T) { + store := &testStore{scope: "FULL"} + tags := &testTags{snapshotURI: "s3://snapshots/snapshot-1", scope: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL} + workflow := &testWorkflow{} + service := NewService(store, testAuthorizer{}, tags, workflow) + ctx := auth.AuthSessionTo(t.Context(), testSession{userID: "alice"}) + + checkpoint, err := service.Create(ctx, "018f47a2-4efb-7c21-a848-123456789abc", "request-1", "task-1") + require.NoError(t, err) + require.Equal(t, apiv1alpha1.CheckpointState_CHECKPOINT_STATE_READY, checkpoint.State) + require.Equal(t, "FULL", store.snapshot.ContentScope) + + _, err = service.Fork(ctx, checkpoint.Id, "fork-request") + require.Equal(t, serviceerrors.CodeFailedPrecondition, serviceerrors.CodeOf(err)) + require.Nil(t, workflow.session, "a FULL checkpoint must not reach runtime creation") + + // The recorded scope still binds the copy: a DATA Actor cannot satisfy a FULL boundary. + store, tags = &testStore{scope: "FULL"}, &testTags{snapshotURI: "s3://snapshots/snapshot-1"} + _, err = NewService(store, testAuthorizer{}, tags, nil).Create(ctx, "018f47a2-4efb-7c21-a848-123456789abc", "request-2", "task-1") + require.Error(t, err) + require.Zero(t, tags.createCalls) +} + func TestForkCreatesSessionFromCheckpoint(t *testing.T) { checkpoint := &apiv1alpha1.Checkpoint{Id: "018f47a2-4efb-7c21-a848-123456789abc", State: apiv1alpha1.CheckpointState_CHECKPOINT_STATE_READY} store := &testStore{prepared: checkpoint, snapshot: &database.SessionTaskSnapshot{Atespace: "team-a", URI: "s3://snapshots/snapshot-1", ContentScope: "DATA"}} diff --git a/go/core/internal/service/session/git_proxy_readiness_test.go b/go/core/internal/service/session/git_proxy_readiness_test.go index ce956a6b51..04a54f851b 100644 --- a/go/core/internal/service/session/git_proxy_readiness_test.go +++ b/go/core/internal/service/session/git_proxy_readiness_test.go @@ -31,6 +31,10 @@ func TestGitProxyFailedWarmupRetainsIntentAndReferences(t *testing.T) { require.NoError(t, store.UpsertAgentDefinition(t.Context(), database.AgentDefinition{Namespace: revision.Namespace, AgentName: revision.AgentName, AgentUID: revision.AgentUID, DesiredRevision: revision.Revision})) require.NoError(t, store.RecordRuntimeRevision(t.Context(), revision, true)) actors := deniedProxyResume{&lifecycleTestActors{actors: map[string]*ateapipb.Actor{}}} + template, err := actors.GetActorTemplate(t.Context(), revision.ActorTemplateAtespace, revision.ActorTemplateName) + require.NoError(t, err) + actors.template = template + actors.template.Metadata.Uid = revision.ActorTemplateUID service := NewService(store, serviceTestAuthorizer{}, NewActorWorkflow(store, actors, fixtureCredentials{}, "http://kagent-controller.kagent:8083")) refs := []*api.SessionCredential{{Origin: workspace.ReadProxyOrigin, Header: "Authorization", SecretRef: &api.SecretKeyReference{Name: "mainloop-git-read-unpublished", Key: "authorization"}}} ctx := serviceTestContext("alice") diff --git a/go/core/internal/service/session/quiescence_test.go b/go/core/internal/service/session/quiescence_test.go index 5351bf4ca5..72ddc6a39e 100644 --- a/go/core/internal/service/session/quiescence_test.go +++ b/go/core/internal/service/session/quiescence_test.go @@ -32,6 +32,8 @@ func TestIdleLifecycleDoesNotOwnTaskPublication(t *testing.T) { base := &lifecycleTestActors{actors: map[string]*ateapipb.Actor{}} session, err := NewActorWorkflow(store, base, fixtureCredentials{}, "http://kagent-controller.kagent:8083").Create(t.Context(), session) require.NoError(t, err) + _, err = base.ResumeActor(t.Context(), "team-a", fixtureActorName(t, store, session.Id)) + require.NoError(t, err) message := a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("hello")) message.ContextID = session.ContextId task := a2a.NewSubmittedTask(message, message) @@ -108,3 +110,111 @@ func (s *quiescenceRetryStore) FinishSessionQuiescence(ctx context.Context, work } return s.Client.FinishSessionQuiescence(ctx, work, snapshot) } + +func TestIdleQuiescenceRecoveryAfterScopeRejection(t *testing.T) { + for _, mismatch := range []bool{false, true} { + name := "matching Full snapshot recovers" + if mismatch { + name = "mismatched snapshot remains fenced" + } + t.Run(name, func(t *testing.T) { + store, session := lifecycleFixture(t) + base := &lifecycleTestActors{actors: map[string]*ateapipb.Actor{}, snapshotScope: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL} + template, err := base.GetActorTemplate(t.Context(), store.revision.ActorTemplateAtespace, store.revision.ActorTemplateName) + require.NoError(t, err) + template.SnapshotConfig.OnCommit = ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL + base.template = template + actors := &retryTestActors{lifecycleTestActors: base} + workflow := NewActorWorkflow(store, actors, fixtureCredentials{}, "http://kagent-controller.kagent:8083") + session, err = workflow.Create(t.Context(), session) + require.NoError(t, err) + _, err = actors.ResumeActor(t.Context(), "team-a", fixtureActorName(t, store, session.Id)) + require.NoError(t, err) + message := a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("done")) + message.ContextID = session.ContextId + task := a2a.NewSubmittedTask(message, message) + task.Status.State = a2a.TaskStateCompleted + hash := sha256.Sum256([]byte("completed")) + version, err := store.CreateRuntimeTask(t.Context(), session.Id, hash[:], task, "") + require.NoError(t, err) + require.NoError(t, store.SettleSessionTask(t.Context(), session.Id, string(task.ID), version)) + oldClaim, err := store.ClaimSessionQuiescence(t.Context()) + require.NoError(t, err) + // Reproduce the old controller's failure: Suspend succeeded, but its + // FULL response was rejected and the original claim was never finished. + actor, err := actors.SuspendActor(t.Context(), "team-a", fixtureActorName(t, store, session.Id)) + require.NoError(t, err) + require.Equal(t, ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL, actor.GetStatus().GetExternalSnapshot().GetContentScope()) + _, err = workflow.Suspend(t.Context(), session) + require.ErrorIs(t, err, database.ErrFailedPrecondition) + _, err = store.ClaimSessionQuiescence(t.Context()) + require.ErrorIs(t, err, database.ErrNotFound, "restarting a worker alone must not steal uncertain work") + if mismatch { + base.mu.Lock() + base.actors[actorKey("team-a", fixtureActorName(t, store, session.Id))].Status.ExternalSnapshot.ContentScope = ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA + base.mu.Unlock() + } + // Operator recovery after all old controller workers have stopped. + // The exact version/executor predicate cannot release another claim. + tag, err := store.pool.Exec(t.Context(), ` + UPDATE session_task_event SET quiescence_executor_id = NULL + WHERE sequence = $1 AND quiescence_executor_id = $2 + AND published AND quiescence_pending = TRUE + `, oldClaim.Version, oldClaim.ExecutorID) + require.NoError(t, err) + require.EqualValues(t, 1, tag.RowsAffected()) + newClaim, err := store.ClaimSessionQuiescence(t.Context()) + require.NoError(t, err) + require.NotEqual(t, oldClaim.ExecutorID, newClaim.ExecutorID) + mutations := actors.mutations.Load() + // A fresh worker uses the suspended result, with no second mutation. + NewActorWorkflow(store, actors, fixtureCredentials{}, "http://kagent-controller.kagent:8083").quiesceIdleSession(t.Context(), newClaim) + require.Equal(t, mutations, actors.mutations.Load()) + checkpoint, boundary, err := store.ReserveSessionCheckpoint(t.Context(), &apiv1alpha1.Checkpoint{Id: uuid.NewString(), SessionId: session.Id, HeadTaskId: string(task.ID)}, "alice", "checkpoint") + if mismatch { + require.ErrorIs(t, err, database.ErrFailedPrecondition) + _, err = workflow.Suspend(t.Context(), session) + require.ErrorIs(t, err, database.ErrFailedPrecondition) + return + } + require.NoError(t, err) + require.Equal(t, string(task.ID), checkpoint.HeadTaskId) + require.EqualValues(t, version, checkpoint.HistorySequence) + require.Equal(t, "team-a", boundary.Atespace) + require.Equal(t, "s3://snapshots/snapshot-1", boundary.URI) + require.Equal(t, "FULL", boundary.ContentScope) + // The runbook requires the original task and event to retain the exact + // snapshot, not merely pending=false (which supersession also sets). + var recordedTask string + var recordedVersion, historySequence int64 + var retainedExecutor uuid.UUID + require.NoError(t, store.pool.QueryRow(t.Context(), ` + SELECT e.task_id, e.sequence, t.history_sequence, e.quiescence_executor_id + FROM session_record s + JOIN session_task_event e ON e.history_id = s.history_id + JOIN session_task t ON t.history_id = e.history_id AND t.id = e.task_id + WHERE s.id = $1::uuid + AND e.task_id = $2 AND e.sequence = $3::bigint + AND e.published AND e.quiescence_pending = FALSE + AND t.history_sequence = e.sequence + AND e.snapshot_atespace = $4 AND t.snapshot_atespace = e.snapshot_atespace + AND e.snapshot_uri = $5 AND t.snapshot_uri = e.snapshot_uri + AND e.snapshot_content_scope = $6 + AND t.snapshot_content_scope = e.snapshot_content_scope + `, session.Id, string(task.ID), version, boundary.Atespace, boundary.URI, boundary.ContentScope). + Scan(&recordedTask, &recordedVersion, &historySequence, &retainedExecutor)) + require.Equal(t, string(task.ID), recordedTask) + require.Equal(t, version, recordedVersion) + require.Equal(t, version, historySequence) + require.Equal(t, newClaim.ExecutorID, retainedExecutor) + // Reserving a checkpoint fences explicit lifecycle until finalized. + checkpoint, err = store.FinalizeSessionCheckpoint(t.Context(), checkpoint.Id, "tag-uid", "s3://retained/snapshot", "") + require.NoError(t, err) + snapshot, _, err := store.GetSessionCheckpointSnapshot(t.Context(), checkpoint.Id, "alice") + require.NoError(t, err) + require.Equal(t, "FULL", snapshot.ContentScope) + _, err = workflow.Suspend(t.Context(), session) + require.NoError(t, err, "explicit suspension becomes available again") + }) + } +} diff --git a/go/core/internal/service/session/snapshot_test.go b/go/core/internal/service/session/snapshot_test.go new file mode 100644 index 0000000000..f1495700a7 --- /dev/null +++ b/go/core/internal/service/session/snapshot_test.go @@ -0,0 +1,433 @@ +package session + +import ( + "context" + "testing" + + "github.com/agent-substrate/substrate/pkg/proto/ateapipb" + "github.com/google/uuid" + apiv1alpha1 "github.com/kagent-dev/kagent/go/api/gen/kagent/api/v1alpha1" + "github.com/kagent-dev/kagent/go/core/internal/database" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +func TestQuiesceSnapshotMatchesPreparedPolicy(t *testing.T) { + data, full := ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL + for _, test := range []struct { + name string + policy ateapipb.SnapshotContentScope + actual ateapipb.SnapshotContentScope + wantErr bool + }{ + {name: "Data policy with DATA", policy: data, actual: data}, + {name: "Full policy with FULL", policy: full, actual: full}, + {name: "Data policy rejects FULL", policy: data, actual: full, wantErr: true}, + {name: "Full policy rejects DATA", policy: full, actual: data, wantErr: true}, + {name: "unspecified snapshot rejected", policy: data, wantErr: true}, + } { + t.Run(test.name, func(t *testing.T) { + revision := &database.RuntimeRevision{ActorTemplateAtespace: "team-a", ActorTemplateName: "pinned-template", ActorTemplateUID: "template-uid"} + template := &ateapipb.ActorTemplate{ + Metadata: &ateapipb.ResourceMetadata{Atespace: "team-a", Name: "pinned-template", Uid: "template-uid"}, + SnapshotConfig: &ateapipb.SnapshotConfig{OnCommit: test.policy, OnPause: full}, + } + expected, err := quiesceSnapshotScope(revision, template) + require.NoError(t, err) + actor := &ateapipb.Actor{ + Metadata: &ateapipb.ResourceMetadata{Atespace: "team-a", Name: "actor"}, + Status: &ateapipb.ActorStatus{State: ateapipb.ActorState_ACTOR_STATE_SUSPENDED, + ExternalSnapshot: &ateapipb.ExternalSnapshot{SnapshotUri: "s3://snapshot", ContentScope: test.actual, ActorTemplateUid: "template-uid"}}, + } + snapshot, err := snapshotForQuiesce(revision, actor, expected) + if test.wantErr { + require.Error(t, err) + require.Nil(t, snapshot) + return + } + require.NoError(t, err) + require.Equal(t, "team-a", snapshot.Atespace) + require.Equal(t, "s3://snapshot", snapshot.URI) + require.Contains(t, []string{"DATA", "FULL"}, snapshot.ContentScope) + }) + } +} + +type capturedSuspendTestActors struct { + *lifecycleTestActors + afterCapture func(*ateapipb.Actor, *ateapipb.ActorTemplate) + loseReply bool + captures int +} + +func (a *capturedSuspendTestActors) SuspendActor(ctx context.Context, space, name string) (*ateapipb.Actor, error) { + before, err := a.GetActor(ctx, space, name) + if err != nil { + return nil, err + } + if _, err := a.lifecycleTestActors.SuspendActor(ctx, space, name); err != nil { + return nil, err + } + a.mu.Lock() + defer a.mu.Unlock() + firstCapture := before.GetStatus().GetState() != ateapipb.ActorState_ACTOR_STATE_SUSPENDED && a.captures == 0 + if before.GetStatus().GetState() != ateapipb.ActorState_ACTOR_STATE_SUSPENDED { + a.captures++ + } + if firstCapture && a.afterCapture != nil { + a.afterCapture(a.actors[actorKey(space, name)], a.template) + } + if firstCapture && a.loseReply { + return nil, status.Error(codes.Unavailable, "response lost after captured suspension") + } + return proto.CloneOf(a.actors[actorKey(space, name)]), nil +} + +func TestActorWorkflowCapturedSuspendRetriesRemainFenced(t *testing.T) { + data, full := ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL + for _, test := range []struct { + name string + policy, actual ateapipb.SnapshotContentScope + afterCapture func(*ateapipb.Actor, *ateapipb.ActorTemplate) + loseReply bool + invalid bool + }{ + {name: "DATA rejects FULL across retries", policy: data, actual: full, invalid: true}, + {name: "FULL rejects DATA across retries", policy: full, actual: data, invalid: true}, + {name: "lost invalid FULL reply stays fenced", policy: full, actual: data, loseReply: true, invalid: true}, + {name: "missing URI stays fenced", policy: data, actual: data, invalid: true, afterCapture: func(a *ateapipb.Actor, _ *ateapipb.ActorTemplate) { a.Status.ExternalSnapshot.SnapshotUri = "" }}, + {name: "foreign snapshot template stays fenced", policy: data, actual: data, invalid: true, afterCapture: func(a *ateapipb.Actor, _ *ateapipb.ActorTemplate) { + a.Status.ExternalSnapshot.ActorTemplateUid = "foreign-template" + }}, + {name: "replaced pinned template stays fenced", policy: data, actual: data, invalid: true, afterCapture: func(_ *ateapipb.Actor, p *ateapipb.ActorTemplate) { p.Metadata.Uid = "replacement-template" }}, + {name: "unsupported policy stays fenced", policy: data, actual: data, invalid: true, afterCapture: func(_ *ateapipb.Actor, p *ateapipb.ActorTemplate) { + p.SnapshotConfig.OnCommit = ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_UNSPECIFIED + }}, + {name: "replaced Actor stays fenced", policy: data, actual: data, invalid: true, afterCapture: func(a *ateapipb.Actor, _ *ateapipb.ActorTemplate) { a.Metadata.Uid = "replacement-actor" }}, + {name: "valid DATA lost reply reconciles", policy: data, actual: data, loseReply: true}, + {name: "valid FULL lost reply reconciles", policy: full, actual: full, loseReply: true}, + } { + t.Run(test.name, func(t *testing.T) { + store, session := lifecycleFixture(t) + base := &lifecycleTestActors{actors: map[string]*ateapipb.Actor{}, snapshotScope: test.actual} + template, err := base.GetActorTemplate(t.Context(), store.revision.ActorTemplateAtespace, store.revision.ActorTemplateName) + require.NoError(t, err) + template.SnapshotConfig.OnCommit = test.policy + base.template = template + actors := &capturedSuspendTestActors{lifecycleTestActors: base, afterCapture: test.afterCapture, loseReply: test.loseReply} + workflow := NewActorWorkflow(store, actors, fixtureCredentials{}, "http://kagent-controller.kagent:8083") + session, err = workflow.Create(t.Context(), session) + require.NoError(t, err) + generation, err := store.GetRuntimeGeneration(t.Context(), session.Id) + require.NoError(t, err) + _, err = base.ResumeActor(t.Context(), generation.Atespace, generation.ActorName) + require.NoError(t, err) + _, err = workflow.Suspend(t.Context(), session) + require.Error(t, err) + held, err := store.BeginSessionOperation(t.Context(), session.Id, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_SUSPEND) + require.NoError(t, err) + require.NotEqual(t, uuid.Nil, held.ExecutorID, "the durable operation remembers possibly issued capture") + captured, err := base.GetActor(t.Context(), generation.Atespace, generation.ActorName) + require.NoError(t, err) + for range 2 { + retry := NewActorWorkflow(store, actors, fixtureCredentials{}, "http://kagent-controller.kagent:8083") + _, retryErr := retry.Suspend(t.Context(), held.Instance) + persisted, err := store.GetSessionByID(t.Context(), session.Id) + require.NoError(t, err) + after, err := base.GetActor(t.Context(), generation.Atespace, generation.ActorName) + require.NoError(t, err) + require.True(t, proto.Equal(captured, after), "retry must not replace or repair rejected state implicitly") + if test.invalid { + require.Error(t, retryErr) + require.Equal(t, apiv1alpha1.RuntimeState_RUNTIME_STATE_READY, persisted.State) + require.Equal(t, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_SUSPEND, persisted.Operation) + current, err := store.GetSessionOperation(t.Context(), session.Id, held.ID) + require.NoError(t, err) + require.NotEqual(t, uuid.Nil, current.ExecutorID) + _, err = retry.Resume(t.Context(), persisted) + require.ErrorIs(t, err, database.ErrConflict) + _, err = retry.Delete(t.Context(), persisted) + require.ErrorIs(t, err, database.ErrConflict) + } else { + require.NoError(t, retryErr) + require.Equal(t, apiv1alpha1.RuntimeState_RUNTIME_STATE_SUSPENDED, persisted.State) + require.Equal(t, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_NONE, persisted.Operation) + } + } + require.Equal(t, 1, actors.captures, "a retry must not capture again") + retained, err := store.GetRuntimeGeneration(t.Context(), session.Id) + require.NoError(t, err) + require.Equal(t, generation.ID, retained.ID) + require.Equal(t, generation.ActorUID, retained.ActorUID) + }) + } +} + +type observedSuspendTestStore struct { + *lifecycleTestStore + loseReply bool + failOnce bool + finishes int +} + +func (s *observedSuspendTestStore) FinishObservedSessionSuspension(ctx context.Context, sessionID string, id uuid.UUID, revision, actorUID string) (*apiv1alpha1.Session, error) { + s.finishes++ + if s.failOnce && s.finishes == 1 && !s.loseReply { + return nil, status.Error(codes.Unavailable, "database completion failed before commit") + } + result, err := s.Client.FinishObservedSessionSuspension(ctx, sessionID, id, revision, actorUID) + if err == nil && s.failOnce && s.finishes == 1 && s.loseReply { + return nil, status.Error(codes.Unavailable, "database completion reply lost after commit") + } + return result, err +} + +type observedSuspendTestActors struct { + *lifecycleTestActors + suspends int +} + +func (a *observedSuspendTestActors) SuspendActor(context.Context, string, string) (*ateapipb.Actor, error) { + a.suspends++ + return nil, status.Error(codes.Internal, "observed suspension must not issue a runtime mutation") +} + +func TestActorWorkflowInitialSuspendCompletionRetries(t *testing.T) { + data, full := ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL + for _, test := range []struct { + name string + policy ateapipb.SnapshotContentScope + golden bool + }{ + {name: "DATA without snapshot", policy: data}, + {name: "FULL without snapshot", policy: full}, + {name: "DATA with borrowed golden FULL", policy: data, golden: true}, + } { + for _, loseReply := range []bool{false, true} { + failure := "before commit" + if loseReply { + failure = "lost completion reply" + } + t.Run(test.name+"/"+failure, func(t *testing.T) { + baseStore, session := lifecycleFixture(t) + store := &observedSuspendTestStore{lifecycleTestStore: baseStore, failOnce: true, loseReply: loseReply} + baseActors := &lifecycleTestActors{actors: map[string]*ateapipb.Actor{}} + template, err := baseActors.GetActorTemplate(t.Context(), store.revision.ActorTemplateAtespace, store.revision.ActorTemplateName) + require.NoError(t, err) + template.SnapshotConfig.OnCommit = test.policy + baseActors.template = template + actors := &observedSuspendTestActors{lifecycleTestActors: baseActors} + workflow := NewActorWorkflow(store, actors, fixtureCredentials{}, "http://kagent-controller.kagent:8083") + session, err = workflow.Create(t.Context(), session) + require.NoError(t, err) + generation, err := store.GetRuntimeGeneration(t.Context(), session.Id) + require.NoError(t, err) + if test.golden { + baseActors.mu.Lock() + baseActors.actors[actorKey(generation.Atespace, generation.ActorName)].Status.ExternalSnapshot = &ateapipb.ExternalSnapshot{ + SnapshotUri: "s3://golden/template", ContentScope: full, ActorTemplateUid: store.revision.ActorTemplateUID, + } + baseActors.mu.Unlock() + } + initial, err := actors.GetActor(t.Context(), generation.Atespace, generation.ActorName) + require.NoError(t, err) + _, err = workflow.Suspend(t.Context(), session) + require.Error(t, err) + held, err := store.BeginSessionOperation(t.Context(), session.Id, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_SUSPEND) + require.NoError(t, err) + require.Equal(t, uuid.Nil, held.ExecutorID, "failed no-op persistence must not imply issued capture") + if loseReply { + require.Equal(t, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_NONE, held.Instance.Operation) + } else { + require.Equal(t, apiv1alpha1.RuntimeState_RUNTIME_STATE_READY, held.Instance.State) + require.Equal(t, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_SUSPEND, held.Instance.Operation) + } + retry := NewActorWorkflow(store, actors, fixtureCredentials{}, "http://kagent-controller.kagent:8083") + session, err = retry.Suspend(t.Context(), held.Instance) + require.NoError(t, err) + require.Equal(t, apiv1alpha1.RuntimeState_RUNTIME_STATE_SUSPENDED, session.State) + require.Equal(t, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_NONE, session.Operation) + after, err := actors.GetActor(t.Context(), generation.Atespace, generation.ActorName) + require.NoError(t, err) + require.True(t, proto.Equal(initial, after)) + require.Zero(t, actors.suspends, "both attempts settle using only Actor observations") + _, err = retry.Quiesce(t.Context(), session) + require.Error(t, err, "terminal task boundaries still require a valid captured snapshot") + continuation := NewActorWorkflow(store, baseActors, fixtureCredentials{}, "http://kagent-controller.kagent:8083") + session, err = continuation.Resume(t.Context(), session) + require.NoError(t, err) + _, err = continuation.Delete(t.Context(), session) + require.NoError(t, err) + }) + } + } +} + +func TestQuiesceSnapshotRejectsUntrustedBoundary(t *testing.T) { + for _, name := range []string{"template UID", "template atespace", "template name", "unsupported policy", "missing policy", "snapshot template UID", "missing snapshot URI", "unsettled Actor"} { + t.Run(name, func(t *testing.T) { + revision := &database.RuntimeRevision{ActorTemplateAtespace: "team-a", ActorTemplateName: "pinned-template", ActorTemplateUID: "template-uid"} + template := &ateapipb.ActorTemplate{ + Metadata: &ateapipb.ResourceMetadata{Atespace: "team-a", Name: "pinned-template", Uid: "template-uid"}, + SnapshotConfig: &ateapipb.SnapshotConfig{OnCommit: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL}, + } + actor := &ateapipb.Actor{Status: &ateapipb.ActorStatus{State: ateapipb.ActorState_ACTOR_STATE_SUSPENDED, + ExternalSnapshot: &ateapipb.ExternalSnapshot{SnapshotUri: "s3://snapshot", ContentScope: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL, ActorTemplateUid: "template-uid"}}} + switch name { + case "template UID": + template.Metadata.Uid = "replacement" + case "template atespace": + template.Metadata.Atespace = "other" + case "template name": + template.Metadata.Name = "latest" + case "unsupported policy": + template.SnapshotConfig.OnCommit = ateapipb.SnapshotContentScope(99) + case "missing policy": + template.SnapshotConfig = nil + case "snapshot template UID": + actor.Status.ExternalSnapshot.ActorTemplateUid = "replacement" + case "missing snapshot URI": + actor.Status.ExternalSnapshot.SnapshotUri = "" + case "unsettled Actor": + actor.Status.State = ateapipb.ActorState_ACTOR_STATE_SUSPENDING + } + expected, err := quiesceSnapshotScope(revision, template) + if err == nil { + _, err = snapshotForQuiesce(revision, actor, expected) + } + require.Error(t, err) + }) + } +} + +func TestActorWorkflowConfiguredSnapshotScope(t *testing.T) { + data, full := ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL + for _, policy := range []ateapipb.SnapshotContentScope{data, full} { + for _, actual := range []ateapipb.SnapshotContentScope{data, full} { + for _, operation := range []string{"quiesce", "suspend"} { + t.Run(policy.String()+"/"+actual.String()+"/"+operation, func(t *testing.T) { + store, session := lifecycleFixture(t) + base := &lifecycleTestActors{actors: map[string]*ateapipb.Actor{}, snapshotScope: actual} + template, err := base.GetActorTemplate(t.Context(), store.revision.ActorTemplateAtespace, store.revision.ActorTemplateName) + require.NoError(t, err) + base.template = template + base.template.SnapshotConfig.OnCommit = policy + workflow := NewActorWorkflow(store, base, fixtureCredentials{}, "http://kagent-controller.kagent:8083") + session, err = workflow.Create(t.Context(), session) + require.NoError(t, err) + // Dispatch starts compute while the Session is already READY. + _, err = base.ResumeActor(t.Context(), "team-a", fixtureActorName(t, store, session.Id)) + require.NoError(t, err) + if operation == "quiesce" { + _, err = workflow.Quiesce(t.Context(), session) + } else { + session, err = workflow.Suspend(t.Context(), session) + } + if policy != actual { + require.Error(t, err) + return + } + require.NoError(t, err) + _, err = workflow.Resume(t.Context(), session) + require.NoError(t, err, "same Actor resume must support either snapshot scope") + }) + } + } + } +} + +func TestPauseAlwaysPreservesFullWaitingTask(t *testing.T) { + for _, policy := range []ateapipb.SnapshotContentScope{ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL} { + t.Run(policy.String(), func(t *testing.T) { + store, session := lifecycleFixture(t) + base := &lifecycleTestActors{actors: map[string]*ateapipb.Actor{}} + template, err := base.GetActorTemplate(t.Context(), store.revision.ActorTemplateAtespace, store.revision.ActorTemplateName) + require.NoError(t, err) + base.template = template + base.template.SnapshotConfig.OnCommit = policy + workflow := NewActorWorkflow(store, base, fixtureCredentials{}, "http://kagent-controller.kagent:8083") + session, err = workflow.Create(t.Context(), session) + require.NoError(t, err) + _, err = base.ResumeActor(t.Context(), "team-a", fixtureActorName(t, store, session.Id)) + require.NoError(t, err) + require.NoError(t, workflow.Pause(t.Context(), session)) + actor, err := base.GetActor(t.Context(), "team-a", fixtureActorName(t, store, session.Id)) + require.NoError(t, err) + require.Equal(t, ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL, actor.GetStatus().GetLocalSnapshot().GetContentScope()) + }) + } +} + +func TestActorWorkflowSuspendBeforeFirstResume(t *testing.T) { + data, full := ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL + for _, test := range []struct { + name string + policy ateapipb.SnapshotContentScope + golden bool + }{ + {name: "Data without snapshot", policy: data}, + {name: "Full without snapshot", policy: full}, + {name: "Data with borrowed golden FULL", policy: data, golden: true}, + } { + for _, continuation := range []string{"resume then delete", "delete"} { + t.Run(test.name+"/"+continuation, func(t *testing.T) { + store, session := lifecycleFixture(t) + actors := &lifecycleTestActors{actors: map[string]*ateapipb.Actor{}} + template, err := actors.GetActorTemplate(t.Context(), store.revision.ActorTemplateAtespace, store.revision.ActorTemplateName) + require.NoError(t, err) + template.SnapshotConfig.OnCommit = test.policy + actors.template = template + workflow := NewActorWorkflow(store, actors, fixtureCredentials{}, "http://kagent-controller.kagent:8083") + session, err = workflow.Create(t.Context(), session) + require.NoError(t, err) + generation, err := store.GetRuntimeGeneration(t.Context(), session.Id) + require.NoError(t, err) + if test.golden { + actors.mu.Lock() + actors.actors[actorKey(generation.Atespace, generation.ActorName)].Status.ExternalSnapshot = &ateapipb.ExternalSnapshot{ + SnapshotUri: "s3://golden/template", ContentScope: full, ActorTemplateUid: store.revision.ActorTemplateUID, + } + actors.mu.Unlock() + } + initial, err := actors.GetActor(t.Context(), generation.Atespace, generation.ActorName) + require.NoError(t, err) + unchanged, err := actors.SuspendActor(t.Context(), generation.Atespace, generation.ActorName) + require.NoError(t, err) + require.True(t, proto.Equal(initial, unchanged), "Substrate's suspended fast path must not manufacture a snapshot") + _, err = workflow.Quiesce(t.Context(), session) + require.Error(t, err, "a task boundary must still reject missing state or mismatched golden scope") + session, err = workflow.Suspend(t.Context(), session) + require.NoError(t, err) + require.Equal(t, apiv1alpha1.RuntimeState_RUNTIME_STATE_SUSPENDED, session.State) + require.Equal(t, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_NONE, session.Operation) + persisted, err := store.GetSessionByID(t.Context(), session.Id) + require.NoError(t, err) + require.Equal(t, session.State, persisted.State) + require.Equal(t, session.Operation, persisted.Operation) + _, err = workflow.Suspend(t.Context(), session) + require.NoError(t, err, "Suspend retry must remain settled") + unchanged, err = actors.GetActor(t.Context(), generation.Atespace, generation.ActorName) + require.NoError(t, err) + require.True(t, proto.Equal(initial, unchanged), "initial lifecycle suspension retains the existing state") + if continuation == "resume then delete" { + session, err = workflow.Resume(t.Context(), session) + require.NoError(t, err) + require.Equal(t, apiv1alpha1.RuntimeState_RUNTIME_STATE_READY, session.State) + require.Equal(t, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_NONE, session.Operation) + resumed, err := store.GetRuntimeGeneration(t.Context(), session.Id) + require.NoError(t, err) + require.Equal(t, generation.ID, resumed.ID) + require.Equal(t, generation.ActorUID, resumed.ActorUID) + require.Len(t, actors.actors, 1, "Resume must retain the same Actor") + } + session, err = workflow.Delete(t.Context(), session) + require.NoError(t, err) + require.Equal(t, apiv1alpha1.RuntimeState_RUNTIME_STATE_DELETED, session.State) + require.Equal(t, apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_NONE, session.Operation) + require.Empty(t, actors.actors) + }) + } + } +} diff --git a/go/core/internal/service/session/workflow.go b/go/core/internal/service/session/workflow.go index 9cfcf4f5d0..4c0fc128ff 100644 --- a/go/core/internal/service/session/workflow.go +++ b/go/core/internal/service/session/workflow.go @@ -32,12 +32,14 @@ type workflowStore interface { ClaimSessionOperation(context.Context, string, uuid.UUID, uuid.UUID) (bool, error) ReleaseRuntimeOperation(context.Context, string, uuid.UUID, uuid.UUID) error FinishSessionOperation(context.Context, string, uuid.UUID, uuid.UUID, string, string, string) (*apiv1alpha1.Session, error) + FinishObservedSessionSuspension(context.Context, string, uuid.UUID, string, string) (*apiv1alpha1.Session, error) GetSessionOperation(context.Context, string, uuid.UUID) (*database.SessionOperation, error) } type actorClient interface { substrate.LifecycleClient PauseActor(context.Context, string, string) (*ateapipb.Actor, error) + GetActorTemplate(context.Context, string, string) (*ateapipb.ActorTemplate, error) } // ActorWorkflow runs the imperative Substrate operations behind Session @@ -169,6 +171,9 @@ func (w *ActorWorkflow) Pause(ctx context.Context, session *apiv1alpha1.Session) if !validActorIdentity(actor, revision, name) || actor.GetMetadata().GetUid() != current.GetMetadata().GetUid() || actor.GetStatus().GetState() != ateapipb.ActorState_ACTOR_STATE_PAUSED { return fmt.Errorf("pause Actor %s/%s returned status %s", atespace, name, actor.GetStatus().GetState()) } + if actor.GetStatus().GetLocalSnapshot().GetContentScope() != ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL { + return fmt.Errorf("pause Actor %s/%s returned a snapshot without full process state", atespace, name) + } return nil } @@ -192,24 +197,67 @@ func (w *ActorWorkflow) Quiesce(ctx context.Context, session *apiv1alpha1.Sessio if err := w.verifyActor(ctx, session, revision, current); err != nil { return nil, err } + // Recovery of a released claim observes an already completed suspension. + // Do not issue another suspend when its snapshot can be verified directly. + if current.GetStatus().GetState() == ateapipb.ActorState_ACTOR_STATE_SUSPENDED && current.GetStatus().GetExternalSnapshot().GetSnapshotUri() != "" { + return w.quiesceSnapshot(ctx, session, current) + } actor, err := w.actors.SuspendActor(ctx, atespace, name) if err != nil { return nil, fmt.Errorf("suspend Actor %s/%s: %w", atespace, name, err) } - if actor.GetStatus().GetState() != ateapipb.ActorState_ACTOR_STATE_SUSPENDED { - return nil, fmt.Errorf("suspend Actor %s/%s returned status %s", atespace, name, actor.GetStatus().GetState()) - } - metadata := actor.GetMetadata() - if !validActorIdentity(actor, revision, name) || metadata.GetUid() != current.GetMetadata().GetUid() { + if actor.GetMetadata().GetUid() != current.GetMetadata().GetUid() { return nil, fmt.Errorf("suspend actor %s/%s returned invalid identity", atespace, name) } + return w.quiesceSnapshot(ctx, session, actor) +} + +// observeQuiesce reconciles an already issued boundary without issuing runtime +// work. A pending or mismatched outcome leaves the durable claim fenced. +func (w *ActorWorkflow) observeQuiesce(ctx context.Context, session *apiv1alpha1.Session) (*database.SessionTaskSnapshot, error) { + generation, err := w.store.GetRuntimeGeneration(ctx, session.GetId()) + if err != nil { + return nil, err + } + actor, err := w.actors.GetActor(ctx, generation.Atespace, generation.ActorName) + if err != nil { + return nil, err + } + return w.quiesceSnapshot(ctx, session, actor) +} + +func (w *ActorWorkflow) quiesceSnapshot(ctx context.Context, session *apiv1alpha1.Session, actor *ateapipb.Actor) (*database.SessionTaskSnapshot, error) { + revision, err := w.store.GetRuntimeRevision(ctx, session.GetPreparedRevision()) + if err != nil { + return nil, fmt.Errorf("load prepared revision: %w", err) + } + if err := w.verifyActor(ctx, session, revision, actor); err != nil { + return nil, err + } + template, err := w.actors.GetActorTemplate(ctx, revision.ActorTemplateAtespace, revision.ActorTemplateName) + if err != nil { + return nil, fmt.Errorf("get prepared ActorTemplate: %w", err) + } + expected, err := quiesceSnapshotScope(revision, template) + if err != nil { + return nil, err + } + return snapshotForQuiesce(revision, actor, expected) +} + +func snapshotForQuiesce(revision *database.RuntimeRevision, actor *ateapipb.Actor, expected ateapipb.SnapshotContentScope) (*database.SessionTaskSnapshot, error) { + atespace, name := actor.GetMetadata().GetAtespace(), actor.GetMetadata().GetName() + if actor.GetStatus().GetState() != ateapipb.ActorState_ACTOR_STATE_SUSPENDED { + return nil, fmt.Errorf("actor %s/%s has unsettled status %s", atespace, name, actor.GetStatus().GetState()) + } snapshot := actor.GetStatus().GetExternalSnapshot() if snapshot.GetSnapshotUri() == "" { return nil, fmt.Errorf("suspend Actor %s/%s returned no snapshot", atespace, name) } scope := snapshot.GetContentScope() - if scope != ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA { - return nil, fmt.Errorf("actor %s/%s returned invalid snapshot content scope %s", atespace, name, scope) + if scope != expected || snapshot.GetActorTemplateUid() != revision.ActorTemplateUID { + return nil, fmt.Errorf("actor %s/%s returned snapshot content scope %s from template %q; prepared revision requires %s from %q", + atespace, name, scope, snapshot.GetActorTemplateUid(), expected, revision.ActorTemplateUID) } return &database.SessionTaskSnapshot{ Atespace: atespace, URI: snapshot.GetSnapshotUri(), @@ -217,6 +265,24 @@ func (w *ActorWorkflow) Quiesce(ctx context.Context, session *apiv1alpha1.Sessio }, nil } +// quiesceSnapshotScope returns the scope Substrate records when an Actor of the +// prepared revision suspends. Substrate always records the template's OnCommit +// scope, including when it uploads a paused Actor's Full local snapshot, so the +// pinned template, not a fixed scope, is the expectation. +func quiesceSnapshotScope(revision *database.RuntimeRevision, template *ateapipb.ActorTemplate) (ateapipb.SnapshotContentScope, error) { + metadata := template.GetMetadata() + if metadata.GetAtespace() != revision.ActorTemplateAtespace || metadata.GetName() != revision.ActorTemplateName || + metadata.GetUid() == "" || metadata.GetUid() != revision.ActorTemplateUID { + return 0, fmt.Errorf("prepared ActorTemplate identity changed") + } + switch scope := template.GetSnapshotConfig().GetOnCommit(); scope { + case ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL: + return scope, nil + default: + return 0, fmt.Errorf("prepared ActorTemplate has unsupported quiesce snapshot scope %s", scope) + } +} + // Create provisions the persisted session once, using its pinned checkpoint for // forks. Retries return current state; an uncertain prior creation blocks execution. func (w *ActorWorkflow) Create(ctx context.Context, session *apiv1alpha1.Session) (*apiv1alpha1.Session, error) { @@ -382,6 +448,32 @@ func (w *ActorWorkflow) execute(ctx context.Context, operation *database.Session } } + if kind == apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_SUSPEND && operation.ExecutorID == uuid.Nil { + current, err := w.actors.GetActor(ctx, binding.Atespace, binding.Name) + if err != nil { + return nil, fmt.Errorf("observe Actor before suspension: %w", err) + } + if err := w.verifyActor(ctx, session, revision, current); err != nil { + return nil, err + } + if current.GetStatus().GetState() == ateapipb.ActorState_ACTOR_STATE_SUSPENDED { + // No runtime mutation is needed. Never claim this observation: an + // executor ID must continue to mean capture may have been issued, + // including after a failed or lost database completion reply. + finishCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + result, err := w.store.FinishObservedSessionSuspension(finishCtx, sessionID, operation.ID, session.PreparedRevision, current.GetMetadata().GetUid()) + if errors.Is(err, database.ErrConflict) { + observed, readErr := w.store.GetSessionOperation(finishCtx, sessionID, operation.ID) + if readErr != nil { + return nil, errors.Join(err, readErr) + } + return operationOutcome(observed) + } + return result, err + } + } + executorID := uuid.New() claimed, err := w.store.ClaimSessionOperation(ctx, sessionID, operation.ID, executorID) if err != nil { @@ -451,6 +543,11 @@ func (w *ActorWorkflow) execute(ctx context.Context, operation *database.Session if err := substrate.ApplyActorTransition(ctx, w.actors, transition); err != nil { return nil, fmt.Errorf("lifecycle operation %s remains pending: %w", operation.ID, err) } + if kind == apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_SUSPEND { + if _, err := w.observeQuiesce(ctx, session); err != nil { + return nil, fmt.Errorf("verify suspended runtime snapshot: %w", err) + } + } if kind == apiv1alpha1.RuntimeOperation_RUNTIME_OPERATION_DELETE { if err := w.credentials.Delete(ctx, *generation); err != nil { return nil, err @@ -521,12 +618,6 @@ func (w *ActorWorkflow) InspectPreparation(ctx context.Context, session *apiv1al if err != nil || association == nil { return nil, err } - reader, ok := w.actors.(interface { - GetActorTemplate(context.Context, string, string) (*ateapipb.ActorTemplate, error) - }) - if !ok { - return nil, fmt.Errorf("prepared template observation unavailable") - } revision, err := w.store.GetRuntimeRevision(ctx, session.GetPreparedRevision()) if err != nil { return nil, err @@ -535,7 +626,7 @@ func (w *ActorWorkflow) InspectPreparation(ctx context.Context, session *apiv1al if err != nil || actor.GetMetadata().GetUid() != association.ActorUid { return nil, fmt.Errorf("runtime identity changed") } - template, err := reader.GetActorTemplate(ctx, revision.ActorTemplateAtespace, revision.ActorTemplateName) + template, err := w.actors.GetActorTemplate(ctx, revision.ActorTemplateAtespace, revision.ActorTemplateName) if err != nil { return nil, err } diff --git a/go/core/internal/service/session/workflow_test.go b/go/core/internal/service/session/workflow_test.go index e835cef511..6bbf7feed9 100644 --- a/go/core/internal/service/session/workflow_test.go +++ b/go/core/internal/service/session/workflow_test.go @@ -159,12 +159,13 @@ func lifecycleFixture(t *testing.T) (*lifecycleTestStore, *apiv1alpha1.Session) require.NoError(t, client.RecordRuntimeRevision(t.Context(), *revision, true)) session, _, err := client.CreateSession(t.Context(), &apiv1alpha1.Session{Id: uuid.NewString(), Creator: "alice", Agent: &apiv1alpha1.ResourceReference{Namespace: "team-a", Name: "assistant"}}, uuid.NewString()) require.NoError(t, err) - return &lifecycleTestStore{Client: client, revision: revision}, session + return &lifecycleTestStore{Client: client, revision: revision, pool: pool}, session } type lifecycleTestStore struct { *database.Client revision *database.RuntimeRevision + pool *pgxpool.Pool } func (s *lifecycleTestStore) GetRuntimeRevision(context.Context, string) (*database.RuntimeRevision, error) { @@ -172,12 +173,14 @@ func (s *lifecycleTestStore) GetRuntimeRevision(context.Context, string) (*datab } type lifecycleTestActors struct { - mu sync.Mutex - actors map[string]*ateapipb.Actor - policyErr error - policy *ateapipb.EgressPolicy - policyActor string - policyCalls int + mu sync.Mutex + actors map[string]*ateapipb.Actor + template *ateapipb.ActorTemplate + snapshotScope ateapipb.SnapshotContentScope + policyErr error + policy *ateapipb.EgressPolicy + policyActor string + policyCalls int } func actorKey(atespace, name string) string { return atespace + "/" + name } @@ -192,6 +195,21 @@ func (a *lifecycleTestActors) GetActor(_ context.Context, atespace, name string) return proto.CloneOf(actor), nil } +func (a *lifecycleTestActors) GetActorTemplate(_ context.Context, atespace, name string) (*ateapipb.ActorTemplate, error) { + a.mu.Lock() + defer a.mu.Unlock() + if a.template != nil { + return proto.CloneOf(a.template), nil + } + return &ateapipb.ActorTemplate{ + Metadata: &ateapipb.ResourceMetadata{Atespace: atespace, Name: name, Uid: "actor-template-uid"}, + SnapshotConfig: &ateapipb.SnapshotConfig{ + OnPause: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL, + OnCommit: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, + }, + }, nil +} + func (a *lifecycleTestActors) CreateActor(_ context.Context, atespace, name, templateNamespace, templateName string) (*ateapipb.Actor, error) { a.mu.Lock() defer a.mu.Unlock() @@ -233,6 +251,7 @@ func (a *lifecycleTestActors) PauseActor(_ context.Context, atespace, name strin defer a.mu.Unlock() actor := a.actors[actorKey(atespace, name)] actor.Status.State = ateapipb.ActorState_ACTOR_STATE_PAUSED + actor.Status.LocalSnapshot = &ateapipb.LocalSnapshot{ContentScope: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_FULL} return proto.CloneOf(actor), nil } @@ -240,8 +259,19 @@ func (a *lifecycleTestActors) SuspendActor(_ context.Context, atespace, name str a.mu.Lock() defer a.mu.Unlock() actor := a.actors[actorKey(atespace, name)] + if actor.GetStatus().GetState() == ateapipb.ActorState_ACTOR_STATE_SUSPENDED { + return proto.CloneOf(actor), nil + } actor.Status.State = ateapipb.ActorState_ACTOR_STATE_SUSPENDED - actor.Status.ExternalSnapshot = &ateapipb.ExternalSnapshot{SnapshotUri: "s3://snapshots/snapshot-1", ContentScope: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA} + scope := a.snapshotScope + if scope == ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_UNSPECIFIED { + scope = ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA + } + templateUID := "actor-template-uid" + if a.template != nil { + templateUID = a.template.GetMetadata().GetUid() + } + actor.Status.ExternalSnapshot = &ateapipb.ExternalSnapshot{SnapshotUri: "s3://snapshots/snapshot-1", ContentScope: scope, ActorTemplateUid: templateUID} return proto.CloneOf(actor), nil } @@ -269,6 +299,8 @@ func lifecycleForkFixture(t *testing.T, store *lifecycleTestStore, actors *lifec t.Helper() source, err := NewActorWorkflow(store, actors, fixtureCredentials{}, "http://kagent-controller.kagent:8083").Create(t.Context(), source) require.NoError(t, err) + _, err = actors.ResumeActor(t.Context(), "team-a", fixtureActorName(t, store, source.Id)) + require.NoError(t, err) message := a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("hello")) message.ContextID = source.ContextId task := a2a.NewSubmittedTask(message, message)