Skip to content
Merged
27 changes: 17 additions & 10 deletions docs/architecture/runtime-and-lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,9 @@ level with `session_id` and `idle_time`.

The runtime stages a final task update and acknowledges it after native cleanup.
That acknowledgement publishes task state and history atomically, without waiting
for pause/suspend. A Session lifecycle worker independently claims the idle
boundary in PostgreSQL. INPUT_REQUIRED/AUTH_REQUIRED pauses the actor on its node;
terminal work suspends it and records the exact external snapshot. Waiting tasks
for suspension. A Session lifecycle worker independently claims the idle
boundary in PostgreSQL. Both INPUT_REQUIRED/AUTH_REQUIRED and terminal work
suspend the Actor and record the exact external DATA snapshot. Waiting tasks
are not forkable. The Session stays logically READY, and Substrate ingress
resumes it when another authorized interaction arrives.

Expand Down Expand Up @@ -193,8 +193,8 @@ sequenceDiagram
Gateway-->>Client: current public task
Note over Worker,DB: Idle lifecycle runs independently of the client response
Worker->>DB: claim idle boundary unless new execution superseded it
Worker->>Actor: pause or suspend
Actor-->>Worker: settled native boundary
Worker->>Actor: suspend with DATA snapshot
Actor-->>Worker: suspended Actor and external DATA snapshot
Worker->>DB: record snapshot and finish idle claim
```

Expand All @@ -215,11 +215,18 @@ remains in PostgreSQL.

Substrate v0.5.0-alpha2 applies one content scope to every snapshot of an Actor,
both the node-local snapshot taken on pause and the one uploaded on suspend.
Templates use Full, so paused and suspended Actors keep their process memory, and
their checkpoints cannot be forked until Substrate's lifecycle v2 separates the two
scopes again. A Data snapshot resumes by starting fresh containers from the OCI
image with the saved durable directories; Substrate still restores one as Data when
the Actor's template changed after the snapshot was taken.
Agent and standalone sandbox templates use DATA. Resume starts fresh containers

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Small docs correction: can we also update the automatic-quiescence section and its sequence diagram? They still say waiting tasks pause on-node while only terminal tasks suspend externally, which contradicts the DATA behavior described here.

from the OCI image with the saved durable directories. Harnesses recover pending
approvals and user input from their durable state; sandbox guests start with a
fresh process registry. Agent checkpoints can be forked without carrying the
source session's process memory or runtime identity into the new session.

Codex and Claude record failed deferred continuations as `abandoned` in their
existing input journals. Admission rejects abandoned or restored unfinished
execution phases with an error requiring a new session, instead of restoring a
pending interaction for a failed task. Failures known to precede execution keep
the existing retry behavior. This rule is limited to durable deferred input;
general crash recovery and remote tool outcome reconciliation are follow-up work.

The Go ADK opens and migrates its SQLite session store before readiness, but
retains no idle database connections. Full and golden restores preserve guest
Expand Down
8 changes: 5 additions & 3 deletions docs/architecture/sandboxes.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,11 @@ prevent old results from overwriting newer database state.
Creation must finish before suspend/resume; deletion can supersede creation or
other operations and cannot be canceled into a live sandbox. Resume preserves
durable files; process handles last only as long as the guest's in-memory registry.
Sandboxes take Full snapshots until Substrate's lifecycle v2 (see
[Runtime and lifecycle](runtime-and-lifecycle.md)), so that registry survives
suspend and resume as well.
Sandboxes take DATA snapshots (see
[Runtime and lifecycle](runtime-and-lifecycle.md)). Resume starts a fresh guest
with the saved durable directories. Running processes stop during suspension,
and old process handles become unavailable after resume. Commands are not replayed;
callers can start new processes against the restored files.
Expiration immediately rejects new guest requests and lets the worker supersede
unfinished lifecycle work with deletion. Deletion finishes after backend cleanup,
releases runtime-artifact pins, and retains a tombstone and creation receipt so
Expand Down
4 changes: 2 additions & 2 deletions docs/architecture/telemetry-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ Kind `internal`. One execution segment of a runtime that emits its own invoke_ag

### `kagent.execute_tool.internal`

Refines `gen_ai.execute_tool.internal`, kind `internal`. One tool call of a harness turn. Named `execute_tool {gen_ai.tool.name}`. The span runs from the tool call to its result. A subagent tool goes under the execute_tool span of the tool call that started the subagent. Other tools go under the invoke_agent span. A call open across a pause starts no earlier than the segment its result arrives in. The call belongs to that segment, but a subagent tool stays under its parent tool span.
Refines `gen_ai.execute_tool.internal`, kind `internal`. One tool call of a harness turn. Named `execute_tool {gen_ai.tool.name}`. The span runs from the tool call to its result. A subagent tool goes under the execute_tool span of the tool call that started the subagent when that parent is known in the segment. Other tools go under the invoke_agent span. For Claude and Codex DATA continuations, non-gated calls still open at input publication are recorded as unfinished; this indicates a missing final result, not proof of remote failure. An approved deferred attempt is recorded in the resumed segment, excluding approval wait time. Claude includes replay startup; Codex includes the harness MCP caller setup and cleanup. Proven pre-execution failures suppress the span. Denial and supplying a cached result create no execution span. Previous tool parents are not restored across suspension.

| Attribute | Requirement | Note |
| --- | --- | --- |
Expand All @@ -328,7 +328,7 @@ Refines `gen_ai.execute_tool.internal`, kind `internal`. One tool call of a harn

### `kagent.inference.client`

Refines `gen_ai.client.inference`, kind `client`. One model request of a harness turn. Named `chat {gen_ai.request.model}`, or `chat` when the request model is unknown. A subagent model call goes under the execute_tool span of the tool call that started the subagent. Examples are the Claude `Agent` tool and the Codex `spawnAgent` call. This rule also applies when the tool span is in a later segment. Other model calls go under the invoke_agent span. A subagent model call can start outside the time of its parent span. A Codex `spawnAgent` call ends when the subagent starts, so the subagent model calls start after that span ends. After a pause, the tool span starts in the later segment, so earlier subagent model calls start before it. A call that ended with finish reason `error` has an error status, unless it was canceled. One span covers a call and all its automatic retries, and only a final failure gives it an error status. A Claude call's token counts add up every attempt that the provider started. Codex reports usage only for the attempt that succeeded, and none for a call canceled mid-response. Codex errors of the `other` and `badRequest` categories can also come from outside a model request, and they still give a failed call. Codex reports no call times, so a Codex call starts at the previous call's usage report or final error. It ends when its first tool starts or the turn pauses for input, or else at its own usage report or final error. The first call of a Codex subagent starts when its `spawnAgent` call first names its thread.
Refines `gen_ai.client.inference`, kind `client`. One model request of a harness turn. Named `chat {gen_ai.request.model}`, or `chat` when the request model is unknown. A subagent model call goes under the execute_tool span of the tool call that started the subagent when that parent is known in the segment. Examples are the Claude `Agent` tool and the Codex `spawnAgent` call. For Claude and Codex DATA continuations, parent bookkeeping is local to an execution segment; it is not restored across suspension. Other model calls go under the current invoke_agent span. A subagent model call can start outside the time of its parent span. A Codex `spawnAgent` call ends when the subagent starts, so the subagent model calls start after that span ends. A call that ended with finish reason `error` has an error status, unless it was canceled. One span covers a call and all its automatic retries, and only a final failure gives it an error status. A Claude call's token counts add up every attempt that the provider started. Codex reports usage only for the attempt that succeeded, and none for a call canceled mid-response. Codex errors of the `other` and `badRequest` categories can also come from outside a model request, and they still give a failed call. Codex reports no call times, so a Codex call starts at the previous call's usage report or final error. It ends when its first tool starts or the turn pauses for input, or else at its own usage report or final error. The first call of a Codex subagent starts when its `spawnAgent` call first names its thread.

| Attribute | Requirement | Note |
| --- | --- | --- |
Expand Down
8 changes: 6 additions & 2 deletions go/adk/pkg/taskstore/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,12 @@ func (e *settledExecutor) Before(ctx context.Context, call *a2asrv.CallContext,
if send.Message == nil {
return ctx, nil, a2a.ErrInvalidParams
}
if reservation, ok := e.AgentExecutor.(interface{ ReservedTaskID() a2a.TaskID }); ok {
if id := reservation.ReservedTaskID(); id != "" && send.Message.TaskID != id {
if reservation, ok := e.AgentExecutor.(interface{ ReservedTaskID() (a2a.TaskID, error) }); ok {
id, err := reservation.ReservedTaskID()
if err != nil {
return ctx, nil, a2a.NewError(a2a.ErrUnsupportedOperation, err.Error())
}
if id != "" && send.Message.TaskID != id {
return ctx, nil, a2a.NewError(a2a.ErrUnsupportedOperation, "native session is waiting for another task")
}
}
Expand Down
17 changes: 17 additions & 0 deletions go/adk/pkg/taskstore/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -407,3 +407,20 @@ func TestSendAdmissionReleasesWhenCallEndsBeforeExecution(t *testing.T) {
})
}
}

type unavailableExecutor struct {
a2asrv.AgentExecutor
}

func (unavailableExecutor) ReservedTaskID() (a2a.TaskID, error) {
return "", errors.New("native session cannot continue; start a new session")
}

func TestSendAdmissionReportsUnusableSessionBeforeAcceptingInput(t *testing.T) {
wrapper := (&Store{}).WrapExecutor(unavailableExecutor{}, "", nil)
ctx, call := a2asrv.NewCallContext(t.Context(), nil)
_, _, err := wrapper.Before(ctx, call, &a2asrv.Request{Payload: &a2a.SendMessageRequest{Message: a2a.NewMessage(a2a.MessageRoleUser)}})
require.ErrorContains(t, err, "start a new session")
require.Nil(t, wrapper.admitted)
require.Empty(t, wrapper.pending)
}
5 changes: 5 additions & 0 deletions go/api/a2a/hitl.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,11 @@ func ValidateAskUserResponse(request *AskUserRequest, response *AskUserResponse)
if len(response.Answers) != len(request.Questions) {
return fmt.Errorf("ask-user response must answer every question")
}
for i, answer := range response.Answers {
if len(answer.Answer) == 0 || !request.Questions[i].Multiple && len(answer.Answer) != 1 {
return fmt.Errorf("ask-user response has invalid selection for question %d", i)
}
}
return nil
}

Expand Down
27 changes: 27 additions & 0 deletions go/api/a2a/hitl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"testing"

a2atype "github.com/a2aproject/a2a-go/v2/a2a"
"github.com/stretchr/testify/require"
)

func TestParseToolApprovalResponseAcceptsEveryPendingDecision(t *testing.T) {
Expand Down Expand Up @@ -98,3 +99,29 @@ func TestValidateAskUserResponseRequiresEveryAnswer(t *testing.T) {
t.Fatal("ValidateAskUserResponse() accepted an incomplete response")
}
}

func TestValidateAskUserResponseSelections(t *testing.T) {
for _, test := range []struct {
name string
multiple bool
answer []string
wantErr bool
}{
{name: "empty single", wantErr: true},
{name: "empty multiple", multiple: true, wantErr: true},
{name: "too many single", answer: []string{"one", "two"}, wantErr: true},
{name: "free text", answer: []string{"custom answer"}},
{name: "multiple selections", multiple: true, answer: []string{"one", "two"}},
} {
t.Run(test.name, func(t *testing.T) {
request := &AskUserRequest{ID: "question", Questions: []HITLQuestion{{Question: "Choose", Multiple: test.multiple}}}
response := &AskUserResponse{ID: request.ID, Answers: []AskUserAnswer{{Answer: test.answer}}}
err := ValidateAskUserResponse(request, response)
if test.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}
}
3 changes: 2 additions & 1 deletion go/core/internal/database/client_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,8 @@ func TestSessionReplyArchivesStatusMessageAtomically(t *testing.T) {
require.NoError(t, client.SettleSessionTask(ctx, sessionID, string(parked.ID), version))
boundary, err := client.ClaimSessionQuiescence(ctx)
require.NoError(t, err)
require.NoError(t, client.FinishSessionQuiescence(ctx, boundary, nil))
require.Error(t, client.FinishSessionQuiescence(ctx, boundary, nil))
require.NoError(t, client.FinishSessionQuiescence(ctx, boundary, &SessionTaskSnapshot{Atespace: "team-a", URI: "s3://snapshots/waiting", ContentScope: "DATA"}))

answer := &a2a.Message{ID: "answer-1", Role: a2a.MessageRoleUser, TaskID: "task-1", ContextID: session.ContextId}
resumed := *parked
Expand Down
12 changes: 6 additions & 6 deletions go/core/internal/database/session_quiescence.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (
apiv1 "github.com/kagent-dev/kagent/go/api/gen/kagent/api/v1"
)

// SessionQuiescence grants one worker permission to pause an idle session or
// suspend it and record its snapshot. Task publication has already completed.
// SessionQuiescence grants one worker permission to suspend an idle session
// and record its snapshot. Task publication has already completed.
type SessionQuiescence struct {
Session *apiv1.Session
TaskID string
Expand Down Expand Up @@ -102,16 +102,16 @@ func (c *Client) ClaimSessionQuiescence(ctx context.Context) (*SessionQuiescence
return result, err
}

// FinishSessionQuiescence records a claimed pause/suspend outcome and releases
// the session for new execution. Terminal tasks require the matching snapshot.
// FinishSessionQuiescence records a claimed suspension outcome and releases
// the session for new execution. Every settled task requires the matching snapshot.
// Retries are harmless, and a stale claim cannot release another operation.
// Task state and history remain readable throughout lifecycle work.
func (c *Client) FinishSessionQuiescence(ctx context.Context, work *SessionQuiescence, snapshot *SessionTaskSnapshot) error {
if work == nil || work.ExecutorID == uuid.Nil {
return fmt.Errorf("claimed task boundary is required")
}
if work.State.Terminal() && (snapshot == nil || snapshot.URI == "" || snapshot.Atespace == "" || snapshot.ContentScope == "") {
return fmt.Errorf("terminal task quiescence requires a runtime snapshot")
if snapshot == nil || snapshot.URI == "" || snapshot.Atespace == "" || snapshot.ContentScope == "" {
return fmt.Errorf("task quiescence requires a runtime snapshot")
}
return c.withTx(ctx, func(tx pgx.Tx) error {
session, err := lockSession(ctx, tx, work.Session.Id)
Expand Down
3 changes: 3 additions & 0 deletions go/core/internal/database/task_fixtures_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ func saveRuntimeTask(t *testing.T, client *Client, sessionID string, task *a2a.T
}
require.Equal(t, sessionID, work.Session.Id)
require.Equal(t, string(task.ID), work.TaskID)
if snapshot == nil && !work.State.Terminal() {
snapshot = &SessionTaskSnapshot{Atespace: "team-a", URI: "s3://snapshots/waiting-" + work.TaskID, ContentScope: "DATA"}
}
return client.FinishSessionQuiescence(ctx, work, snapshot)
}

Expand Down
1 change: 1 addition & 0 deletions go/core/internal/service/sandbox/guest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ func (a *testActors) SuspendActor(context.Context, string, string) (*ateapipb.Ac
defer a.mu.Unlock()
a.calls = append(a.calls, "suspend")
a.actor.Status.State = ateapipb.ActorState_ACTOR_STATE_SUSPENDED
a.actor.Status.ExternalSnapshot = &ateapipb.ExternalSnapshot{SnapshotUri: "s3://snapshots/sandbox", ContentScope: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA}
return proto.CloneOf(a.actor), a.mutationErr
}
func (a *testActors) DeleteActor(context.Context, string, string) error {
Expand Down
1 change: 1 addition & 0 deletions go/core/internal/service/sandbox/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ func (a *testActors) SuspendActor(context.Context, string, string) (*ateapipb.Ac
}
a.calls = append(a.calls, "suspend")
a.actor.Status.State = ateapipb.ActorState_ACTOR_STATE_SUSPENDED
a.actor.Status.ExternalSnapshot = &ateapipb.ExternalSnapshot{SnapshotUri: "s3://snapshots/sandbox", ContentScope: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA}
return proto.CloneOf(a.actor), a.mutationErr
}
func (a *testActors) DeleteActor(context.Context, string, string) error {
Expand Down
10 changes: 2 additions & 8 deletions go/core/internal/service/session/quiescence.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func (w *ActorWorkflow) wakeQuiescence() {
}
}

// Start pauses or suspends idle sessions independently of task publication.
// Start suspends idle sessions to DATA independently of task publication.
// Startup and periodic recovery scans discover work missed by local signals.
// Workers drain claims with bounded concurrency; task reads never wait for them.
func (w *ActorWorkflow) Start(ctx context.Context) error {
Expand Down Expand Up @@ -74,13 +74,7 @@ func (w *ActorWorkflow) Start(ctx context.Context) error {

func (w *ActorWorkflow) quiesceIdleSession(ctx context.Context, work *database.SessionQuiescence) {
runtimeCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
var snapshot *database.SessionTaskSnapshot
var err error
if work.State.Terminal() {
snapshot, err = w.Quiesce(runtimeCtx, work.Session)
} else {
err = w.Pause(runtimeCtx, work.Session)
}
snapshot, err := w.Quiesce(runtimeCtx, work.Session)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we add E2E coverage that waits for a verified DATA snapshot and suspended Actor before answering pending input? The approval helper replies immediately after INPUT_REQUIRED, so it can supersede unclaimed quiescence and pass without replacing the harness. The ask-user suspension test also skips Claude and Codex.

Approval, denial, cancellation, and native ask-user responses should exercise that restore boundary.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Extended E2E coverage

cancel()
if err != nil {
// No timeout-based takeover: the Substrate request may still complete.
Expand Down
6 changes: 3 additions & 3 deletions go/core/internal/service/session/quiescence_wake_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,13 +183,13 @@ func TestQuiescenceDrainsConcurrentSettlementsAcrossReplicas(t *testing.T) {
require.Equal(t, 1, calls, "each durable claim must run exactly once across replicas")
actor, err := base.GetActor(t.Context(), "team-a", name)
require.NoError(t, err)
require.Equal(t, ateapipb.ActorState_ACTOR_STATE_SUSPENDED, actor.Status.State)
require.Equal(t, ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA, actor.GetStatus().GetExternalSnapshot().GetContentScope())
require.NotEmpty(t, actor.GetStatus().GetExternalSnapshot().GetSnapshotUri())
if states[i%len(states)].Terminal() {
require.Equal(t, ateapipb.ActorState_ACTOR_STATE_SUSPENDED, actor.Status.State)
_, snapshot, err := store.ReserveSessionCheckpoint(t.Context(), &apiv1.Checkpoint{Id: uuid.NewString(), SessionId: session.Id, HeadTaskId: requests[i].TaskId}, "alice", uuid.NewString())
require.NoError(t, err)
require.Equal(t, "s3://snapshots/snapshot-1", snapshot.URI)
} else {
require.Equal(t, ateapipb.ActorState_ACTOR_STATE_PAUSED, actor.Status.State)
}
}
}
Expand Down
Loading
Loading