Skip to content
Open
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
32 changes: 24 additions & 8 deletions api/genpb/session_grpc.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 6 additions & 4 deletions api/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,10 @@ type Runtime interface {
// ErrMemoryStateLost when another instance is there, or none is, before it captures anything
// if it can tell, and in any case before returning a ref: a snapshot of a replacement would
// hand its callers compute that holds none of the session's state. in.RecordedCheckpoint is
// the checkpoint the journal last recorded; a backend may refuse, with ErrMemoryStateLost,
// compute that holds another one (see Incarnation.RecordedCheckpoint).
// the checkpoint the journal last recorded. A backend whose compute can retain captures must
// refuse, with ErrMemoryStateLost and before recapturing, compute that holds another one (see
// Incarnation.RecordedCheckpoint). This quarantines a physical capture whose journal append lost
// a race after Snapshot returned.
Snapshot(ctx context.Context, in Incarnation, kind SnapshotKind) (SnapshotRef, error)

// Restore brings an incarnation back from a snapshot and returns a nonempty ID.
Expand Down Expand Up @@ -344,8 +346,8 @@ type SessionSpec struct {
// its first Suspend (a parent's SUSPEND in a child's copied prefix is not the child's).
//
// A backend whose compute can hold a snapshot the journal never recorded (substrate: a capture a
// memory-tier Snapshot refused stays on the actor) compares it with the snapshot the existing
// compute holds before attaching to or resuming it, and refuses another with
// memory-tier Snapshot refused stays on the actor) must compare it with the snapshot the existing
// compute holds before attaching to, resuming or snapshotting it, and refuses another with
// ErrMemoryStateLost. Like StartedTurns it is a function, so the backend reads the journal only
// after it has read the compute, and sees a SUSPEND another host recorded in between. A backend
// that does not need it does not call it. Nil declares no recorded checkpoint.
Expand Down
16 changes: 12 additions & 4 deletions api/session.proto
Original file line number Diff line number Diff line change
Expand Up @@ -344,8 +344,8 @@ message Delta {
// is classified.
// ABORTED: STALE_CURSOR, SESSION_BUSY, COMPUTE_BUSY, CHECKPOINT_IN_PROGRESS, FENCED,
// SNAPSHOT_SUPERSEDED (Fork only).
// FAILED_PRECONDITION: SESSION_DELETED, MEMORY_STATE_LOST, CHECKPOINT_INVALID,
// COMPUTE_CONFIG_INVALID.
// FAILED_PRECONDITION: SESSION_DELETED, CHECKPOINT_INCOMPLETE_TURN, MEMORY_STATE_LOST,
// CHECKPOINT_INVALID, COMPUTE_CONFIG_INVALID.
// UNAVAILABLE: CHECKPOINT_PENDING, HARNESS_UNAVAILABLE, COMPUTE_UNAVAILABLE.
// RESOURCE_EXHAUSTED: COMPUTE_RESOURCE_EXHAUSTED.
// DeleteSession reports SESSION_BUSY and SESSION_DELETED; Exec, Resume, Suspend, Fork, Approve
Expand Down Expand Up @@ -472,7 +472,12 @@ service Sessions {
// node-local warm checkpoint, so a session goes straight from live to a cold snapshot.
// Suspend routes an owned unreceipted approval to its recorded harness; inherited approvals
// and ordinary sessions use their stored default. An unserved recorded name is
// FAILED_PRECONDITION, with no fallback.
// FAILED_PRECONDITION, with no fallback. On a memory-capable backend Suspend admits the harness
// before fencing or snapshotting so it can apply memory-tier checkpoint safety: an unreachable
// harness is UNAVAILABLE; a descriptor mismatch or invalid class is FAILED_PRECONDITION.
// If the latest turn is incomplete and recovery may run it again, a REQUIRES_MEMORY_SNAPSHOT
// Suspend returns FAILED_PRECONDITION (CHECKPOINT_INCOMPLETE_TURN) before snapshotting or
// appending SUSPEND.
rpc Suspend(SuspendRequest) returns (Session); // cold, free worker
// A recorded override where either harness is REQUIRES_MEMORY_SNAPSHOT is
// FAILED_PRECONDITION before compute changes or journal repair, as for Exec admission.
Expand All @@ -494,6 +499,9 @@ service Sessions {
// snapshot. If the fan-out then fails, the checkpoint is not rolled back and the parent is not
// resumed automatically. A pending approval keeps it parked, and a turn can run on it while the
// failed children are stopped. A retry must fork at the new head (at_seq <= 0, or the new head's
// seq).
// seq). Absent an existing checkpoint mark, a REQUIRES_MEMORY_SNAPSHOT Fork returns ABORTED
// (SESSION_BUSY) when a locally active parent turn or its pre-journal preparation holds operation
// admission, without canceling it; if the latest turn is incomplete and recovery may run it again,
// Fork returns FAILED_PRECONDITION (CHECKPOINT_INCOMPLETE_TURN) before checkpoint side effects.
rpc Fork(ForkRequest) returns (ForkResponse);
}
28 changes: 28 additions & 0 deletions changelog/unreleased/incomplete-memory-checkpoint-compat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
category: Compatibility
---

- A `REQUIRES_MEMORY_SNAPSHOT` Fork of a locally active parent now returns `ABORTED` with
`agentsessions/SESSION_BUSY` without ending or fencing the turn. Earlier hosts let Fork proceed:
they fenced and ended the turn, which returned `ABORTED` with
`agentsessions/CHECKPOINT_IN_PROGRESS`, before attempting the parent checkpoint. Pre-journal
preparation is now refused the same way as an active turn.
- Memory-tier Suspend and Fork now return `FAILED_PRECONDITION` with
`agentsessions/CHECKPOINT_INCOMPLETE_TURN` when the latest turn is incomplete and recovery may run
it again. This includes a turn still running through another writer that shares the journal; a
retry passes this check after it records `END`. Earlier hosts accepted and checkpointed that
boundary.
- On a backend that advertises memory snapshots, Suspend now admits the harness before fencing or
snapshotting. While the caller remains live, an unreachable harness returns `UNAVAILABLE` with
`agentsessions/HARNESS_UNAVAILABLE`; a descriptor mismatch or invalid harness class returns
`FAILED_PRECONDITION`.
- Fork failures wrapping `controller.ErrInvalidExecutionLog` or `controller.ErrReplayDiverged` now
return `FAILED_PRECONDITION` instead of `INTERNAL`. Suspend failures wrapping
`eventlog.ErrTampered` now return `DATA_LOSS` instead of `INTERNAL`.
- A custom memory `api.Runtime` whose compute can retain captures must compare its held capture with
`SessionSpec.RecordedCheckpoint`, `Incarnation.RecordedCheckpoint`, or the ref passed to
`Restore`, and return `api.ErrMemoryStateLost` before attaching, resuming, or recapturing when
they differ.
Upgrade every such Runtime before, or atomically with, Sessions hosts built with this change. On
rollback, roll back Sessions hosts first; do not restore a non-enforcing Runtime while an
unrecorded capture may remain.
13 changes: 13 additions & 0 deletions changelog/unreleased/incomplete-memory-checkpoint.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
category: Fixed
Comment thread
Tatsinnit marked this conversation as resolved.
Resolved
---

- Memory-tier Suspend and Fork refuse an incomplete execution before snapshotting. This prevents a
snapshot from capturing an unjournaled RAM mutation that recovery could apply a second time.
- A stateful Fork no longer cancels a running parent turn. Active contention is `ABORTED`; an
abandoned incomplete turn is `FAILED_PRECONDITION` with `CHECKPOINT_INCOMPLETE_TURN`.
- Memory-tier Suspend fences before capture and commits `SUSPEND` only at the journal head it
validated, refusing peer movement instead of accepting it under the captured RAM.
- Memory-capable Suspend now describes the harness before fencing or snapshotting to apply the
memory-tier rule. Custom memory Runtime implementations must quarantine captures the journal did
not record by refusing a mismatched `RecordedCheckpoint`.
83 changes: 83 additions & 0 deletions controller/checkpoint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package controller

import (
"errors"

"github.com/agent-primitives/sessions/api"
"github.com/agent-primitives/sessions/eventlog"
)

// ErrCheckpointIncompleteTurn refuses a memory checkpoint whose latest execution recovery may run
// again. Capturing RAM after the harness changed it but before END committed would let Resume apply
// the same mutation twice.
var ErrCheckpointIncompleteTurn = errors.New("controller: checkpoint refused because the latest execution is incomplete and recovery may run it again")

// ValidateCheckpointState verifies records and reports whether a memory checkpoint can be taken
// without capturing a turn that Resume may run again. A partial input prefix is safe because the
// harness was not invoked. An owned undecided approval request and an inherited unresolved request
// are also safe: recovery parks or refuses them without invoking the harness. A decided gate is not
// safe: an earlier recovery may have changed RAM before failing without a receipt.
func ValidateCheckpointState(records []eventlog.Record) error {
if err := verifyRecords("", records); err != nil {
return err
}
events := make([]api.Event, 0, len(records))
for _, record := range records {
events = append(events, record.Event)
}
executions, err := recordedExecutions(events)
if err != nil {
return err
}
scan, err := scanApprovalRecords(records, 0)
if err != nil {
return err
}
execution, err := pendingResumeExecution(events, executions)
if err != nil {
if errors.Is(err, ErrIncompleteInvocation) && len(executions) > 0 &&
incompleteInputPrefix(events, executions[len(executions)-1]) {
return nil
}
return err
}
if execution == nil {
return nil
}
if state := scan.selected; state != nil && state.ExecutionID == execution.id && state.Receipt == nil {
if state.Inherited || state.Request != nil && state.Decision == nil {
return nil
}
}
return ErrCheckpointIncompleteTurn
}

// incompleteInputPrefix recognizes only the prefix Exec can leave before Harness.Run: one valid
// start followed by fewer valid inputs than it declared, with no later event from any execution.
func incompleteInputPrefix(events []api.Event, execution recordedExecution) bool {
if !execution.hasStart || execution.completed || execution.inputCount == nil ||
execution.inputRecords != len(execution.inputs) || int64(execution.inputRecords) >= *execution.inputCount {
return false
}
for i, event := range events[execution.start:] {
if event.Kind == api.EventLifecycle {
continue
}
if event.ExecutionID != execution.id {
return false
}
switch event.Kind {
case api.EventExecutionStart:
if i != 0 || event.ExecutionStart == nil {
return false
}
case api.EventInput:
if event.Message == nil {
return false
}
default:
return false
}
}
return true
}
81 changes: 81 additions & 0 deletions controller/checkpoint_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package controller

import (
"errors"
"testing"

"github.com/agent-primitives/sessions/api"
"github.com/agent-primitives/sessions/eventlog"
)

func checkpointRecords(t *testing.T, events ...api.Event) []eventlog.Record {
t.Helper()
log := gateLog(t, events...)
records, err := log.Read(1)
if err != nil {
t.Fatal(err)
}
return records
}

func TestValidateCheckpointState(t *testing.T) {
zero, one, two := int64(0), int64(1), int64(2)
start := func(id string, count *int64) api.Event {
return api.Event{ExecutionID: id, Kind: api.EventExecutionStart, ExecutionStart: &api.ExecutionStart{InputCount: count}}
}
input := func(id string) api.Event {
return api.Event{ExecutionID: id, Kind: api.EventInput, Message: api.TextMessage("user", "hi")}
}
end := func(id string) api.Event {
return api.Event{ExecutionID: id, Kind: api.EventEnd, End: &api.HarnessEnd{State: "COMPLETED"}}
}
failure := api.Event{ExecutionID: "e", Kind: api.EventError, Err: &api.Error{Description: "failed"}}
lifecycle := api.Event{Kind: api.EventLifecycle, Lifecycle: &api.Lifecycle{Kind: api.LifecycleSuspend}}

for _, tc := range []struct {
name string
events []api.Event
want error
}{
{name: "empty"},
{name: "lifecycle only", events: []api.Event{lifecycle}},
{name: "completed", events: []api.Event{start("e", &one), input("e"), end("e")}},
{name: "modern pending", events: []api.Event{start("e", &one), input("e")}, want: ErrCheckpointIncompleteTurn},
{name: "modern error remains pending", events: []api.Event{start("e", &zero), failure}, want: ErrCheckpointIncompleteTurn},
{name: "markerless modern pending", events: []api.Event{input("e")}, want: ErrCheckpointIncompleteTurn},
{name: "partial input prefix", events: []api.Event{start("e", &two), input("e")}},
{name: "partial input with error is invalid", events: []api.Event{start("e", &two), input("e"), failure}, want: ErrInvalidExecutionLog},
{name: "legacy pending", events: []api.Event{{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}}, want: ErrCheckpointIncompleteTurn},
{name: "legacy end", events: []api.Event{{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}, {Kind: api.EventEnd}}},
{name: "legacy error", events: []api.Event{{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}, {Kind: api.EventError, Err: &api.Error{Description: "failed"}}}},
{name: "older incomplete superseded", events: []api.Event{start("old", &zero), start("new", &zero), end("new")}},
{name: "approval call only", events: gateEvents()[:2], want: ErrCheckpointIncompleteTurn},
{name: "approval pending", events: gateEvents()[:3]},
{name: "approval decided", events: gateEvents()[:4], want: ErrCheckpointIncompleteTurn},
{name: "approval decided recovery failed", events: append(append([]api.Event(nil), gateEvents()[:4]...), failure), want: ErrCheckpointIncompleteTurn},
{name: "approval receipt remains pending", events: gateEvents()[:5], want: ErrCheckpointIncompleteTurn},
{name: "approval completed", events: gateEvents()},
} {
t.Run(tc.name, func(t *testing.T) {
err := ValidateCheckpointState(checkpointRecords(t, tc.events...))
if tc.want == nil && err != nil || tc.want != nil && !errors.Is(err, tc.want) {
t.Fatalf("ValidateCheckpointState = %v, want %v", err, tc.want)
}
})
}
}

func TestValidateCheckpointStateAllowsInheritedOpenApproval(t *testing.T) {
parent := gateLog(t, gateEvents()[:4]...)
child := gateLog(t)
if err := Fork(parent, child, 4); err != nil {
t.Fatal(err)
}
records, err := child.Read(1)
if err != nil {
t.Fatal(err)
}
if err := ValidateCheckpointState(records); err != nil {
t.Fatalf("ValidateCheckpointState = %v", err)
}
}
Loading