Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions docs/architecture/runtime-and-lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
5 changes: 3 additions & 2 deletions docs/architecture/runtime-generation-identity.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
161 changes: 108 additions & 53 deletions go/core/internal/database/session_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -128,72 +128,127 @@ 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)
}
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
Expand Down
Loading
Loading