From 7e06d5fe6cb714221283ebceb72f1278bde3d8a9 Mon Sep 17 00:00:00 2001 From: Tatsat Mishra Date: Fri, 27 Nov 2026 21:37:41 +1300 Subject: [PATCH 1/5] fix(placement): refuse unsafe memory checkpoints --- api/genpb/session_grpc.pb.go | 16 +- api/runtime.go | 10 +- api/session.proto | 8 +- .../incomplete-memory-checkpoint.md | 13 + controller/checkpoint.go | 83 +++ controller/checkpoint_test.go | 81 +++ docs/api-reference.md | 6 +- docs/architecture.md | 9 +- docs/faq.md | 7 +- docs/substrate-conformance.md | 31 +- placement/approval_test.go | 9 +- placement/cleanup_resources_test.go | 51 ++ placement/compute_guard.go | 5 +- placement/compute_guard_test.go | 16 - placement/fork_verify_test.go | 8 +- placement/legacy_inventory_test.go | 12 +- placement/memory_approval_test.go | 14 +- placement/placement.go | 183 ++++-- placement/placement_test.go | 99 ++-- placement/registry.go | 4 +- placement/registry_add_test.go | 10 +- placement/resume_cas_test.go | 37 +- placement/session_guard.go | 5 +- placement/suspend_test.go | 152 ++++- placement/transport_test.go | 552 ++++-------------- session/approval_override_test.go | 8 + session/checkpoint_test.go | 162 +++-- session/error_reasons_test.go | 4 + session/errors.go | 2 + session/fork_wake_test.go | 128 ---- session/service.go | 11 +- spec.md | 51 +- 32 files changed, 926 insertions(+), 861 deletions(-) create mode 100644 changelog/unreleased/incomplete-memory-checkpoint.md create mode 100644 controller/checkpoint.go create mode 100644 controller/checkpoint_test.go diff --git a/api/genpb/session_grpc.pb.go b/api/genpb/session_grpc.pb.go index 4f4cdca9..bd9625e6 100644 --- a/api/genpb/session_grpc.pb.go +++ b/api/genpb/session_grpc.pb.go @@ -48,8 +48,8 @@ const ( // 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 @@ -171,7 +171,9 @@ type SessionsClient interface { // 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. Suspend(ctx context.Context, in *SuspendRequest, opts ...grpc.CallOption) (*Session, error) // A recorded override where either harness is REQUIRES_MEMORY_SNAPSHOT is // FAILED_PRECONDITION before compute changes or journal repair, as for Exec admission. @@ -352,8 +354,8 @@ func (c *sessionsClient) Fork(ctx context.Context, in *ForkRequest, opts ...grpc // 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 @@ -475,7 +477,9 @@ type SessionsServer interface { // 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. Suspend(context.Context, *SuspendRequest) (*Session, error) // A recorded override where either harness is REQUIRES_MEMORY_SNAPSHOT is // FAILED_PRECONDITION before compute changes or journal repair, as for Exec admission. diff --git a/api/runtime.go b/api/runtime.go index d6690918..32dba2ce 100644 --- a/api/runtime.go +++ b/api/runtime.go @@ -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. @@ -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. diff --git a/api/session.proto b/api/session.proto index 271de789..f108fd5c 100644 --- a/api/session.proto +++ b/api/session.proto @@ -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 @@ -472,7 +472,9 @@ 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. 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. diff --git a/changelog/unreleased/incomplete-memory-checkpoint.md b/changelog/unreleased/incomplete-memory-checkpoint.md new file mode 100644 index 00000000..5e84cccf --- /dev/null +++ b/changelog/unreleased/incomplete-memory-checkpoint.md @@ -0,0 +1,13 @@ +--- +category: Fixed +--- + +- 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`. diff --git a/controller/checkpoint.go b/controller/checkpoint.go new file mode 100644 index 00000000..75690927 --- /dev/null +++ b/controller/checkpoint.go @@ -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 +} diff --git a/controller/checkpoint_test.go b/controller/checkpoint_test.go new file mode 100644 index 00000000..7ce58994 --- /dev/null +++ b/controller/checkpoint_test.go @@ -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) + } +} diff --git a/docs/api-reference.md b/docs/api-reference.md index 047e5232..6f8d3fd4 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -1805,8 +1805,8 @@ they apply to Exec, Resume, Suspend, Fork, Approve and CloseApproval wherever th 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 @@ -1854,7 +1854,7 @@ provide required-mode deployment or transport assembly. | Approve | [ApproveRequest](#agentsessions-v1-ApproveRequest) | [ApproveResponse](#agentsessions-v1-ApproveResponse) | Implemented durable approval decisions for STATELESS_REPLAY and REQUIRES_MEMORY_SNAPSHOT executions. OK commits only a decision; the caller must Resume to continue. An exact retry of the tuple, approved value, reason, identity and verified approver returns the existing decision, even after resolution. A changed decision/reason/identity, or a different verified approver, for that request is FAILED_PRECONDITION, never an overwrite. INVALID_ARGUMENT: missing session/execution/tool-call tuple, non-positive request_seq, or absent approved. NOT_FOUND: unknown session. FAILED_PRECONDITION: stale, inherited, or wrong request tuple, changed decision, or invalid recorded approval evidence. The gate cannot be created for an in-process harness that declares any other tier; a wire harness that omits its tier or sends an unknown one is read as STATELESS_REPLAY and gets the gate (spec APR-1, WIRE-3). Approve does not Describe or resolve a harness. ABORTED: local contention (including a live Resume or a stateful Fork), append-CAS conflict or superseded fence; retry after reading the session. Identity is unverified provenance, ignored by an enforcing Go host. Independent read+approve permission checks are opt-in. This method does not run a host's pre-dispatch tool policy hook (it runs when recovery dispatches the approved call) and implies no expiry, implicit Resume, or Cancel behavior. | | CloseApproval | [CloseApprovalRequest](#agentsessions-v1-CloseApprovalRequest) | [CloseApprovalResponse](#agentsessions-v1-CloseApprovalResponse) | Closes an approval gate the harness cannot re-issue, writing only journal records: no harness, executor or compute runs. OK returns the gate's decision and receipt; after it Exec admits a new turn. A retry, or a close of a gate that already has a receipt from any writer, returns the existing records without writing. The closed execution gets no END: Resume re-drives it and serves the receipt to a harness that re-issues the call. A REQUIRES_MEMORY_SNAPSHOT harness restored at the gate cannot continue there unless the gate is the execution's first effect (spec APR-19); Exec is that session's route. Closing an approved gate revokes the approval for later recovery but cannot stop an executor call another host already dispatched, so its receipt is OUTCOME_UNKNOWN. INVALID_ARGUMENT: missing session/execution/tool-call tuple or non-positive request_seq. NOT_FOUND: unknown session. FAILED_PRECONDITION: deleted session; wrong, inherited or superseded request tuple, or one whose request was never journaled; or invalid recorded approval evidence. DATA_LOSS: the journal fails hash-chain verification. ABORTED: local contention (including a live Resume or a stateful Fork), append-CAS conflict or superseded fence; retry after reading the session. Independent read+approval.close permission checks are opt-in. | | Cancel | [CancelRequest](#agentsessions-v1-CancelRequest) | [Session](#agentsessions-v1-Session) | In-flight control: cancel the running execution. Not implemented: the server returns UNIMPLEMENTED. | -| Suspend | [SuspendRequest](#agentsessions-v1-SuspendRequest) | [Session](#agentsessions-v1-Session) | Compute-layer durability. There is no warm Pause: no Runtime backend implements a 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. cold, free worker | +| Suspend | [SuspendRequest](#agentsessions-v1-SuspendRequest) | [Session](#agentsessions-v1-Session) | Compute-layer durability. There is no warm Pause: no Runtime backend implements a 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. 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. cold, free worker | | Resume | [ResumeRequest](#agentsessions-v1-ResumeRequest) | [Session](#agentsessions-v1-Session) | A recorded override where either harness is REQUIRES_MEMORY_SNAPSHOT is FAILED_PRECONDITION before compute changes or journal repair, as for Exec admission. Otherwise an unresolved owned approval returns its current paused Session without runtime IO. A call-only cut repairs the request; neither outcome proves cold compute. After a decision, recovery uses the recorded invocation and SnapshotRef. It may park at another gate (without RESUME), or finish and commit RESUME. A missing executor is FAILED_PRECONDITION and leaves the decision recoverable, and so does a transient refusal from the host's optional tool policy. Approved executor failures are durable EXECUTOR_ERROR receipts and definitive policy refusals durable POLICY_DENIED receipts, available to the harness for continuation, not transport failures. Snapshots and unresolved requests are retained indefinitely; there is no approval expiry or automatic decision. | | Fork | [ForkRequest](#agentsessions-v1-ForkRequest) | [ForkResponse](#agentsessions-v1-ForkResponse) | The differentiator: branch a session at a sequence into 1..128 children (ForkRequest.count). A STATELESS_REPLAY fork leaves the parent untouched. Forking a REQUIRES_MEMORY_SNAPSHOT harness, which only forks at the head, first checkpoints the parent once for the whole fan-out (it suspends, and a SUSPEND event lands on its chain) and clones every child from that 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). | diff --git a/docs/architecture.md b/docs/architecture.md index 46e8f384..56248b64 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -126,9 +126,10 @@ The `Placer` wires Sessions to the `Runtime` SPI and owns the incarnation lifecy - **Dial** — the harness is reached by dialing `Incarnation.Address` with `Incarnation.CallMetadata` on every call. One dial path, two address forms: a `unix://` socket for `runtime/local`; the `atenet-router` `host:port` for `runtime/substrate`, whose `ate-target-actor` metadata names the actor. - Before a stateful fork checkpoints its parent the Placer closes the parent's open harness streams, - because substrate waits for an actor's in-flight requests to drain before it snapshots; `Suspend` - instead refuses a session whose turn is still running. + Before a stateful fork checkpoints its parent the Placer refuses any running or durably incomplete + turn. A turn may have changed RAM before its next journal write, so cancelling and snapshotting it + could make recovery apply that mutation twice. `Suspend` applies the same memory-tier rule and + binds its memory snapshot to the exact validated journal head with a fence and append CAS. - **Lifecycle map** — session `Suspend → Runtime.Snapshot` checkpoints compute and `Resume → Runtime.Restore` restores it. Execution `END` does not automatically call `Runtime.Stop`. `DeleteSession` records permanent `PENDING` intent without releasing actors, pins or snapshots. @@ -220,7 +221,7 @@ stateDiagram-v2 - **One session guard per registry.** `Registry.Add` gives a registered harness's Placer the same session guard and per-session checkpoint state as the static ones, so overlapping `Exec`, `Suspend` and `Resume` on one session are `ABORTED` whichever of its Placers each call reaches, - a stateful `Fork` through any of them ends and refuses a turn through another, and a `Suspend` + a stateful `Fork` through any of them refuses a turn through another without ending it, and a `Suspend` and a stateful `Fork` of one session refuse each other (`ABORTED`). A `PlacerFactory` returns a new Placer for each call; `Add` refuses one that belongs to another registry or has an operation in progress. diff --git a/docs/faq.md b/docs/faq.md index 5621acdb..25523007 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -75,8 +75,11 @@ swap on append is what makes "single writer" enforceable rather than a hope. Across all Placers in one Registry, Exec, Suspend and Resume refuse conflicting operations for one session with gRPC `ABORTED`, without changing compute or the journal. Suspend will not interrupt a running turn. Delete also refuses overlap with those operations or a fork's fan-out and rollback. -Fork holds shared deletion admission instead of the exclusive turn guard: a stateful fork can -supersede a running turn, and its checkpoint mark remains held through the last child clone. +Fork holds shared deletion admission for its full operation. A stateful fork also takes the turn +guard briefly while it validates and installs its checkpoint mark, refusing a running turn rather +than cancelling it because RAM may contain an unjournaled mutation. The mark remains held through +the last child clone. A crash-left incomplete turn similarly refuses a memory Suspend or Fork with +`FAILED_PRECONDITION` until it is recovered or superseded. Retry refused calls after the holder finishes, using the current cursor for Exec. Other sessions remain independent. A standalone Placer has its own guard; separate Registries or hosts are not fenced by this local guard. diff --git a/docs/substrate-conformance.md b/docs/substrate-conformance.md index 44efef54..2e438929 100644 --- a/docs/substrate-conformance.md +++ b/docs/substrate-conformance.md @@ -1063,7 +1063,10 @@ How the session layer uses it: - **A fan-out shares one checkpoint.** `Fork(count: N)` snapshots the parent once and clones N children from that single snapshot, so the whole fleet branches from identical state. A turn on the parent would wake it and replace that snapshot, so the Placer refuses one with - `ErrCheckpointing` (ABORTED) until the last child is cloned. A second stateful fork or a + `ErrCheckpointing` (ABORTED) until the last child is cloned. Before that mark is installed, an + active turn is refused with `ErrSessionBusy` (ABORTED), and a journal tail without `END` is refused + with `CHECKPOINT_INCOMPLETE_TURN` (FAILED_PRECONDITION): the runtime may already contain an + unjournaled mutation that recovery would otherwise apply again. A second stateful fork or a `Suspend` of the parent in that time is refused the same way, before it fences or snapshots anything, so it can neither fail the first fork's SUSPEND record nor replace its snapshot; a fork that arrives while a `Suspend` runs is refused too. A fan-out that fails partway @@ -1125,8 +1128,10 @@ Constraints inherited from substrate, enforced or surfaced rather than papered o - The fork checkpoint is committed under a fence and a CAS on the seq the caller validated, so a turn racing the fork can never widen the children's prefix past the RAM they were cloned from. A fork that is *refused* takes the fence path not at all: a request that changes nothing must not - supersede a turn in flight on the parent. A stateful fork that proceeds does supersede it, - closing its harness stream before checkpointing; Suspend instead refuses overlap with a turn. + supersede a turn in flight on the parent. A stateful fork refuses an in-flight or durably + incomplete turn before checkpointing. It transiently holds ordinary operation admission through + checkpoint-mark installation, so pre-journal connection preparation is refused too; Fork closes + no local stream. Suspend likewise refuses overlap with a turn. Fork holds shared deletion admission through checkpoint, fan-out and rollback, so Delete is refused until it returns. Failed fan-out releases the checkpoint before rollback, allowing new parent turns while the failed children are stopped. Independent Registries or hosts are outside @@ -1134,18 +1139,10 @@ Constraints inherited from substrate, enforced or surfaced rather than papered o the writer that beat it even though it gives up. Closing that needs a read-only fence accessor on `eventlog.Store` (`NewFence` is currently the only way to obtain one, and it mutates), which is a wider API change than this path warrants. -- Ending the parent's harness streams sits between two fences. The first stops an in-flight turn - from writing an `ERROR` for the interruption; a turn that mints a newer fence in that window sees - that the checkpoint claimed its connection and writes nothing. Ending a stream only cancels the - turn, so the checkpoint then waits, bounded by the caller's context, until every ended turn has - made its fence call or returned. Only then is the second fence minted, the one the SUSPEND record - is written under, so no turn this Registry drives can fail the record after the parent is already - cold. - The connections and the checkpoint mark are per session and shared by every Placer of a +- The operation guard and checkpoint mark are per session and shared by every Placer of a `placement.Registry`, including one `Registry.Add` registers later, so a turn routed to a - different harness by `ExecRequest.harness` is covered. - If the context ends first, the fork aborts before it snapshots. A turn driven by another process - is outside this: only the log fences it. + different harness by `ExecRequest.harness` is covered. A turn driven by another process is outside + this local admission: only the log fences it, and its open stream can still delay runtime drain. Two properties make the failure paths above safe, both read off substrate's suspend/delete workflows (`cmd/ateapi/internal/controlapi/`) rather than assumed: @@ -1318,8 +1315,10 @@ taken on the envoy router (at `362637f9` and `fc0e3586`). harness on gVisor, at `362637f9`, `SuspendActor` under such a stream took **5m30s**: it waited for the router to reset the stream. `Placer.Suspend` therefore never checkpoints under a turn it knows of: while an `Exec` or `Resume` of the session runs, it is refused with `ErrSessionBusy` - (ABORTED), and once the turn has returned its stream is closed. A stateful `Fork`, which - supersedes the running turn instead, closes the parent's harness streams before it checkpoints. + (ABORTED), and once the turn has returned its stream is closed. A stateful `Fork` likewise refuses + a running or durably incomplete turn before it checkpoints instead of closing that stream. + A memory-tier Suspend fences and revalidates the exact head before `SuspendActor`, then appends at + that head, so a peer writer cannot be included after the checkpoint decision. `TestSuspendUnderAnIdleHarnessStream` checks the Suspend half on a live cluster. Both cover turns any Placer of this process's `placement.Registry` drives; a turn driven outside this Registry is fenced by the log, but its stream stays open until it next touches the log and can still stall a diff --git a/placement/approval_test.go b/placement/approval_test.go index e4e4fc28..b5fe3cba 100644 --- a/placement/approval_test.go +++ b/placement/approval_test.go @@ -415,7 +415,14 @@ func TestInheritedApprovalSuspendUsesSessionHarness(t *testing.T) { if err != nil { t.Fatal(err) } - if err := memory.Fork(t.Context(), parent, "parent", []placement.ForkChild{{UID: "child", Log: child}}, head); err != nil { + err = memory.Fork(t.Context(), parent, "parent", []placement.ForkChild{{UID: "child", Log: child}}, head) + if decided { + if !errors.Is(err, controller.ErrCheckpointIncompleteTurn) { + t.Fatalf("decided inherited fork=%v, want ErrCheckpointIncompleteTurn", err) + } + return + } + if err != nil { t.Fatal(err) } state, err := controller.InspectApproval(child, 0) diff --git a/placement/cleanup_resources_test.go b/placement/cleanup_resources_test.go index b98727a1..4c0cc6f9 100644 --- a/placement/cleanup_resources_test.go +++ b/placement/cleanup_resources_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/agent-primitives/sessions/api" + "github.com/agent-primitives/sessions/controller" "github.com/agent-primitives/sessions/eventlog" "github.com/agent-primitives/sessions/harness/echoagent" "github.com/agent-primitives/sessions/sqlitelog" @@ -46,6 +47,19 @@ type recordingLog struct { plan []api.CleanupResource } +type ownedMemoryBackend struct{ *ownedBackend } + +func (b *ownedMemoryBackend) Describe(ctx context.Context) (api.Descriptor, error) { + if b.refuse != nil { + return api.Descriptor{}, b.refuse + } + return api.Descriptor{ID: "memory", Capabilities: api.Capabilities{Resumability: api.ResumabilityRequiresMemorySnapshot}}, nil +} + +func (*ownedMemoryBackend) Capabilities() api.RuntimeCapabilities { + return api.RuntimeCapabilities{MemorySnapshot: true} +} + func (l *recordingLog) BeginPlannedAllocation(ctx context.Context, backend, operation string, plan ...api.CleanupResource) (string, error) { l.plan = plan return l.BeginAllocation(ctx, backend, operation) @@ -174,3 +188,40 @@ func TestForkRecordsUnpublishedPlanAndPartialEvidence(t *testing.T) { t.Fatalf("tag UID was not recorded: confirm with another UID err=%v", err) } } + +func TestIncompleteMemoryForkRecordsNoResourcePlan(t *testing.T) { + s, err := sqlitelog.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer s.Close() + parent := s.Session("parent") + zero := int64(0) + fence, err := parent.NewFence() + if err != nil { + t.Fatal(err) + } + if _, err := parent.Append(0, fence, api.Event{ExecutionID: "e", Kind: api.EventExecutionStart, + ExecutionStart: &api.ExecutionStart{InputCount: &zero}}); err != nil { + t.Fatal(err) + } + backend := &ownedBackend{ + allocationBackend: &allocationBackend{trace: new([]string)}, + key: "k", + plan: []api.CleanupResource{{Reference: "actor"}}, + } + p := New(&ownedMemoryBackend{ownedBackend: backend}, echoagent.Model) + child := s.ForkSession(sqlitelog.SessionMeta{UID: "child", ParentUID: "parent"}) + + err = p.Fork(t.Context(), parent, "parent", []ForkChild{{UID: "child", Log: child}}, 1) + if !errors.Is(err, controller.ErrCheckpointIncompleteTurn) || backend.forks != 0 { + t.Fatalf("Fork = %v forks=%d, want ErrCheckpointIncompleteTurn before runtime", err, backend.forks) + } + allocations, err := s.Allocations(t.Context(), "child") + if err != nil { + t.Fatal(err) + } + if len(allocations) != 0 { + t.Fatalf("refused Fork recorded allocations: %+v", allocations) + } +} diff --git a/placement/compute_guard.go b/placement/compute_guard.go index 01dcc290..acc6e3d1 100644 --- a/placement/compute_guard.go +++ b/placement/compute_guard.go @@ -148,9 +148,8 @@ func (g *computeGuard) settle(ctx context.Context, errp *error) { // the operation. A takeover by a caller's own stale cursor moves nothing and is not this. left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore) case errors.Is(err, ErrCheckpointing): - // Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may - // still be snapshotting the compute, or may fail before it suspends it, and only the - // Fork's SUSPEND record would show which. + // A checkpoint may still be snapshotting the compute, or may fail before it suspends it, and + // only its SUSPEND record would show which. left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it") case errors.Is(err, eventlog.ErrFenced): left.Cleanup = errors.New("release skipped: a newer writer fenced this operation") diff --git a/placement/compute_guard_test.go b/placement/compute_guard_test.go index 498cc982..bea9e698 100644 --- a/placement/compute_guard_test.go +++ b/placement/compute_guard_test.go @@ -437,22 +437,6 @@ func TestComputeGuard(t *testing.T) { e.expected = &head e.log.onConfirm = func() { e.peerAppend(suspendEvent) } }}, - // A checkpoint that superseded the turn may be snapshotting the compute or may fail before it - // does; here it never records a SUSPEND, as a stateful Fork whose Snapshot fails does not. - {name: "superseded by a checkpoint", ops: both, want: guardSkips, cause: errSuperseded, setup: func(e *guardEnv) { - e.log.onFence = func() { - if _, err := e.p.beginCheckpoint(e.uid); err != nil { - e.t.Fatal(err) - } - } - }}, - {name: "superseded by a checkpoint, live before allocation", ops: both, seed: "live", want: guardUnchanged, cause: errSuperseded, setup: func(e *guardEnv) { - e.log.onFence = func() { - if _, err := e.p.beginCheckpoint(e.uid); err != nil { - e.t.Fatal(err) - } - } - }}, {name: "caller cancelled", ops: both, want: guardReleases, cause: context.Canceled, setup: func(e *guardEnv) { e.log.onFence = e.cancel }}, diff --git a/placement/fork_verify_test.go b/placement/fork_verify_test.go index 95e11571..3931b5de 100644 --- a/placement/fork_verify_test.go +++ b/placement/fork_verify_test.go @@ -48,13 +48,7 @@ func TestForkRefusesATamperedParentBeforeEffects(t *testing.T) { var p *placement.Placer if tc.memory { p = memorySubstratePlacer(ctl) - fence, err := parent.NewFence() - if err != nil { - t.Fatal(err) - } - if _, err := parent.Append(0, fence, api.Event{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}); err != nil { - t.Fatal(err) - } + appendCompletedLegacyTurn(t, parent, "hi") } else { p = newLocalPlacer(t, echoagent.Harness{}) if _, err := p.Exec(context.Background(), parent, "parent", []api.Message{*api.TextMessage("user", "hi")}, 0); err != nil { diff --git a/placement/legacy_inventory_test.go b/placement/legacy_inventory_test.go index aecfe387..5b540129 100644 --- a/placement/legacy_inventory_test.go +++ b/placement/legacy_inventory_test.go @@ -25,14 +25,8 @@ func TestLegacyForkInventoryStaysIncomplete(t *testing.T) { } t.Cleanup(func() { s.Close() }) parent := s.Session("parent") - fence, err := parent.NewFence() - if err != nil { - t.Fatal(err) - } - if _, err := parent.Append(0, fence, api.Event{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}); err != nil { - t.Fatal(err) - } - meta := sqlitelog.SessionMeta{UID: "c1", ParentUID: "parent", ForkSeq: 1, ModelPolicyEligible: modern} + head := appendCompletedLegacyTurn(t, parent, "hi") + meta := sqlitelog.SessionMeta{UID: "c1", ParentUID: "parent", ForkSeq: head, ModelPolicyEligible: modern} child := s.Session("c1") if modern { child = s.ForkSession(meta) @@ -61,7 +55,7 @@ func TestLegacyForkInventoryStaysIncomplete(t *testing.T) { ctl.failCloneOf = "c2" } children := []placement.ForkChild{{UID: "c1", Log: first}, {UID: "c2", Log: inventoryFenceLog{Store: s.Session("c2")}}} - err = memorySubstratePlacer(ctl).Fork(t.Context(), parent, "parent", children, 1) + err = memorySubstratePlacer(ctl).Fork(t.Context(), parent, "parent", children, head) if outcome == "success" && err != nil { t.Fatal(err) } diff --git a/placement/memory_approval_test.go b/placement/memory_approval_test.go index 78d18d86..4aebdc78 100644 --- a/placement/memory_approval_test.go +++ b/placement/memory_approval_test.go @@ -150,8 +150,18 @@ func TestMemoryTierApprovalParkedForkAndInheritedGate(t *testing.T) { if len(ctl.calls) != calls { t.Fatal("refused fork touched compute") } - if err := p.Fork(t.Context(), parent, "parent", []placement.ForkChild{{UID: "child", Log: child}}, head); err != nil { - t.Fatalf("fork at head = %v", err) + err = p.Fork(t.Context(), parent, "parent", []placement.ForkChild{{UID: "child", Log: child}}, head) + if decided { + if !errors.Is(err, controller.ErrCheckpointIncompleteTurn) { + t.Fatalf("decided fork at head = %v, want ErrCheckpointIncompleteTurn", err) + } + if childHead, headErr := child.Head(); headErr != nil || childHead != 0 { + t.Fatalf("refused decided fork child head=%d err=%v", childHead, headErr) + } + return + } + if err != nil { + t.Fatalf("pending fork at head = %v", err) } state, err := controller.InspectApproval(child, 0) if err != nil || state == nil || !state.Inherited || state.Receipt != nil { diff --git a/placement/placement.go b/placement/placement.go index edfe7a48..ae5aec49 100644 --- a/placement/placement.go +++ b/placement/placement.go @@ -47,14 +47,15 @@ var ErrSessionBusy = errors.New("placement: another operation is in progress for // ErrDescriptorMismatch is returned when the harness reports a descriptor id other than the one the // Placer expects (WithDescriptorID): the address reaches a different harness than the one that was // configured. Like ErrUnplaceable it is raised by the admission check, before any compute is -// provisioned or anything is written to the log, and again on the turn's own connection for a -// LiveDescriber backend. session.Service surfaces it as codes.FailedPrecondition. +// provisioned or anything is written to the log, including a memory-capable Suspend, and again on +// the turn's own connection for a LiveDescriber backend. session.Service surfaces it as +// codes.FailedPrecondition. var ErrDescriptorMismatch = errors.New("placement: harness is not the expected one") // ErrHarnessUnavailable is returned when the harness could not be reached to describe itself during -// admission or the controller's connected-harness identity check, or to prepare its Connect stream -// before a new execution. None runs the harness or appends execution records; the connected checks -// may follow compute allocation and fence minting. +// admission (including memory-capable Suspend), the controller's connected-harness identity check, +// or Connect preparation before a new execution. None runs the harness or appends execution records; +// the connected checks may follow compute allocation and fence minting. // session.Service surfaces it as codes.Unavailable. If the caller's own deadline or cancellation // ended the check, it is ErrAdmissionInterrupted instead: the same expired call cannot succeed. var ErrHarnessUnavailable = errors.New("placement: harness unavailable") @@ -311,9 +312,9 @@ func WithDurableDedup(declared func(tool string) bool) Option { func WithLogger(logger *slog.Logger) Option { return func(p *Placer) { p.logger = logger } } // WithDescriptorID makes the Placer refuse a harness whose Describe reports a HarnessDescriptor.id -// other than id, with ErrDescriptorMismatch, wherever it applies the CanPlace gate: Exec, Resume and -// Fork, and the turn's own connection for a LiveDescriber backend. Empty, the default, means the id -// is not checked. +// other than id, with ErrDescriptorMismatch, wherever it applies the CanPlace gate: Exec, Resume, +// memory-capable Suspend and Fork, and the turn's own connection for a LiveDescriber backend. Empty, +// the default, means the id is not checked. // // The id is what the harness reports about itself, so the check catches an address that reaches the // wrong harness, not a harness that lies about what it is. It is not authentication. @@ -799,9 +800,8 @@ func tcpDial(address string, opts []grpc.DialOption) (api.Harness, func() error, return harnesswire.NewClientHarness(v1.NewHarnessClient(conn)), conn.Close, nil } -// ErrCheckpointing is returned when another operation holds the session's checkpoint mark, -// or a checkpoint ended the harness connection a turn was using. It is retryable once that -// operation returns; session.Service maps it to codes.Aborted. +// ErrCheckpointing is returned when another operation holds the session's checkpoint mark. It is +// retryable once that operation returns; session.Service maps it to codes.Aborted. var ErrCheckpointing = errors.New("placement: session is being checkpointed") // errSuperseded is the cancellation cause of a turn whose harness connection a checkpoint ended. The @@ -931,12 +931,10 @@ func (p *Placer) refuseDuringCheckpoint(sessionUID string) error { return nil } -// beginCheckpoint marks the session as being checkpointed, so openHarness refuses new connections -// for it, and returns the connections already open, each marked superseded. Taking the mark and the -// set under one lock is what leaves no window for a turn to slip a stream in between. The caller -// mints its fence after this returns, so a turn that mints a newer fence still sees the superseded -// mark (checkSuperseded) and writes nothing. A connection stays marked even if the checkpoint -// aborts. Every successful call must be paired with endCheckpoint. +// beginCheckpoint marks the session as being checkpointed, so openHarness refuses new connections. +// The caller holds ordinary operation admission through this call, so there can be no existing local +// connection; taking the mark under the same session-set lock closes the mark-to-registration race. +// Every successful call must be paired with endCheckpoint. // // Checkpoints do not nest: while another operation holds the mark, beginCheckpoint fails with // ErrCheckpointing and changes nothing. A second fork would otherwise mint a fence that fails the @@ -949,12 +947,11 @@ func (p *Placer) beginCheckpoint(sessionUID string) ([]*liveHarness, error) { if err := p.sessions.setCheckpointLocked(sessionUID); err != nil { return nil, err } - open := make([]*liveHarness, 0, len(p.sessions.live[sessionUID])) - for l := range p.sessions.live[sessionUID] { - l.superseded.Store(true) - open = append(open, l) + if len(p.sessions.live[sessionUID]) != 0 { + delete(p.sessions.checkpoints, sessionUID) + return nil, fmt.Errorf("%w: session %q has an open harness connection", ErrSessionBusy, sessionUID) } - return open, nil + return nil, nil } // markCheckpoint excludes a stateful Fork during a guarded Suspend, approval decision, @@ -988,30 +985,8 @@ func (s *sessionSet) endCheckpoint(sessionUID string) { delete(s.checkpoints, sessionUID) } -// endHarnesses ends the harness connections beginCheckpoint returned, and must run before a stateful -// fork checkpoints the session's compute. Substrate drains the actor's in-flight requests before it -// snapshots, and an open Connect stream idling on a model call counts as one: left open, it stalls -// the checkpoint until that drain times out. Ending the stream also stops a turn the checkpoint has -// just fenced from talking to a harness that will be frozen mid-call. -// -// Suspend does not call it: it refuses to run beside an Exec or Resume of the session -// (ErrSessionBusy), and they hold the session guard until their harness connection is closed. -// -// The caller mints its fence first, so the turn being ended can no longer write: it records no -// ERROR for an interruption the host caused, and it returns errSuperseded. A turn that minted a newer -// fence in between is stopped by the superseded mark beginCheckpoint set (checkSuperseded). -// -// Ending a stream only cancels the turn's context, and a turn that registered but has not yet -// minted its fence still mints one. So endHarnesses then waits, bounded by ctx, until every ended -// turn has made its fence call or returned. After it returns nil, no turn run by a Placer sharing -// this session set can mint a fence on the session, and the fence the caller mints next is the -// newest one the checkpoint will see. If ctx ends first, it returns an error and the caller must -// abort before checkpointing. -// -// It covers connections opened by every Placer sharing this Placer's session set: all Placers of -// one Registry, so a turn routed by ExecRequest.harness to another harness's Placer is ended too. -// A turn driven by another process is fenced by the log as before, but its stream stays open until -// that turn next touches the log or returns. +// endHarnesses is retained for a checkpoint caller that explicitly collected connections. Stateful +// Fork holds operation admission through beginCheckpoint, so its set is empty and this is a no-op. func (p *Placer) endHarnesses(ctx context.Context, sessionUID string, open []*liveHarness) (err error) { if len(open) == 0 { return nil @@ -1101,6 +1076,53 @@ func (p *Placer) suspend(ctx context.Context, log eventlog.Store, sessionUID str if err != nil { return api.SnapshotRef{}, fmt.Errorf("placement: read session journal: %w", err) } + // Stateless snapshots carry no process memory, so replaying an incomplete turn is safe. A + // memory-capable backend can host either tier, so read its descriptor before applying the + // memory-only checkpoint rule. Backends without memory snapshots keep Suspend's no-admission path. + memoryCheckpoint := false + if p.backend.Capabilities().MemorySnapshot { + desc, describeErr := p.admit(ctx, sessionUID) + if describeErr != nil { + return api.SnapshotRef{}, describeErr + } + memoryCheckpoint = desc.Capabilities.Resumability == api.ResumabilityRequiresMemorySnapshot + if memoryCheckpoint { + if checkpointErr := controller.ValidateCheckpointState(recs); checkpointErr != nil { + return api.SnapshotRef{}, checkpointErr + } + } + } + head := int64(0) + if len(recs) > 0 { + head = recs[len(recs)-1].Seq + } + fence := int64(0) + if cursor != nil { + head, fence = cursor.head, cursor.fence + } else if memoryCheckpoint { + // Bind the irreversible capture to the exact journal state validated above. A peer writer + // that moves the head after this fence makes the later SUSPEND CAS fail instead of widening + // the accepted checkpoint boundary over its incomplete turn. + fence, err = log.NewFence() + if err != nil { + return api.SnapshotRef{}, err + } + current, err := log.Read(1) + if err != nil { + return api.SnapshotRef{}, fmt.Errorf("placement: reread session journal: %w", err) + } + currentHead := int64(0) + if len(current) > 0 { + currentHead = current[len(current)-1].Seq + } + if currentHead != head { + return api.SnapshotRef{}, fmt.Errorf("%w: session advanced from seq %d to %d while Suspend was being prepared", eventlog.ErrConflict, head, currentHead) + } + if err := controller.ValidateCheckpointState(current); err != nil { + return api.SnapshotRef{}, err + } + recs = current + } // Pass the checkpoint the journal last recorded too, so the backend refuses compute holding a // snapshot the journal never recorded (one an earlier Snapshot refused) instead of capturing it. instance, _ := controller.LatestComputeInstance(recs, p.ranHere) @@ -1116,12 +1138,12 @@ func (p *Placer) suspend(ctx context.Context, log eventlog.Store, sessionUID str } _, appendFinished := observability.BeginDebug(ctx, p.logger, "placement", "append_suspend_event", "session_uid", sessionUID) lc := api.Lifecycle{Kind: api.LifecycleSuspend, Snapshot: &ref} - if cursor == nil { + if cursor == nil && !memoryCheckpoint { err = appendLifecycle(log, lc) } else { var record eventlog.Record - record, err = log.Append(cursor.head, cursor.fence, api.Event{Kind: api.EventLifecycle, Lifecycle: &lc}) - if err == nil && cursor.observer.OnRecord != nil { + record, err = log.Append(head, fence, api.Event{Kind: api.EventLifecycle, Lifecycle: &lc}) + if err == nil && cursor != nil && cursor.observer.OnRecord != nil { cursor.observer.OnRecord(record) } } @@ -1424,6 +1446,8 @@ func placementErrorKind(err error) string { return "harness_unavailable" case errors.Is(err, ErrCheckpointing): return "checkpointing" + case errors.Is(err, controller.ErrCheckpointIncompleteTurn): + return "checkpoint_incomplete_turn" case errors.Is(err, api.ErrMemoryStateLost): return "memory_state_lost" case errors.Is(err, eventlog.ErrTampered): @@ -1455,7 +1479,8 @@ func closeErrorKind(err error) string { // The compute half depends on the harness's resumability. A STATELESS_REPLAY harness replay-forks — // each child cold-boots and the copied journal reconstructs it, leaving the parent untouched. A // REQUIRES_MEMORY_SNAPSHOT harness holds live state the journal cannot reconstruct (I4), so the -// parent is checkpointed first and every child is cloned from that snapshot. +// parent is checkpointed first and every child is cloned from that snapshot. A live or durably +// incomplete parent turn is refused before any checkpoint side effect occurs. // // The whole fan-out shares ONE parent checkpoint: N children cost one snapshot and N clones, and all // of them branch from the identical state. The parent's checkpoint mark is held until the last child @@ -1629,6 +1654,26 @@ func (p *Placer) forkSource(ctx context.Context, parent eventlog.Store, parentUI if desc.Capabilities.Resumability != api.ResumabilityRequiresMemorySnapshot { return api.SnapshotRef{Local: parentUID}, func() {}, nil } + if err := p.refuseDuringCheckpoint(parentUID); err != nil { + return api.SnapshotRef{}, nil, err + } + // Exclude a local turn through the read-to-mark window. If another checkpoint already owns the + // session, retain ErrCheckpointing rather than reporting its operation hold as ordinary traffic. + operationRelease, err := p.trySessionLock(parentUID) + if err != nil { + if checkpointErr := p.refuseDuringCheckpoint(parentUID); checkpointErr != nil { + return api.SnapshotRef{}, nil, checkpointErr + } + return api.SnapshotRef{}, nil, err + } + defer func() { + if operationRelease != nil { + operationRelease() + } + }() + if err := p.refuseDuringCheckpoint(parentUID); err != nil { + return api.SnapshotRef{}, nil, err + } // Check the head BEFORE minting a fence. Minting is an autocommitted bump that supersedes any // in-flight writer, so doing it first would let a fork that is then REFUSED as unplaceable still // kill a turn racing on the parent — a request that changes nothing would leave the session worse @@ -1644,13 +1689,29 @@ func (p *Placer) forkSource(ctx context.Context, parent eventlog.Store, parentUI return api.SnapshotRef{}, nil, fmt.Errorf("%w: harness %q requires %s, which can only fork at the log head (%d), not seq %d", ErrUnplaceable, desc.ID, desc.Capabilities.Resumability, head, atSeq) } - // Past this point the fork is committing, so superseding the current writer is intended. - // Fencing before the snapshot stops an in-flight turn advancing the head underneath an - // irreversible checkpoint. The mark refuses new harness streams until every child is cloned. + // Refuse before the checkpoint mark, fence, or stream cancellation. A memory snapshot must not + // capture RAM changed by a turn whose END is absent: Resume could otherwise run that turn again + // and apply the mutation twice. + recs, err := parent.Read(1) + if err != nil { + return api.SnapshotRef{}, nil, fmt.Errorf("placement: read parent journal: %w", err) + } + if len(recs) > 0 && recs[len(recs)-1].Seq != atSeq { + return api.SnapshotRef{}, nil, fmt.Errorf("%w: parent advanced from seq %d to %d while the fork was being prepared", eventlog.ErrConflict, atSeq, recs[len(recs)-1].Seq) + } + if err := controller.ValidateCheckpointState(recs); err != nil { + return api.SnapshotRef{}, nil, err + } + // Atomically prevent a new stream from opening. The operation hold above excludes both running + // turns and pre-journal connection preparation, so no stream is cancelled by Fork. open, err := p.beginCheckpoint(parentUID) if err != nil { return api.SnapshotRef{}, nil, err } + // The mark now excludes new local turns and competing checkpoints. Release ordinary operation + // admission so calls during snapshot/fan-out keep the established ErrCheckpointing result. + operationRelease() + operationRelease = nil release := sync.OnceFunc(func() { p.sessions.endCheckpoint(parentUID) }) // Lift the mark on every path but the one that hands release to the caller, a panic included: // a recovered panic in the runtime's Snapshot must not leave the parent refused for good. @@ -1663,7 +1724,8 @@ func (p *Placer) forkSource(ctx context.Context, parent eventlog.Store, parentUI if _, err := parent.NewFence(); err != nil { return api.SnapshotRef{}, nil, err } - // A turn could still have committed in the window before that fence landed. Re-check now, while + // A writer on another host could still have committed in the window before that fence landed. + // Re-check now, while // aborting is free: after the snapshot the parent is cold whether or not the fork proceeds. if head, err = parent.Head(); err != nil { return api.SnapshotRef{}, nil, err @@ -1674,11 +1736,9 @@ func (p *Placer) forkSource(ctx context.Context, parent eventlog.Store, parentUI if err := p.endHarnesses(ctx, parentUID, open); err != nil { return api.SnapshotRef{}, nil, allocationStartError(ctx, err) } - // A turn ended above may have minted a newer fence after ours. It wrote nothing - // (checkSuperseded), but its fence would leave ours stale and fail the SUSPEND append after the - // parent is already cold. endHarnesses returned only once every such turn had minted, and no new - // turn can open, so mint the fence the record is written under now, and re-check the head while - // aborting is still free. + // Mint the fence the record is written under now, and re-check the head while aborting is still + // free. The local checkpoint mark excludes new streams; the second fence narrows the race with a + // writer on another host. fence, err := parent.NewFence() if err != nil { return api.SnapshotRef{}, nil, err @@ -1696,10 +1756,13 @@ func (p *Placer) forkSource(ctx context.Context, parent eventlog.Store, parentUI // FORK marker records in place of the parent's. Pass the instance the journal last recorded so // the backend refuses a replacement (api.ErrMemoryStateLost). The records read here are the // history the SUSPEND append below extends under its CAS on atSeq. - recs, err := parent.Read(1) + recs, err = parent.Read(1) if err != nil { return api.SnapshotRef{}, nil, fmt.Errorf("placement: read parent journal: %w", err) } + if err := controller.ValidateCheckpointState(recs); err != nil { + return api.SnapshotRef{}, nil, err + } // The parent's recorded checkpoint goes along, as in suspend, so a capture an earlier Snapshot // refused is not captured again and handed to the children. instance, _ := controller.LatestComputeInstance(recs, p.ranHere) diff --git a/placement/placement_test.go b/placement/placement_test.go index d0570c10..0c11a05a 100644 --- a/placement/placement_test.go +++ b/placement/placement_test.go @@ -540,6 +540,23 @@ func memorySubstratePlacer(ctl substrate.ControlClient) *placement.Placer { echoagent.Model) } +func appendCompletedLegacyTurn(t *testing.T, log eventlog.Store, text string) int64 { + t.Helper() + fence, err := log.NewFence() + if err != nil { + t.Fatal(err) + } + input, err := log.Append(0, fence, api.Event{Kind: api.EventInput, Message: api.TextMessage("user", text)}) + if err != nil { + t.Fatal(err) + } + end, err := log.Append(input.Seq, fence, api.Event{Kind: api.EventEnd, End: &api.HarnessEnd{State: "COMPLETED"}}) + if err != nil { + t.Fatal(err) + } + return end.Seq +} + // Forking a REQUIRES_MEMORY_SNAPSHOT session must checkpoint the parent first and clone the child // from that snapshot: the parent's live RAM is not in the journal, so a replay-fork would silently // hand back a divergent child. The parent must SURVIVE (snapshot, not Stop/delete), and the ref must @@ -552,14 +569,7 @@ func TestForkOfMemoryHarnessClonesParentSnapshot(t *testing.T) { defer store.Close() parent, child := store.Session("parent"), store.Session("child") - fence, err := parent.NewFence() - if err != nil { - t.Fatal(err) - } - if _, err := parent.Append(0, fence, api.Event{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}); err != nil { - t.Fatal(err) - } - head, _ := parent.Head() + head := appendCompletedLegacyTurn(t, parent, "hi") ctl := &cloningControl{snapshot: "snap-parent-1"} if err := memorySubstratePlacer(ctl).Fork(context.Background(), parent, "parent", []placement.ForkChild{{UID: "child", Log: child}}, head); err != nil { @@ -675,14 +685,7 @@ func TestForkOfMemoryHarnessWithoutExternalHandleRefusesCheckpoint(t *testing.T) defer store.Close() parent, child := store.Session("parent"), store.Session("child") - fence, err := parent.NewFence() - if err != nil { - t.Fatal(err) - } - if _, err := parent.Append(0, fence, api.Event{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}); err != nil { - t.Fatal(err) - } - head, _ := parent.Head() + head := appendCompletedLegacyTurn(t, parent, "hi") ctl := &cloningControl{} // every suspend reports no held snapshot err = memorySubstratePlacer(ctl).Fork(context.Background(), parent, "parent", []placement.ForkChild{{UID: "child", Log: child}}, head) @@ -720,18 +723,12 @@ func TestForkOfMemoryHarnessWithoutExternalHandleIsUnplaceable(t *testing.T) { } defer store.Close() parent, child := store.Session("parent"), store.Session("child") - fence, err := parent.NewFence() - if err != nil { - t.Fatal(err) - } - if _, err := parent.Append(0, fence, api.Event{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}); err != nil { - t.Fatal(err) - } + head := appendCompletedLegacyTurn(t, parent, "hi") ctl := &cloningControl{} backend := substrate.New(ctl, "space", substrate.ObjectRef{Name: "counter"}, api.Descriptor{ID: "mem", Capabilities: api.Capabilities{Resumability: api.ResumabilityRequiresMemorySnapshot}}) p := placement.New(checkpointWithoutURI{Backend: backend}, echoagent.Model) - err = p.Fork(context.Background(), parent, "parent", []placement.ForkChild{{UID: "child", Log: child}}, 1) + err = p.Fork(context.Background(), parent, "parent", []placement.ForkChild{{UID: "child", Log: child}}, head) if !errors.Is(err, placement.ErrUnplaceable) || errors.Is(err, substrate.ErrNoSnapshotToClone) { t.Fatalf("err=%v want ErrUnplaceable, not ErrNoSnapshotToClone", err) } @@ -790,14 +787,7 @@ func TestForkFanOutTakesOneParentCheckpoint(t *testing.T) { defer store.Close() parent := store.Session("parent") - fence, err := parent.NewFence() - if err != nil { - t.Fatal(err) - } - if _, err := parent.Append(0, fence, api.Event{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}); err != nil { - t.Fatal(err) - } - head, _ := parent.Head() + head := appendCompletedLegacyTurn(t, parent, "hi") children := []placement.ForkChild{ {UID: "c1", Log: store.Session("c1")}, @@ -864,6 +854,10 @@ func TestResumeIgnoresInheritedParentSnapshotRef(t *testing.T) { if err != nil { t.Fatal(err) } + rec, err = parent.Append(rec.Seq, fence, api.Event{Kind: api.EventEnd, End: &api.HarnessEnd{State: "COMPLETED"}}) + if err != nil { + t.Fatal(err) + } rec, err = parent.Append(rec.Seq, fence, api.Event{Kind: api.EventLifecycle, Lifecycle: &api.Lifecycle{ Kind: api.LifecycleSuspend, Snapshot: &api.SnapshotRef{Local: "parent", ExternalURI: "snap-parent-now", Memory: true}, @@ -876,6 +870,10 @@ func TestResumeIgnoresInheritedParentSnapshotRef(t *testing.T) { if err != nil { t.Fatal(err) } + rec, err = parent.Append(rec.Seq, fence, api.Event{Kind: api.EventEnd, End: &api.HarnessEnd{State: "COMPLETED"}}) + if err != nil { + t.Fatal(err) + } head := rec.Seq ctl := &cloningControl{snapshot: "snap-parent-now"} @@ -925,15 +923,7 @@ func TestForkAbortsWhenParentAdvancesUnderIt(t *testing.T) { defer store.Close() parent, child := store.Session("parent"), store.Session("child") - fence, err := parent.NewFence() - if err != nil { - t.Fatal(err) - } - rec, err := parent.Append(0, fence, api.Event{Kind: api.EventInput, Message: api.TextMessage("user", "one")}) - if err != nil { - t.Fatal(err) - } - head := rec.Seq + head := appendCompletedLegacyTurn(t, parent, "one") ctl := &cloningControl{snapshot: "snap-parent-1"} ctl.beforeSuspend = func() { @@ -970,14 +960,7 @@ func TestForkFanOutRollsBackProvisionedChildren(t *testing.T) { defer store.Close() parent := store.Session("parent") - fence, err := parent.NewFence() - if err != nil { - t.Fatal(err) - } - if _, err := parent.Append(0, fence, api.Event{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}); err != nil { - t.Fatal(err) - } - head, _ := parent.Head() + head := appendCompletedLegacyTurn(t, parent, "hi") children := []placement.ForkChild{ {UID: "c1", Log: store.Session("c1")}, @@ -1013,14 +996,7 @@ func TestForkRollbackSurvivesACancelledCaller(t *testing.T) { defer store.Close() parent := store.Session("parent") - fence, err := parent.NewFence() - if err != nil { - t.Fatal(err) - } - if _, err := parent.Append(0, fence, api.Event{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}); err != nil { - t.Fatal(err) - } - head, _ := parent.Head() + head := appendCompletedLegacyTurn(t, parent, "hi") ctx, cancel := context.WithCancel(context.Background()) ctl := &cloningControl{snapshot: "snap-parent-1", failCloneOf: "c2"} @@ -1056,14 +1032,7 @@ func TestForkRollbackBudgetsEachChildSeparately(t *testing.T) { defer store.Close() parent := store.Session("parent") - fence, err := parent.NewFence() - if err != nil { - t.Fatal(err) - } - if _, err := parent.Append(0, fence, api.Event{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}); err != nil { - t.Fatal(err) - } - head, _ := parent.Head() + head := appendCompletedLegacyTurn(t, parent, "hi") const cost = 100 * time.Millisecond children := []placement.ForkChild{ diff --git a/placement/registry.go b/placement/registry.go index 71d00884..89938478 100644 --- a/placement/registry.go +++ b/placement/registry.go @@ -82,7 +82,7 @@ func WithReservedNames(names ...string) RegistryOption { // per-session connections and checkpoint marks; Add does the same for a Placer added later. // session.Service routes a turn by ExecRequest.harness but a Suspend or Fork by the session's // recorded harness, so the two can land on different Placers; sharing them is what lets Suspend -// refuse a turn (ErrSessionBusy), and a stateful fork end and refuse one, whichever Placer runs it. +// refuse a turn and a stateful fork refuse a journaled incomplete turn, whichever Placer runs it. // Separate Registries do not fence each other. // // NewRegistry rejects a Placer that already belongs to a registry, and one with an operation in @@ -153,7 +153,7 @@ func NewRegistry(defaultHarness string, placers map[string]*Placer, opts ...Regi // On success p shares the Registry's session guard and its per-session connections and checkpoint // marks, exactly as the Placers given to NewRegistry do: an operation on a session through p and // one through any other Placer in this Registry refuse to overlap with ErrSessionBusy, and a -// stateful fork through either ends and refuses a turn through the other. Add refuses a p that +// stateful fork through either refuses a turn through the other without ending it. Add refuses a p that // belongs to another Registry or has an operation in progress, as NewRegistry does; the check // cannot see an operation that starts while Add runs, so p must not be in use until Add returns. // Adding a Placer already in this Registry under another name shares nothing new. A refused p is diff --git a/placement/registry_add_test.go b/placement/registry_add_test.go index a0a81697..e6a8fb1f 100644 --- a/placement/registry_add_test.go +++ b/placement/registry_add_test.go @@ -38,13 +38,13 @@ func TestSuspendRefusesAStreamOpenedByAnAddedPlacer(t *testing.T) { } // A Placer added to a running host shares the checkpoint state: a stateful fork through the -// static harness ends a parent turn running through the added one, and the reverse. -func TestForkEndsAParentStreamOpenedByAnAddedPlacer(t *testing.T) { - testCheckpointEndsOpenStream(t, forkCheckpoint, addedPair) +// static harness refuses a parent turn running through the added one, and the reverse. +func TestForkRefusesAParentStreamOpenedByAnAddedPlacer(t *testing.T) { + testForkRefusesOpenStream(t, addedPair) } -func TestForkThroughAnAddedPlacerEndsAStaticPlacersStream(t *testing.T) { - testCheckpointEndsOpenStream(t, forkCheckpoint, addedPairReversed) +func TestForkThroughAnAddedPlacerRefusesAStaticPlacersStream(t *testing.T) { + testForkRefusesOpenStream(t, addedPairReversed) } func TestForkRefusesAParentTurnOnAnAddedPlacer(t *testing.T) { diff --git a/placement/resume_cas_test.go b/placement/resume_cas_test.go index 77d74ec2..59b9b4f8 100644 --- a/placement/resume_cas_test.go +++ b/placement/resume_cas_test.go @@ -175,7 +175,7 @@ func (b *resumeRestoreProbe) Restore(ctx context.Context, ref api.SnapshotRef) ( return b.Backend.Restore(ctx, ref) } -func TestCheckedResumeRefusesForkCommittedDuringRestore(t *testing.T) { +func TestCheckedResumeRestoreRefusesAnIncompleteMemoryFork(t *testing.T) { store := newSuspendStore(t) log := store.Session("s") seedPlacementApproval(t, log, "mem", api.EventExecutionStart) @@ -205,32 +205,31 @@ func TestCheckedResumeRefusesForkCommittedDuringRestore(t *testing.T) { if err != nil { t.Fatal(err) } - var afterFork []eventlog.Record + beforeFork := suspendRecords(t, log) + var forkErr error b.beforeRestore = func() { - // Fork cannot see the turn until Restore returns and openHarness registers it. - if err := p.Fork(t.Context(), log, "s", []placement.ForkChild{{UID: "child", Log: store.Session("child")}}, expected); err != nil { - t.Fatal(err) - } - afterFork = suspendRecords(t, log) + // Restore has not opened a harness connection yet, but the durable incomplete turn is enough + // to refuse the memory checkpoint before a fence, snapshot or child write. + forkErr = p.Fork(t.Context(), log, "s", []placement.ForkChild{{UID: "child", Log: store.Session("child")}}, expected) } wrapped := &checkpointApprovalLog{Store: log} err = r.Resume(t.Context(), wrapped, "s", "mem", placement.WithResumeExpectedLastSeq(expected)) - values := fmt.Sprintf("expected_last_seq %d, head %d", expected, len(afterFork)) - if !errors.Is(err, eventlog.ErrConflict) || !strings.Contains(err.Error(), values) { - t.Fatalf("Resume=%v runs=%d tools=%d, want conflict with %q before effects", err, runs.Load(), effects.Load(), values) + if forkErr == nil || !errors.Is(forkErr, placement.ErrSessionBusy) { + t.Fatalf("Fork during Restore = %v, want ErrSessionBusy", forkErr) } - if wrapped.fences != 2 || b.restores != 1 || runs.Load() != 0 || effects.Load() != 0 || backend.snapshots != 1 { - t.Fatalf("fences=%d restores=%d runs=%d tools=%d snapshots=%d", wrapped.fences, b.restores, runs.Load(), effects.Load(), backend.snapshots) + if err != nil { + t.Fatalf("Resume = %v", err) } - if !reflect.DeepEqual(afterFork, suspendRecords(t, log)) { - t.Fatal("refused Resume changed the fork's committed prefix") + if wrapped.fences != 2 || b.restores != 1 || runs.Load() != 1 || effects.Load() != 1 || backend.snapshots != 0 { + t.Fatalf("fences=%d restores=%d runs=%d tools=%d snapshots=%d", wrapped.fences, b.restores, runs.Load(), effects.Load(), backend.snapshots) } - b.beforeRestore = nil - if err := r.Resume(t.Context(), log, "s", "mem", placement.WithResumeExpectedLastSeq(int64(len(afterFork)))); err != nil { - t.Fatalf("retry from the new cursor: %v", err) + after := suspendRecords(t, log) + if len(after) <= len(beforeFork) || after[len(after)-1].Event.Kind != api.EventLifecycle || after[len(after)-1].Event.Lifecycle.Kind != api.LifecycleResume { + t.Fatalf("successful Resume records=%v", after) } - if effects.Load() != 1 || runs.Load() != 1 { - t.Fatalf("retry duplicated effects: runs=%d tools=%d", runs.Load(), effects.Load()) + child, childErr := store.Session("child").Read(1) + if childErr != nil || len(child) != 0 { + t.Fatalf("refused Fork child records=%v err=%v", child, childErr) } if err := log.Verify(); err != nil { t.Fatal(err) diff --git a/placement/session_guard.go b/placement/session_guard.go index 5d00f481..070e1b4a 100644 --- a/placement/session_guard.go +++ b/placement/session_guard.go @@ -3,8 +3,9 @@ package placement import "sync" // sessionGuard preserves exclusive turn/lifecycle admission while separately fencing deletion. -// Fork and routing reads hold shared deletion admission without blocking an ordinary operation: -// a stateful fork may supersede a running turn, and rollback releases the parent for new turns. +// Fork and routing reads hold shared deletion admission without blocking an ordinary operation. A +// memory-tier Fork refuses a journaled incomplete turn before it checkpoints; rollback releases the +// parent for new turns. // Every admission and release shares mu; entries disappear only after the last hold is released. type sessionGuard struct { mu sync.Mutex diff --git a/placement/suspend_test.go b/placement/suspend_test.go index b53893dc..59912e0d 100644 --- a/placement/suspend_test.go +++ b/placement/suspend_test.go @@ -10,8 +10,10 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" "github.com/agent-primitives/sessions/api" + "github.com/agent-primitives/sessions/controller" "github.com/agent-primitives/sessions/eventlog" "github.com/agent-primitives/sessions/harness/echoagent" "github.com/agent-primitives/sessions/placement" @@ -869,9 +871,9 @@ func TestSuspendRefusesLostMemoryWithoutARecordedInstance(t *testing.T) { memory bool legacy bool }{ - {name: "memory, journal without compute_instance", memory: true, legacy: true}, + {name: "memory, completed journal without compute_instance", memory: true, legacy: true}, {name: "memory, no turn yet", memory: true}, - {name: "stateless, journal without compute_instance", legacy: true}, + {name: "stateless, completed journal without compute_instance", legacy: true}, } { t.Run(tc.name, func(t *testing.T) { ctl := newSuspendControl() @@ -887,7 +889,11 @@ func TestSuspendRefusesLostMemoryWithoutARecordedInstance(t *testing.T) { t.Fatal(err) } if _, err := log.Append(0, fence, api.Event{ExecutionID: "e1", Kind: api.EventExecutionStart, - ExecutionStart: &api.ExecutionStart{Harness: desc.ID, HarnessVersion: desc.Version}}); err != nil { + ExecutionStart: &api.ExecutionStart{Harness: desc.ID, HarnessVersion: desc.Version, InputCount: proto.Int64(0)}}); err != nil { + t.Fatal(err) + } + if _, err := log.Append(1, fence, api.Event{ExecutionID: "e1", Kind: api.EventEnd, + End: &api.HarnessEnd{State: "COMPLETED"}}); err != nil { t.Fatal(err) } } @@ -919,6 +925,146 @@ func TestSuspendRefusesLostMemoryWithoutARecordedInstance(t *testing.T) { } } +func TestMemorySuspendRefusesAnAbandonedIncompleteTurn(t *testing.T) { + ctl := newSuspendControl() + p, _ := newSuspendPlacer(t, ctl, true) + store := newSuspendStore(t) + log := store.Session("session") + ref := substrate.ActorRef{Atespace: "space", Name: "session"} + ctl.actors[ref] = &suspendActor{status: substrate.StatusRunning, worker: true, uid: ctl.newUID()} + fence, err := log.NewFence() + if err != nil { + t.Fatal(err) + } + start := api.Event{ExecutionID: "e1", Kind: api.EventExecutionStart, + ExecutionStart: &api.ExecutionStart{Harness: "mem", InputCount: proto.Int64(0)}} + if _, err := log.Append(0, fence, start); err != nil { + t.Fatal(err) + } + before := suspendRecords(t, log) + + got, err := p.Suspend(t.Context(), log, "session") + if !errors.Is(err, controller.ErrCheckpointIncompleteTurn) || got != (api.SnapshotRef{}) { + t.Fatalf("Suspend = %+v, %v, want ErrCheckpointIncompleteTurn", got, err) + } + if len(ctl.calls) != 0 || !reflect.DeepEqual(before, suspendRecords(t, log)) { + t.Fatalf("refused Suspend calls=%v records=%v", ctl.calls, suspendRecords(t, log)) + } + if actor := ctl.actors[ref]; actor.status != substrate.StatusRunning || !actor.worker || actor.snapshot.Name != "" { + t.Fatalf("refused Suspend changed actor: %+v", actor) + } +} + +type suspendRaceLog struct { + eventlog.Store + onSecondRead func() + reads int +} + +func (l *suspendRaceLog) Read(from int64) ([]eventlog.Record, error) { + l.reads++ + if l.reads == 2 && l.onSecondRead != nil { + l.onSecondRead() + } + return l.Store.Read(from) +} + +func TestMemorySuspendBindsSnapshotToValidatedHead(t *testing.T) { + ctl := newSuspendControl() + p, _ := newSuspendPlacer(t, ctl, true) + store := newSuspendStore(t) + log := store.Session("session") + ref := substrate.ActorRef{Atespace: "space", Name: "session"} + ctl.actors[ref] = &suspendActor{status: substrate.StatusRunning, worker: true, uid: ctl.newUID()} + peer := store.Session("session") + wrapped := &suspendRaceLog{Store: log} + wrapped.onSecondRead = func() { + fence, err := peer.NewFence() + if err != nil { + t.Fatal(err) + } + if _, err := peer.Append(0, fence, api.Event{ExecutionID: "peer", Kind: api.EventExecutionStart, + ExecutionStart: &api.ExecutionStart{InputCount: proto.Int64(0)}}); err != nil { + t.Fatal(err) + } + } + + got, err := p.Suspend(t.Context(), wrapped, "session") + if !errors.Is(err, eventlog.ErrConflict) || got != (api.SnapshotRef{}) { + t.Fatalf("Suspend = %+v, %v, want pre-snapshot conflict", got, err) + } + if len(ctl.calls) != 0 { + t.Fatalf("conflicted Suspend reached runtime: %v", ctl.calls) + } + records := suspendRecords(t, log) + if len(records) != 1 || records[0].Event.Kind != api.EventExecutionStart { + t.Fatalf("conflicted Suspend records=%v", records) + } +} + +func TestMemorySuspendDoesNotPublishCaptureAfterPeerTurnStarts(t *testing.T) { + ctl := newSuspendControl() + p, _ := newSuspendPlacer(t, ctl, true) + store := newSuspendStore(t) + log, peer := store.Session("session"), store.Session("session") + actorRef := substrate.ActorRef{Atespace: "space", Name: "session"} + actor := &suspendActor{status: substrate.StatusRunning, worker: true, uid: ctl.newUID()} + ctl.actors[actorRef] = actor + ctl.beforeSuspend = func() { + fence, err := peer.NewFence() + if err != nil { + t.Fatal(err) + } + if _, err := peer.Append(0, fence, api.Event{ExecutionID: "peer", Kind: api.EventExecutionStart, + ExecutionStart: &api.ExecutionStart{InputCount: proto.Int64(0)}}); err != nil { + t.Fatal(err) + } + actor.turns++ // The peer changed RAM after journaling its start but before the capture. + } + + got, err := p.Suspend(t.Context(), log, "session") + if (!errors.Is(err, eventlog.ErrConflict) && !errors.Is(err, eventlog.ErrFenced)) || got != (api.SnapshotRef{}) { + t.Fatalf("Suspend = %+v, %v, want the peer writer to invalidate publication", got, err) + } + records := suspendRecords(t, log) + if len(records) != 1 || records[0].Event.Kind != api.EventExecutionStart { + t.Fatalf("failed publication records=%v", records) + } + if actor.status != substrate.StatusSuspended || actor.snapshot.Name == "" || ctl.snapshots[actor.snapshot].turns != 1 { + t.Fatalf("premise failed: peer mutation was not captured: actor=%+v snapshots=%v", actor, ctl.snapshots) + } + if err := p.Resume(t.Context(), log, "session"); !errors.Is(err, api.ErrMemoryStateLost) { + t.Fatalf("Resume of unrecorded capture = %v, want ErrMemoryStateLost", err) + } +} + +type tamperedSuspendLog struct{ eventlog.Store } + +func (l tamperedSuspendLog) Read(from int64) ([]eventlog.Record, error) { + records, err := l.Store.Read(from) + if err == nil && len(records) > 0 { + records[0].Hash = "tampered" + } + return records, err +} + +func TestMemorySuspendRefusesTamperedJournalBeforeSnapshot(t *testing.T) { + ctl := newSuspendControl() + p, _ := newSuspendPlacer(t, ctl, true) + store := newSuspendStore(t) + log := store.Session("session") + appendCompletedLegacyTurn(t, log, "hi") + ref := substrate.ActorRef{Atespace: "space", Name: "session"} + ctl.actors[ref] = &suspendActor{status: substrate.StatusRunning, worker: true, uid: ctl.newUID()} + + if _, err := p.Suspend(t.Context(), tamperedSuspendLog{Store: log}, "session"); !errors.Is(err, controller.ErrJournalTampered) || !errors.Is(err, eventlog.ErrTampered) { + t.Fatalf("Suspend = %v, want ErrJournalTampered", err) + } + if len(ctl.calls) != 0 { + t.Fatalf("tampered Suspend reached runtime: %v", ctl.calls) + } +} + // A memory-tier Suspend refuses a capture it did not check (another caller suspended the actor and // resumed it on a worker that restored only its files, in between), and the actor is left holding // that capture. The refusal sticks: Exec, Resume, a new Suspend and a stateful Fork each compare diff --git a/placement/transport_test.go b/placement/transport_test.go index 857bef4b..6cc51181 100644 --- a/placement/transport_test.go +++ b/placement/transport_test.go @@ -16,6 +16,7 @@ import ( "github.com/agent-primitives/sessions/api" v1 "github.com/agent-primitives/sessions/api/genpb" "github.com/agent-primitives/sessions/client" + "github.com/agent-primitives/sessions/controller" "github.com/agent-primitives/sessions/eventlog" "github.com/agent-primitives/sessions/harness/echoagent" "github.com/agent-primitives/sessions/harnesswire" @@ -379,18 +380,27 @@ func testSuspendRefusesOpenStream(t *testing.T, pair placerPair) { case <-time.After(10 * time.Second): t.Fatal("the cancelled turn never returned") } - if _, err := p.Suspend(context.Background(), log, "s1"); err != nil { - t.Fatalf("Suspend after the turn returned: %v", err) + if _, err := p.Suspend(context.Background(), log, "s1"); !errors.Is(err, controller.ErrCheckpointIncompleteTurn) { + t.Fatalf("Suspend after the interrupted turn returned %v, want ErrCheckpointIncompleteTurn", err) } - if !<-streamEnded { - t.Fatal("the harness's Connect stream was still open when the runtime checkpointed") + backend.mu.Lock() + snapshots = backend.snapshots + backend.mu.Unlock() + if snapshots != 0 { + t.Fatalf("Suspend of the interrupted turn took %d snapshot(s)", snapshots) + } + select { + case <-streamEnded: + t.Fatal("refused Suspend reached the runtime checkpoint") + default: } } -// A stateful fork supersedes the parent's running turn instead, so it must end the parent's stream -// before it checkpoints. -func TestForkEndsTheParentsOpenHarnessStreamBeforeTheCheckpoint(t *testing.T) { - testCheckpointEndsOpenStream(t, forkCheckpoint) +// A stateful fork must leave the parent's running turn and stream alone. The turn may already have +// changed RAM before its next journal write, so cancelling it and snapshotting would let recovery +// apply that mutation twice. +func TestForkRefusesTheParentsOpenHarnessStreamBeforeTheCheckpoint(t *testing.T) { + testForkRefusesOpenStream(t) } type blockedPrepareHarness struct { @@ -406,7 +416,7 @@ func (h *blockedPrepareHarness) PrepareRun(ctx context.Context) (api.PreparedHar return nil, ctx.Err() } -func TestForkCancelsPreparedHarnessBeforeExecutionIsRecorded(t *testing.T) { +func TestForkRefusesPreparedHarnessBeforeExecutionIsRecorded(t *testing.T) { store, err := sqlitelog.Open(":memory:") if err != nil { t.Fatal(err) @@ -430,31 +440,27 @@ func TestForkCancelsPreparedHarnessBeforeExecutionIsRecorded(t *testing.T) { t.Fatal("turn never began Connect preparation") } - if err := forkCheckpoint(p, log, "s1"); err != nil { - t.Fatalf("checkpoint: %v", err) + if err := forkCheckpoint(p, log, "s1"); !errors.Is(err, placement.ErrSessionBusy) { + t.Fatalf("Fork = %v, want ErrSessionBusy", err) } select { case <-h.done: - case <-time.After(10 * time.Second): - t.Fatal("checkpoint did not cancel prepared Connect") + t.Fatal("refused Fork cancelled Connect preparation") + default: } select { case err := <-execErr: - if !errors.Is(err, placement.ErrCheckpointing) || !errors.Is(err, eventlog.ErrFenced) { - t.Fatalf("turn returned %v, want ErrCheckpointing and ErrFenced", err) - } - case <-time.After(10 * time.Second): - t.Fatal("superseded turn did not return") + t.Fatalf("refused Fork ended Connect preparation: %v", err) + default: } - kinds := journalKinds(t, log) - if len(kinds) != 1 || kinds[0] != api.EventLifecycle { - t.Fatalf("journal=%v, want only checkpoint lifecycle record", kinds) + if kinds := journalKinds(t, log); len(kinds) != 0 { + t.Fatalf("journal=%v, want no checkpoint record", kinds) } } -// The fork must end the turn's stream whichever Placer of the Registry runs the turn. -func TestForkEndsAParentStreamOpenedByAnotherPlacerOfTheRegistry(t *testing.T) { - testCheckpointEndsOpenStream(t, forkCheckpoint, registryPair) +// The refusal applies whichever Placer of the Registry runs the turn. +func TestForkRefusesAParentStreamOpenedByAnotherPlacerOfTheRegistry(t *testing.T) { + testForkRefusesOpenStream(t, registryPair) } // placerPair returns the Placer a checkpoint runs on and the one a turn runs on. @@ -477,7 +483,7 @@ func registryPair(t *testing.T, b placement.Backend, model func(context.Context, return def, other } -func testCheckpointEndsOpenStream(t *testing.T, checkpoint func(*placement.Placer, *sqlitelog.Log, string) error, pair ...placerPair) { +func testForkRefusesOpenStream(t *testing.T, pair ...placerPair) { t.Helper() hs := startHarnessServer(t, echoagent.Harness{}) store, err := sqlitelog.Open(":memory:") @@ -494,29 +500,18 @@ func testCheckpointEndsOpenStream(t *testing.T, checkpoint func(*placement.Place <-ctx.Done() return api.ModelResponse{}, ctx.Err() // what a real model client returns: not the cause } - streamEnded := make(chan bool, 1) - backend := &routedBackend{ - address: hs.addr, - desc: memDescriptor, - onSnapshot: func() { - // Give the server a bounded moment to observe the reset, as substrate's drain would. - select { - case <-hs.finished: - streamEnded <- true - case <-time.After(5 * time.Second): - streamEnded <- false - } - }, - } + backend := &routedBackend{address: hs.addr, desc: memDescriptor} mk := placerPair(samePlacer) if len(pair) > 0 { mk = pair[0] } p, turn := mk(t, backend, model) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() execErr := make(chan error, 1) go func() { - _, err := turn.Exec(context.Background(), log, "s1", []api.Message{*api.TextMessage("user", "hi")}, 0) + _, err := turn.Exec(ctx, log, "s1", []api.Message{*api.TextMessage("user", "hi")}, 0) execErr <- err }() select { @@ -528,29 +523,38 @@ func testCheckpointEndsOpenStream(t *testing.T, checkpoint func(*placement.Place } <-hs.started - if err := checkpoint(p, log, "s1"); err != nil { - t.Fatalf("checkpoint: %v", err) + before, err := log.Head() + if err != nil { + t.Fatal(err) } - if !<-streamEnded { - t.Fatal("the harness's Connect stream was still open when the runtime checkpointed") + if err := forkCheckpoint(p, log, "s1"); !errors.Is(err, placement.ErrSessionBusy) { + t.Fatalf("Fork = %v, want ErrSessionBusy", err) } select { case err := <-execErr: - // The checkpoint fenced the turn before ending its stream, so the turn reports that, not - // the incidental cancellation, and the service maps it to a retryable Aborted. - if !errors.Is(err, placement.ErrCheckpointing) || !errors.Is(err, eventlog.ErrFenced) { - t.Fatalf("interrupted turn returned %v, want ErrCheckpointing and eventlog.ErrFenced", err) - } - case <-time.After(10 * time.Second): - t.Fatal("the interrupted turn never returned") + t.Fatalf("refused Fork ended the running turn: %v", err) + default: + } + if n := len(hs.finished); n != 0 { + t.Fatalf("refused Fork closed %d harness stream(s)", n) + } + backend.mu.Lock() + snapshots := backend.snapshots + backend.mu.Unlock() + if snapshots != 0 { + t.Fatalf("refused Fork took %d snapshot(s)", snapshots) } - // The host interrupted the turn; the fence keeps that out of the journal as a harness ERROR. - kinds := journalKinds(t, log) - if slices.Contains(kinds, api.EventError) { - t.Fatalf("journal %v records the checkpoint's interruption as a harness ERROR", kinds) + if after, err := log.Head(); err != nil || after != before { + t.Fatalf("refused Fork moved the journal head from %d to %d (err %v)", before, after, err) } - if kinds[len(kinds)-1] != api.EventLifecycle { - t.Fatalf("journal %v does not end in the checkpoint's SUSPEND", kinds) + cancel() + select { + case err := <-execErr: + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled turn returned %v, want context.Canceled", err) + } + case <-time.After(10 * time.Second): + t.Fatal("the cancelled turn never returned") } } @@ -732,10 +736,10 @@ func TestNewRegistryRejectsAPlacerWithACheckpointInProgress(t *testing.T) { // when the fork's checkpoint begins. Registration must still be refused. (Suspend cannot begin while // a turn is past its early checks: the turn holds the session guard.) func TestForkRefusesAParentTurnRegisteringAsTheCheckpointBegins(t *testing.T) { - testCheckpointRefusesARegisteringTurn(t, forkCheckpoint) + testForkRefusesARegisteringTurn(t) } -func testCheckpointRefusesARegisteringTurn(t *testing.T, checkpoint func(*placement.Placer, *sqlitelog.Log, string) error) { +func testForkRefusesARegisteringTurn(t *testing.T) { t.Helper() hs := startHarnessServer(t, echoagent.Harness{}) store, err := sqlitelog.Open(":memory:") @@ -754,38 +758,34 @@ func testCheckpointRefusesARegisteringTurn(t *testing.T, checkpoint func(*placem execErr := make(chan error, 1) backend := &routedBackend{address: hs.addr, desc: memDescriptor} p := placement.New(backend, echoagent.Model, placement.WithDialer(dial)) - var gotErr error - backend.onSnapshot = func() { - // The checkpoint has begun; now let the held turn try to register, and wait for it. - close(release) - select { - case gotErr = <-execErr: - case <-time.After(10 * time.Second): - gotErr = errors.New("held turn did not return while the checkpoint ran") - } - } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() go func() { - _, err := p.Exec(context.Background(), log, "s1", []api.Message{*api.TextMessage("user", "hi")}, 0) + _, err := p.Exec(ctx, log, "s1", []api.Message{*api.TextMessage("user", "hi")}, 0) execErr <- err }() <-dialing - if err := checkpoint(p, log, "s1"); err != nil { - t.Fatalf("checkpoint: %v", err) + if err := forkCheckpoint(p, log, "s1"); !errors.Is(err, placement.ErrSessionBusy) { + t.Fatalf("Fork = %v, want ErrSessionBusy", err) } - if !errors.Is(gotErr, placement.ErrCheckpointing) { - t.Fatalf("turn registering as the checkpoint began returned %v, want ErrCheckpointing", gotErr) + select { + case err := <-execErr: + t.Fatalf("refused Fork ended the registering turn: %v", err) + default: } - if n := len(hs.started); n != 0 { - t.Fatalf("%d harness stream(s) opened while the session was being checkpointed", n) + close(release) + cancel() + select { + case <-execErr: + case <-time.After(10 * time.Second): + t.Fatal("cancelled registering turn did not return") } } -// Ending the streams cannot wait for the checkpoint to succeed: the checkpoint is what an open -// stream stalls. So a stateful fork that reaches its checkpoint supersedes the parent's in-flight -// turn even when the checkpoint then fails. The contract that makes that safe: nothing is recorded -// for the failed attempt, the parent stays live, and the caller can run the next turn or retry the -// fork at the new head. -func TestFailedForkCheckpointSupersedesTheParentTurnAndARetryRecovers(t *testing.T) { +// A stateful fork must refuse an in-flight turn before reaching a checkpoint that could capture +// unjournaled RAM. The turn remains usable; once it completes, a retry reaches the runtime and keeps +// the runtime's checkpoint failure as the result. +func TestForkRefusesTheParentTurnBeforeAFailedCheckpoint(t *testing.T) { hs := startHarnessServer(t, echoagent.Harness{}) store, err := sqlitelog.Open(":memory:") if err != nil { @@ -810,47 +810,53 @@ func TestFailedForkCheckpointSupersedesTheParentTurnAndARetryRecovers(t *testing <-ctx.Done() return api.ModelResponse{}, ctx.Err() // what a real model client returns: not the cause } - backend := &routedBackend{address: hs.addr, desc: memDescriptor, snapshotErr: errors.New("checkpoint failed")} + checkpointErr := errors.New("checkpoint failed") + backend := &routedBackend{address: hs.addr, desc: memDescriptor, snapshotErr: checkpointErr} p := placement.New(backend, model) + ctx, cancel := context.WithCancel(context.Background()) execErr := make(chan error, 1) go func() { - _, err := p.Exec(context.Background(), log, "s1", []api.Message{*api.TextMessage("user", "hi")}, 0) + _, err := p.Exec(ctx, log, "s1", []api.Message{*api.TextMessage("user", "hi")}, 0) execErr <- err }() <-modelCalled - if err := forkCheckpoint(p, log, "s1"); err == nil { - t.Fatal("Fork reported success for a failed checkpoint") + if err := forkCheckpoint(p, log, "s1"); !errors.Is(err, placement.ErrSessionBusy) { + t.Fatalf("Fork = %v, want ErrSessionBusy", err) + } + select { + case err := <-execErr: + t.Fatalf("refused Fork ended the in-flight turn: %v", err) + default: } + backend.mu.Lock() + snapshots := backend.snapshots + backend.mu.Unlock() + if snapshots != 0 { + t.Fatalf("refused Fork took %d snapshot(s)", snapshots) + } + cancel() select { case err := <-execErr: - if !errors.Is(err, placement.ErrCheckpointing) || !errors.Is(err, eventlog.ErrFenced) { - t.Fatalf("turn returned %v, want it superseded (ErrCheckpointing, ErrFenced)", err) + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled turn returned %v, want context.Canceled", err) } case <-time.After(10 * time.Second): - t.Fatal("the in-flight turn survived a failed fork checkpoint") - } - kinds := journalKinds(t, log) - if slices.Contains(kinds, api.EventError) || slices.Contains(kinds, api.EventLifecycle) || slices.Contains(kinds, api.EventEnd) { - t.Fatalf("failed fork left journal %v, want only the incomplete execution", kinds) + t.Fatal("the cancelled turn never returned") } - head, err := log.Head() if err != nil { t.Fatal(err) } if _, err := p.Exec(context.Background(), log, "s1", []api.Message{*api.TextMessage("user", "again")}, head); err != nil { - t.Fatalf("next turn after a failed fork: %v", err) + t.Fatalf("new turn after the interrupted one: %v", err) } - if kinds := journalKinds(t, log); kinds[len(kinds)-1] != api.EventEnd { - t.Fatalf("next turn after a failed fork did not complete: %v", kinds) + if err := forkCheckpoint(p, log, "s1"); !errors.Is(err, checkpointErr) { + t.Fatalf("Fork after the parent completed = %v, want %v", err, checkpointErr) } if err := forkCheckpoint(p, log, "s1"); err != nil { - t.Fatalf("retried fork: %v", err) - } - if kinds := journalKinds(t, log); kinds[len(kinds)-1] != api.EventLifecycle { - t.Fatalf("retried fork did not record the parent checkpoint's SUSPEND: %v", kinds) + t.Fatalf("Fork retry after the runtime failure: %v", err) } } @@ -869,347 +875,3 @@ func TestSuspendWithNoOpenStreamStillCheckpoints(t *testing.T) { t.Fatalf("snapshots=%d want 1", backend.snapshots) } } - -// gatedStore holds the turn's fence mint until the checkpoint has minted its own, then holds the -// checkpoint until the turn has either reached the model or returned. That forces the one ordering -// the checkpoint's own fence does not cover: a turn already registered when the checkpoint began -// mints a NEWER fence just before the checkpoint ends its stream. -type gatedStore struct { - eventlog.Store - - mu sync.Mutex - fences int - turnAtFence chan struct{} // closed when the turn asks for its fence - checkpointFence chan struct{} // closed once the checkpoint's fence is minted - turnMoved <-chan struct{} - turnDone <-chan struct{} -} - -func (g *gatedStore) NewFence() (int64, error) { - g.mu.Lock() - g.fences++ - n := g.fences - g.mu.Unlock() - switch n { - case 1: // the turn's - close(g.turnAtFence) - <-g.checkpointFence - return g.Store.NewFence() - case 2: // the checkpoint's, minted before it ends the turn's stream - f, err := g.Store.NewFence() - close(g.checkpointFence) - select { - case <-g.turnMoved: - case <-g.turnDone: - case <-time.After(10 * time.Second): - } - return f, err - default: - return g.Store.NewFence() - } -} - -// A turn that registered before a stateful fork's checkpoint began but mints its fence after the -// checkpoint's is not fenced by it. The checkpoint still ends that turn's stream, so the turn must not -// be allowed to write under its newer fence: it would journal the host's interruption as a harness -// ERROR. The fork must not abort because the turn advanced the parent's head under that fence either. -func TestForkSupersedesAParentTurnThatMintsANewerFence(t *testing.T) { - testCheckpointSupersedesNewerFence(t, func(p *placement.Placer, log eventlog.Store, uid string) error { - head, err := log.Head() - if err != nil { - return err - } - store, err := sqlitelog.Open(":memory:") - if err != nil { - return err - } - defer store.Close() - return p.Fork(context.Background(), log, uid, []placement.ForkChild{{UID: uid + "-child", Log: store.Session(uid + "-child")}}, head) - }) -} - -func testCheckpointSupersedesNewerFence(t *testing.T, checkpoint func(*placement.Placer, eventlog.Store, string) error) { - t.Helper() - hs := startHarnessServer(t, echoagent.Harness{}) - store, err := sqlitelog.Open(":memory:") - if err != nil { - t.Fatal(err) - } - defer store.Close() - - modelCalled, turnDone := make(chan struct{}), make(chan struct{}) - model := func(ctx context.Context, _ api.ModelRequest) (api.ModelResponse, error) { - close(modelCalled) - <-ctx.Done() - return api.ModelResponse{}, ctx.Err() - } - log := &gatedStore{ - Store: store.Session("s1"), - turnAtFence: make(chan struct{}), - checkpointFence: make(chan struct{}), - turnMoved: modelCalled, - turnDone: turnDone, - } - p := placement.New(&routedBackend{address: hs.addr, desc: memDescriptor}, model) - - var execErr error - go func() { - defer close(turnDone) - _, execErr = p.Exec(context.Background(), log, "s1", []api.Message{*api.TextMessage("user", "hi")}, 0) - }() - select { - case <-log.turnAtFence: // registered, so the checkpoint will see and end its stream - case <-turnDone: - t.Fatalf("turn returned before minting its fence: %v", execErr) - } - if err := checkpoint(p, log, "s1"); err != nil { - t.Fatalf("checkpoint: %v", err) - } - select { - case <-turnDone: - case <-time.After(10 * time.Second): - t.Fatal("the superseded turn never returned") - } - if !errors.Is(execErr, placement.ErrCheckpointing) || !errors.Is(execErr, eventlog.ErrFenced) { - t.Fatalf("superseded turn returned %v, want ErrCheckpointing and eventlog.ErrFenced", execErr) - } - kinds := journalKinds(t, log) - if slices.Contains(kinds, api.EventError) { - t.Fatalf("journal %v records the checkpoint's interruption as a harness ERROR", kinds) - } - if kinds[len(kinds)-1] != api.EventLifecycle { - t.Fatalf("journal %v does not end in the checkpoint's SUSPEND", kinds) - } -} - -// lateFenceStore holds the turn's fence mint (call 1) past the checkpoint's first fence (call 2). -// The turn is let go either when the checkpoint asks for its next fence, the one its record is -// written under, or after lateFenceDelay, whichever is first. When the next fence comes first, it is -// minted BEFORE the turn's, which is the ordering that stales the checkpoint's record. A checkpoint -// that waits for its ended turns to mint never asks for that fence while the turn is held, so only -// the delay can let the turn go and the record fence is minted last. -type lateFenceStore struct { - eventlog.Store - - mu sync.Mutex - fences int - turnAtFence chan struct{} // closed when the turn asks for its fence - release chan struct{} // closed to let the turn mint - releaseOnce sync.Once - turnMinted chan struct{} // closed once the turn's fence is minted -} - -const lateFenceDelay = 300 * time.Millisecond - -func (g *lateFenceStore) letTurnMint() { g.releaseOnce.Do(func() { close(g.release) }) } - -func (g *lateFenceStore) NewFence() (int64, error) { - g.mu.Lock() - g.fences++ - n := g.fences - g.mu.Unlock() - switch n { - case 1: // the turn's - close(g.turnAtFence) - <-g.release - defer close(g.turnMinted) - return g.Store.NewFence() - case 2: // the checkpoint's first, minted before it ends the turn's stream - time.AfterFunc(lateFenceDelay, g.letTurnMint) - return g.Store.NewFence() - default: // the fence the checkpoint's record is written under - f, err := g.Store.NewFence() - g.letTurnMint() - select { - case <-g.turnMinted: - case <-time.After(10 * time.Second): - } - return f, err - } -} - -// Ending a turn's stream only cancels its context. A turn that registered but had not yet minted its -// fence still mints one, and if that lands after the fence a stateful fork records the parent's -// checkpoint under, the record fails after the parent is already cold. The fork must wait for the -// turn to mint. -func TestForkWaitsForAnEndedParentTurnToMintBeforeRecording(t *testing.T) { - testCheckpointWaitsForLateFence(t, func(p *placement.Placer, log eventlog.Store, uid string) error { - head, err := log.Head() - if err != nil { - return err - } - store, err := sqlitelog.Open(":memory:") - if err != nil { - return err - } - defer store.Close() - return p.Fork(context.Background(), log, uid, []placement.ForkChild{{UID: uid + "-child", Log: store.Session(uid + "-child")}}, head) - }) -} - -func testCheckpointWaitsForLateFence(t *testing.T, checkpoint func(*placement.Placer, eventlog.Store, string) error) { - t.Helper() - hs := startHarnessServer(t, echoagent.Harness{}) - store, err := sqlitelog.Open(":memory:") - if err != nil { - t.Fatal(err) - } - defer store.Close() - - log := &lateFenceStore{ - Store: store.Session("s1"), - turnAtFence: make(chan struct{}), - release: make(chan struct{}), - turnMinted: make(chan struct{}), - } - backend := &routedBackend{address: hs.addr, desc: memDescriptor} - p := placement.New(backend, echoagent.Model) - - turnDone := make(chan struct{}) - var execErr error - go func() { - defer close(turnDone) - _, execErr = p.Exec(context.Background(), log, "s1", []api.Message{*api.TextMessage("user", "hi")}, 0) - }() - select { - case <-log.turnAtFence: - case <-turnDone: - t.Fatalf("turn returned before minting its fence: %v", execErr) - } - var turnMintedBeforeSnapshot bool - backend.onSnapshot = func() { - select { - case <-log.turnMinted: - turnMintedBeforeSnapshot = true - default: - } - } - if err := checkpoint(p, log, "s1"); err != nil { - t.Fatalf("checkpoint: %v", err) - } - <-turnDone - if !turnMintedBeforeSnapshot { - t.Fatal("the checkpoint snapshotted while the superseded turn could still mint a fence") - } - if !errors.Is(execErr, placement.ErrCheckpointing) || !errors.Is(execErr, eventlog.ErrFenced) { - t.Fatalf("superseded turn returned %v, want ErrCheckpointing and eventlog.ErrFenced", execErr) - } - kinds := journalKinds(t, log) - if len(kinds) != 1 || kinds[0] != api.EventLifecycle { - t.Fatalf("journal %v, want only the checkpoint's SUSPEND", kinds) - } -} - -// The wait is bounded by the caller's context. When it ends first the fork aborts before it -// snapshots the parent, and nothing is recorded, so the parent stays live. -func TestForkAbortsBeforeSnapshotWhenAnEndedParentTurnDoesNotMintInTime(t *testing.T) { - hs := startHarnessServer(t, echoagent.Harness{}) - store, err := sqlitelog.Open(":memory:") - if err != nil { - t.Fatal(err) - } - defer store.Close() - log := &lateFenceStore{ - Store: store.Session("s1"), - turnAtFence: make(chan struct{}), - release: make(chan struct{}), - turnMinted: make(chan struct{}), - } - backend := &routedBackend{address: hs.addr, desc: memDescriptor} - p := placement.New(backend, echoagent.Model) - - turnDone := make(chan struct{}) - var execErr error - go func() { - defer close(turnDone) - _, execErr = p.Exec(context.Background(), log, "s1", []api.Message{*api.TextMessage("user", "hi")}, 0) - }() - <-log.turnAtFence - ctx, cancel := context.WithTimeout(context.Background(), lateFenceDelay/6) - defer cancel() - child, err := sqlitelog.Open(":memory:") - if err != nil { - t.Fatal(err) - } - defer child.Close() - err = p.Fork(ctx, log, "s1", []placement.ForkChild{{UID: "s1-child", Log: child.Session("s1-child")}}, 0) - if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("Fork returned %v, want context.DeadlineExceeded", err) - } - <-turnDone - backend.mu.Lock() - snapshots := backend.snapshots - backend.mu.Unlock() - if snapshots != 0 { - t.Fatalf("Fork took %d snapshot(s) after giving up on the parent's turn", snapshots) - } - if kinds := journalKinds(t, log); len(kinds) != 0 { - t.Fatalf("journal %v, want nothing recorded for the aborted fork", kinds) - } - // The turn's Create returned compute that nothing recorded and the aborted fork did not take. - if !errors.Is(execErr, placement.ErrComputeLeftRunning) || !errors.Is(execErr, placement.ErrCheckpointing) { - t.Fatalf("superseded turn returned %v, want ErrComputeLeftRunning wrapping ErrCheckpointing", execErr) - } -} - -// A stateful fork that supersedes a turn and then fails before it suspends the parent leaves the -// compute the turn's Create returned running, with nothing in the journal that owns it: on -// runtime/substrate, Snapshot refuses an actor that is still transitioning after the turn's Create -// woke it. The turn's error must report that compute (RT-7) instead of assuming the fork took it, -// and nothing calls Stop. -func TestTurnSupersededByAForkWhoseSnapshotFailsReportsItsCompute(t *testing.T) { - hs := startHarnessServer(t, echoagent.Harness{}) - store, err := sqlitelog.Open(":memory:") - if err != nil { - t.Fatal(err) - } - defer store.Close() - log := &lateFenceStore{ - Store: store.Session("s1"), - turnAtFence: make(chan struct{}), - release: make(chan struct{}), - turnMinted: make(chan struct{}), - } - errSnapshot := errors.New("injected: actor is transitioning") - stops := 0 - backend := &routedBackend{address: hs.addr, desc: memDescriptor, snapshotErr: errSnapshot, onStop: func() { stops++ }} - p := placement.New(backend, echoagent.Model) - - turnDone := make(chan struct{}) - var execErr error - go func() { - defer close(turnDone) - _, execErr = p.Exec(context.Background(), log, "s1", []api.Message{*api.TextMessage("user", "hi")}, 0) - }() - select { - case <-log.turnAtFence: // compute allocated and the stream registered, nothing journaled - case <-turnDone: - t.Fatalf("turn returned before minting its fence: %v", execErr) - } - child, err := sqlitelog.Open(":memory:") - if err != nil { - t.Fatal(err) - } - defer child.Close() - err = p.Fork(context.Background(), log, "s1", []placement.ForkChild{{UID: "s1-child", Log: child.Session("s1-child")}}, 0) - if !errors.Is(err, errSnapshot) { - t.Fatalf("Fork returned %v, want the Snapshot failure", err) - } - <-turnDone - var left *placement.ComputeLeftRunningError - if !errors.As(execErr, &left) { - t.Fatalf("superseded turn returned %v, want a ComputeLeftRunningError", execErr) - } - if !errors.Is(execErr, placement.ErrCheckpointing) || !errors.Is(execErr, eventlog.ErrFenced) { - t.Fatalf("superseded turn returned %v, want its cause to stay ErrCheckpointing and eventlog.ErrFenced", execErr) - } - if left.Instance != "s1" { - t.Fatalf("Instance = %q, want the turn's incarnation", left.Instance) - } - if kinds := journalKinds(t, log); len(kinds) != 0 { - t.Fatalf("journal %v, want nothing recorded for the failed fork", kinds) - } - if stops != 0 { - t.Fatalf("Stop called %d times", stops) - } -} diff --git a/session/approval_override_test.go b/session/approval_override_test.go index b0dc26ea..dc757842 100644 --- a/session/approval_override_test.go +++ b/session/approval_override_test.go @@ -143,6 +143,14 @@ func checkMemoryOverrideRefusal(t *testing.T, operation string) { // Refusal leaves the pre-existing approval intent and its route untouched. return } + if operation == "Resume" { + // The interrupted override remains recoverable. A memory checkpoint must not capture A while + // that turn has no END, even though routing refused the recovery first. + if _, err := c.Suspend(t.Context(), &v1.SuspendRequest{Session: uid}); status.Code(err) != codes.FailedPrecondition { + t.Fatalf("Suspend of interrupted override = %v, want FailedPrecondition", err) + } + return + } // With no B approval written, Suspend must retain A's route and checkpoint its memory. suspended, err := c.Suspend(t.Context(), &v1.SuspendRequest{Session: uid}) if err != nil || suspended.GetComputeState() != v1.ComputeState_COMPUTE_COLD { diff --git a/session/checkpoint_test.go b/session/checkpoint_test.go index c6daf928..17bb1b68 100644 --- a/session/checkpoint_test.go +++ b/session/checkpoint_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -21,13 +22,15 @@ import ( ) // memoryBackend presents the local backend as memory-capable and its harness as -// REQUIRES_MEMORY_SNAPSHOT, so a Fork of a session checkpoints the parent: the one operation that -// supersedes a running turn. onSnapshot runs inside Snapshot, standing in for a runtime checkpoint -// in progress. forkErr, when set, fails every Fork. +// REQUIRES_MEMORY_SNAPSHOT, so a Fork of an idle session checkpoints the parent. onSnapshot runs +// inside Snapshot, standing in for a runtime checkpoint in progress. forkErr, when set, fails every +// Fork. type memoryBackend struct { *local.Backend - onSnapshot func() - forkErr error + onSnapshot func() + forkErr error + describeErr error + descriptor *api.Descriptor } func (b *memoryBackend) Fork(ctx context.Context, ref api.SnapshotRef, opts api.ForkOpts) (api.Incarnation, error) { @@ -38,11 +41,78 @@ func (b *memoryBackend) Fork(ctx context.Context, ref api.SnapshotRef, opts api. } func (b *memoryBackend) Describe(ctx context.Context) (api.Descriptor, error) { + if b.describeErr != nil { + return api.Descriptor{}, b.describeErr + } + if b.descriptor != nil { + return *b.descriptor, nil + } desc, err := b.Backend.Describe(ctx) desc.Capabilities.Resumability = api.ResumabilityRequiresMemorySnapshot return desc, err } +func TestMemorySuspendAdmissionErrors(t *testing.T) { + for _, tc := range []struct { + name string + cause error + desc *api.Descriptor + option placement.Option + code codes.Code + reason string + }{ + {name: "unavailable", cause: status.Error(codes.Unavailable, "offline"), code: codes.Unavailable, reason: "HARNESS_UNAVAILABLE"}, + {name: "descriptor mismatch", option: placement.WithDescriptorID("other"), code: codes.FailedPrecondition}, + {name: "invalid class", desc: &api.Descriptor{ID: "memory", HarnessClass: api.HarnessClassUnmediated, + Capabilities: api.Capabilities{Resumability: api.ResumabilityStatelessReplay}}, code: codes.FailedPrecondition}, + } { + t.Run(tc.name, func(t *testing.T) { + inner := local.New(echoagent.Harness{}) + t.Cleanup(func() { _ = inner.Close() }) + snapshots := 0 + backend := &memoryBackend{Backend: inner, describeErr: tc.cause, descriptor: tc.desc, onSnapshot: func() { snapshots++ }} + opts := []placement.Option{} + if tc.option != nil { + opts = append(opts, tc.option) + } + store, err := sqlitelog.Open(":memory:") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = store.Close() }) + if err := store.PutSession(sqlitelog.SessionMeta{UID: "s", Harness: "echo"}); err != nil { + t.Fatal(err) + } + r, err := placement.NewRegistry("echo", map[string]*placement.Placer{"echo": placement.New(backend, echoagent.Model, opts...)}) + if err != nil { + t.Fatal(err) + } + client := serveRegistry(t, store, r) + + _, err = client.Suspend(t.Context(), &v1.SuspendRequest{Session: "s"}) + if status.Code(err) != tc.code { + t.Fatalf("Suspend = %v, want %s", err, tc.code) + } + if tc.reason != "" { + details := status.Convert(err).Details() + if len(details) != 1 { + t.Fatalf("Suspend details=%v, want %s", details, tc.reason) + } + info, ok := details[0].(*errdetails.ErrorInfo) + if !ok || info.Domain != "agentsessions" || info.Reason != tc.reason { + t.Fatalf("Suspend details=%v, want agentsessions/%s", details, tc.reason) + } + } + if snapshots != 0 { + t.Fatalf("refused Suspend reached Snapshot %d time(s)", snapshots) + } + if head, headErr := store.Session("s").Head(); headErr != nil || head != 0 { + t.Fatalf("refused Suspend head=%d err=%v", head, headErr) + } + }) + } +} + func (b *memoryBackend) Capabilities() api.RuntimeCapabilities { return api.RuntimeCapabilities{MemorySnapshot: true} } @@ -87,7 +157,11 @@ func checkpointClient(t *testing.T, backend placement.Backend, model *parkingMod } func execHi(c v1.SessionsClient, sess string) error { - stream, err := c.Exec(context.Background(), &v1.ExecRequest{ + return execHiContext(context.Background(), c, sess) +} + +func execHiContext(ctx context.Context, c v1.SessionsClient, sess string) error { + stream, err := c.Exec(ctx, &v1.ExecRequest{ Session: sess, Inputs: []*v1.Message{wire.MessageToProto(api.TextMessage("user", "hi"))}, }) @@ -102,10 +176,10 @@ func forkParent(c v1.SessionsClient, sess string) error { return err } -// A turn that a stateful fork supersedes is a lost race with a newer writer, which callers retry. It -// must surface as Aborted, as a fenced turn always has, not as Internal because its stream was -// closed. -func TestExecSupersededByAStatefulForkIsAborted(t *testing.T) { +// A stateful fork must refuse an incomplete memory-tier turn without ending that turn. The journal +// cannot prove whether the harness changed RAM after its last record, so snapshotting it would let +// recovery apply the mutation twice. +func TestStatefulForkRefusesAnIncompleteTurn(t *testing.T) { inner := local.New(echoagent.Harness{}) t.Cleanup(func() { _ = inner.Close() }) model := &parkingModel{called: make(chan struct{})} @@ -113,22 +187,27 @@ func TestExecSupersededByAStatefulForkIsAborted(t *testing.T) { sess := mustCreate(t, c) execErr := make(chan error, 1) - go func() { execErr <- execHi(c, sess) }() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { execErr <- execHiContext(ctx, c, sess) }() select { case <-model.called: case <-time.After(10 * time.Second): t.Fatal("turn never reached the model call") } - if err := forkParent(c, sess); err != nil { - t.Fatalf("fork: %v", err) + if err := forkParent(c, sess); status.Code(err) != codes.Aborted { + t.Fatalf("fork: want Aborted, got %v", err) } select { case err := <-execErr: - if status.Code(err) != codes.Aborted { - t.Fatalf("superseded Exec: want Aborted, got %v", err) - } + t.Fatalf("refused Fork ended Exec: %v", err) + default: + } + cancel() + select { + case <-execErr: case <-time.After(10 * time.Second): - t.Fatal("superseded Exec never returned") + t.Fatal("cancelled Exec never returned") } } @@ -280,9 +359,9 @@ func (h *parkedDescribe) Describe(ctx context.Context) (api.Descriptor, error) { return api.Descriptor{}, ctx.Err() } -// A stateful fork that ends a turn while the turn is still checking the harness on its connection -// supersedes it like any other turn: Aborted, not the Canceled of a caller that gave up. -func TestExecSupersededDuringTheHarnessCheckIsAborted(t *testing.T) { +// A stateful fork is refused while the turn is still checking the harness on its connection. It +// must not cancel that Describe or turn. +func TestForkDuringTheHarnessCheckIsAbortedWithoutEndingExec(t *testing.T) { h := &parkedDescribe{parked: make(chan struct{})} inner := local.New(h) t.Cleanup(func() { _ = inner.Close() }) @@ -290,7 +369,9 @@ func TestExecSupersededDuringTheHarnessCheckIsAborted(t *testing.T) { sess := mustCreate(t, c) execErr := make(chan error, 1) - go func() { execErr <- execHi(c, sess) }() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { execErr <- execHiContext(ctx, c, sess) }() select { case <-h.parked: case err := <-execErr: @@ -298,16 +379,19 @@ func TestExecSupersededDuringTheHarnessCheckIsAborted(t *testing.T) { case <-time.After(10 * time.Second): t.Fatal("turn never checked the harness on its connection") } - if err := forkParent(c, sess); err != nil { - t.Fatalf("fork: %v", err) + if err := forkParent(c, sess); status.Code(err) != codes.Aborted { + t.Fatalf("fork: want Aborted, got %v", err) } select { case err := <-execErr: - if status.Code(err) != codes.Aborted { - t.Fatalf("Exec superseded during the harness check: want Aborted, got %v", err) - } + t.Fatalf("refused Fork ended Exec: %v", err) + default: + } + cancel() + select { + case <-execErr: case <-time.After(10 * time.Second): - t.Fatal("superseded Exec never returned") + t.Fatal("cancelled Exec never returned") } } @@ -329,9 +413,8 @@ func (h *controllerParkedDescribe) Describe(ctx context.Context) (api.Descriptor return api.Descriptor{}, ctx.Err() } -// A stateful fork that ends a turn while the controller is describing the connected harness -// supersedes it: Aborted, not the Canceled that a cut Describe reports when the caller gave up. -func TestExecSupersededDuringTheControllersHarnessDescribeIsAborted(t *testing.T) { +// The same refusal applies while the controller is describing the connected harness. +func TestForkDuringTheControllersHarnessDescribeIsAbortedWithoutEndingExec(t *testing.T) { h := &controllerParkedDescribe{parked: make(chan struct{})} inner := local.New(h) t.Cleanup(func() { _ = inner.Close() }) @@ -339,7 +422,9 @@ func TestExecSupersededDuringTheControllersHarnessDescribeIsAborted(t *testing.T sess := mustCreate(t, c) execErr := make(chan error, 1) - go func() { execErr <- execHi(c, sess) }() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { execErr <- execHiContext(ctx, c, sess) }() select { case <-h.parked: case err := <-execErr: @@ -347,15 +432,18 @@ func TestExecSupersededDuringTheControllersHarnessDescribeIsAborted(t *testing.T case <-time.After(10 * time.Second): t.Fatal("the controller never described the harness") } - if err := forkParent(c, sess); err != nil { - t.Fatalf("fork: %v", err) + if err := forkParent(c, sess); status.Code(err) != codes.Aborted { + t.Fatalf("fork: want Aborted, got %v", err) } select { case err := <-execErr: - if status.Code(err) != codes.Aborted { - t.Fatalf("Exec superseded during the controller's Describe: want Aborted, got %v", err) - } + t.Fatalf("refused Fork ended Exec: %v", err) + default: + } + cancel() + select { + case <-execErr: case <-time.After(10 * time.Second): - t.Fatal("superseded Exec never returned") + t.Fatal("cancelled Exec never returned") } } diff --git a/session/error_reasons_test.go b/session/error_reasons_test.go index 240cfe65..5241162f 100644 --- a/session/error_reasons_test.go +++ b/session/error_reasons_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/agent-primitives/sessions/api" + "github.com/agent-primitives/sessions/controller" "github.com/agent-primitives/sessions/eventlog" "github.com/agent-primitives/sessions/harness/echoagent" "github.com/agent-primitives/sessions/placement" @@ -186,6 +187,9 @@ func TestDeleteAndEarlyAdmissionReasons(t *testing.T) { assertErrorInfo(t, withStatusCause(tc.code, tc.cause), tc.code, tc.reason) } assertErrorInfo(t, forkError("uid", api.ErrSnapshotSuperseded), codes.Aborted, "SNAPSHOT_SUPERSEDED") + assertErrorInfo(t, forkError("uid", controller.ErrCheckpointIncompleteTurn), codes.FailedPrecondition, "CHECKPOINT_INCOMPLETE_TURN") + assertErrorInfo(t, suspendError("uid", controller.ErrCheckpointIncompleteTurn), codes.FailedPrecondition, "CHECKPOINT_INCOMPLETE_TURN") + assertErrorInfo(t, suspendError("uid", fmt.Errorf("%w: %w", controller.ErrJournalTampered, eventlog.ErrTampered)), codes.DataLoss, "") supersededAndBusy := errors.Join(api.ErrSnapshotSuperseded, api.ErrComputeBusy) assertErrorInfo(t, forkError("uid", supersededAndBusy), codes.Aborted, "SNAPSHOT_SUPERSEDED") for _, mapper := range []func(string, error) error{execError, resumeError, forkError} { diff --git a/session/errors.go b/session/errors.go index 2b93c5a7..239eae9c 100644 --- a/session/errors.go +++ b/session/errors.go @@ -4,6 +4,7 @@ import ( "errors" "github.com/agent-primitives/sessions/api" + "github.com/agent-primitives/sessions/controller" "github.com/agent-primitives/sessions/eventlog" "github.com/agent-primitives/sessions/placement" "google.golang.org/genproto/googleapis/rpc/errdetails" @@ -63,6 +64,7 @@ func errorReason(code codes.Code, err error) string { case codes.FailedPrecondition: reasons = []mapping{ {eventlog.ErrDeleted, "SESSION_DELETED"}, + {controller.ErrCheckpointIncompleteTurn, "CHECKPOINT_INCOMPLETE_TURN"}, {api.ErrMemoryStateLost, "MEMORY_STATE_LOST"}, {api.ErrInvalidCheckpoint, "CHECKPOINT_INVALID"}, {api.ErrComputeConfigInvalid, "COMPUTE_CONFIG_INVALID"}, diff --git a/session/fork_wake_test.go b/session/fork_wake_test.go index 6d334a5e..18aa2662 100644 --- a/session/fork_wake_test.go +++ b/session/fork_wake_test.go @@ -3,20 +3,9 @@ package session_test import ( "context" "fmt" - "strings" "sync" - "testing" - "time" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/agent-primitives/sessions/api" - v1 "github.com/agent-primitives/sessions/api/genpb" - "github.com/agent-primitives/sessions/harness/echoagent" - "github.com/agent-primitives/sessions/placement" "github.com/agent-primitives/sessions/runtime/substrate" - "github.com/agent-primitives/sessions/sqlitelog" ) // actorControl is an in-memory substrate control plane for the substrate runtime: actors with a @@ -193,120 +182,3 @@ func (c *actorControl) CreateActorFromTag(_ context.Context, a substrate.ActorRe } func (c *actorControl) DeleteTag(context.Context, substrate.SnapshotID) error { return nil } - -// A turn whose Runtime.Create or Runtime.Restore is already in flight when a stateful fork installs -// its checkpoint mark is past the Placer's checkpoint check, so nothing in this Registry stops it -// waking the parent between the fork's checkpoint and its tag. The substrate runtime then refuses to tag a snapshot the parent -// no longer holds. That is a lost race the caller retries at the parent's new head, so Fork must -// report it as Aborted, not Internal; and the turn, which finds the parent held by the fork, is -// Aborted as well. -func TestForkWhoseParentAnInFlightTurnWakesIsAborted(t *testing.T) { - for _, tc := range []struct { - name string - turn func(v1.SessionsClient, string) error - }{ - {"exec", execHi}, - {"resume", func(c v1.SessionsClient, sess string) error { - _, err := c.Resume(context.Background(), &v1.ResumeRequest{Session: sess}) - return err - }}, - } { - t.Run(tc.name, func(t *testing.T) { - ctl := &actorControl{status: map[string]substrate.ActorStatus{}, snapshots: map[string]string{}} - desc, err := echoagent.Harness{}.Describe(context.Background()) - if err != nil { - t.Fatal(err) - } - desc.Capabilities.Resumability = api.ResumabilityRequiresMemorySnapshot - backend := substrate.New(ctl, "space", substrate.ObjectRef{Atespace: "space", Name: "echo"}, desc) - dial := placement.WithDialer(func(api.Incarnation) (api.Harness, func() error, error) { - return echoagent.Harness{}, func() error { return nil }, nil - }) - store, err := sqlitelog.Open(":memory:") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = store.Close() }) - r, err := placement.NewRegistry("echo", map[string]*placement.Placer{"echo": placement.New(backend, echoagent.Model, dial)}) - if err != nil { - t.Fatal(err) - } - c := serveRegistry(t, store, r) - sess := mustCreate(t, c) - // One turn provisions the parent's actor; suspending it leaves the actor SUSPENDED, so - // the next turn's Create or Restore has to resume it. - if err := execHi(c, sess); err != nil { - t.Fatalf("first turn: %v", err) - } - if _, err := c.Suspend(context.Background(), &v1.SuspendRequest{Session: sess}); err != nil { - t.Fatalf("suspend: %v", err) - } - - // Force the interleaving: the turn's resume of the parent waits until the fork has - // checkpointed it, and the fork's check of the parent waits until the turn has returned. - var once sync.Once - waking, checkpointed, turnDone := make(chan struct{}), make(chan struct{}), make(chan struct{}) - hookErr := make(chan error, 2) - wait := func(ch <-chan struct{}, what string) { - select { - case <-ch: - case <-time.After(10 * time.Second): - hookErr <- fmt.Errorf("timed out waiting for %s", what) - } - } - ctl.onResume = func(actor string) { - if actor != sess { - return - } - once.Do(func() { - close(waking) - wait(checkpointed, "the fork's checkpoint") - }) - } - ctl.onSuspend = func(actor string) { - if actor == sess { - select { - case <-waking: - close(checkpointed) - default: - } - } - } - ctl.onGet = func(actor string) { - select { - case <-checkpointed: - if actor == sess { - wait(turnDone, "the turn to return") - } - default: - } - } - - turnErr := make(chan error, 1) - go func() { - err := tc.turn(c, sess) - close(turnDone) - turnErr <- err - }() - select { - case <-waking: - case err := <-turnErr: - t.Fatalf("turn returned before it resumed the parent: %v", err) - case <-time.After(10 * time.Second): - t.Fatal("turn never resumed the parent") - } - forkErr := forkParent(c, sess) - select { - case err := <-hookErr: - t.Fatal(err) - default: - } - if status.Code(forkErr) != codes.Aborted || !strings.Contains(status.Convert(forkErr).Message(), substrate.ErrSnapshotSuperseded.Error()) { - t.Fatalf("fork whose parent a turn woke before the tag: want Aborted for a superseded snapshot, got %v", forkErr) - } - if err := <-turnErr; status.Code(err) != codes.Aborted { - t.Fatalf("turn that woke the parent during the fork: want Aborted, got %v", err) - } - }) - } -} diff --git a/session/service.go b/session/service.go index c3a47837..0d22353e 100644 --- a/session/service.go +++ b/session/service.go @@ -1078,7 +1078,8 @@ func forkError(parent string, err error) error { case errors.Is(err, api.ErrInvalidCheckpoint): return checkpointRefusal("fork", parent, err) case errors.Is(err, placement.ErrUnplaceable), errors.Is(err, placement.ErrDescriptorMismatch), errors.Is(err, api.ErrInvalidHarnessClass), - errors.Is(err, api.ErrMemoryStateLost): + errors.Is(err, api.ErrMemoryStateLost), errors.Is(err, controller.ErrCheckpointIncompleteTurn), + errors.Is(err, controller.ErrInvalidExecutionLog), errors.Is(err, controller.ErrReplayDiverged): return statusError(codes.FailedPrecondition, err, err.Error()) case errors.Is(err, placement.ErrHarnessUnavailable): return statusError(codes.Unavailable, err, err.Error()) @@ -1212,14 +1213,20 @@ func suspendError(uid string, err error) error { switch { case errors.Is(err, eventlog.ErrDeleted): return withStatusCause(codes.FailedPrecondition, err) + case errors.Is(err, eventlog.ErrTampered): + return statusError(codes.DataLoss, err, err.Error()) case errors.Is(err, placement.ErrSessionBusy), errors.Is(err, placement.ErrCheckpointing), errors.Is(err, eventlog.ErrConflict), errors.Is(err, eventlog.ErrFenced), errors.Is(err, api.ErrComputeBusy): return statusError(codes.Aborted, err, err.Error()) case errors.Is(err, api.ErrInvalidCheckpoint): return checkpointRefusal("suspend", uid, err) + case errors.Is(err, placement.ErrUnplaceable), errors.Is(err, placement.ErrDescriptorMismatch), errors.Is(err, api.ErrInvalidHarnessClass): + return statusError(codes.FailedPrecondition, err, fmt.Sprintf("suspend: %v", err)) + case errors.Is(err, placement.ErrHarnessUnavailable): + return statusError(codes.Unavailable, err, fmt.Sprintf("suspend: %v", err)) // api.ErrMemoryStateLost: the compute the session's turns ran on is gone or replaced; retrying // cannot help. - case errors.Is(err, placement.ErrRecordedHarnessNotServed), errors.Is(err, placement.ErrHarnessUnservable), errors.Is(err, controller.ErrInvalidExecutionLog), errors.Is(err, controller.ErrReplayDiverged), + case errors.Is(err, placement.ErrRecordedHarnessNotServed), errors.Is(err, placement.ErrHarnessUnservable), errors.Is(err, controller.ErrInvalidExecutionLog), errors.Is(err, controller.ErrReplayDiverged), errors.Is(err, controller.ErrCheckpointIncompleteTurn), errors.Is(err, api.ErrMemoryStateLost): return statusError(codes.FailedPrecondition, err, fmt.Sprintf("suspend: %v", err)) case errors.Is(err, placement.ErrUnknownHarness): diff --git a/spec.md b/spec.md index 32a888ec..5eb2c41c 100644 --- a/spec.md +++ b/spec.md @@ -1314,11 +1314,19 @@ records only. only for a `Resume` with `expected_last_seq` set (`OPS-29`); otherwise it can append `APPROVAL_REQUEST` under a new fence during a checkpoint. TODO(spike): Should the call-only approval repair refuse with `ABORTED` during a checkpoint? -- `OPS-3`: A `REQUIRES_MEMORY_SNAPSHOT` fork MUST end any in-flight execution on the parent; that - execution fails with `ABORTED`. -- `CreateSession`, `GetSession`, `ListSessions`, and `Replay` take no guard. `Fork` (either tier) - does not take the `OPS-1` session guard, only the deletion exclusion (`OPS-30`). A - `REQUIRES_MEMORY_SNAPSHOT` fork holds the checkpoint mark instead (`OPS-2`). +- `OPS-3`: A `REQUIRES_MEMORY_SNAPSHOT` fork MUST refuse a locally active parent execution with + `ABORTED`, without ending its harness stream, fencing it, snapshotting or writing. A trailing + execution without `END` that is no longer locally active MUST be `FAILED_PRECONDITION` + (`CHECKPOINT_INCOMPLETE_TURN`) before those effects: its RAM may contain a mutation not represented + by the journal, and recovery could apply it again. The approval park in `APR-3` is an intentional + exception while it remains undecided, as are an inherited unresolved gate that recovery refuses + and a partial input prefix that never reached `Harness.Run`. A decided unreceipted gate is refused: + a prior recovery may have changed RAM before failing without a receipt. +- `CreateSession`, `GetSession`, `ListSessions`, and `Replay` take no guard. Every Fork takes only + the deletion exclusion (`OPS-30`) for its full operation. A `REQUIRES_MEMORY_SNAPSHOT` fork also + takes the `OPS-1` session guard transiently through validation and checkpoint-mark installation, + then releases it while retaining the checkpoint mark (`OPS-2`) through the fan-out. Thus an active + or pre-journal local turn is refused, while a later operation sees checkpoint-in-progress. ### 11.2 Create, Get, List @@ -1404,9 +1412,15 @@ records only. ### 11.5 Suspend -- `OPS-17`: `Suspend` MUST call the runtime's `Snapshot(EXTERNAL)`, then mint a fence and append - `LIFECYCLE_SUSPEND` carrying the returned `SnapshotRef` at the current head. It takes no - caller cursor. `compute_state` becomes `COMPUTE_COLD`. +- `OPS-17`: `Suspend` MUST call the runtime's `Snapshot(EXTERNAL)`, then append + `LIFECYCLE_SUSPEND` carrying the returned `SnapshotRef`. It takes no caller cursor. For a memory + checkpoint the host mints the fence before Snapshot, revalidates the journal, and appends with a + compare-and-swap on that exact head; a peer writer cannot widen the accepted checkpoint boundary + after RAM is captured. `compute_state` becomes `COMPUTE_COLD`. +- Before a `REQUIRES_MEMORY_SNAPSHOT` Suspend, the host applies the incomplete-turn check in + `OPS-3`. A refusal takes no snapshot and appends no lifecycle record. A `STATELESS_REPLAY` + Suspend remains allowed because its snapshot carries no process memory and recovery reconstructs + from the journal. - `OPS-18`: `Suspend` routes to the stored harness, except that an owned unreceipted approval routes to its recorded harness (`OPS-8`). - The reference host accepts `Suspend` on a session that is already cold or has never run, and @@ -1473,11 +1487,12 @@ records only. under a new child fence, and appends `LIFECYCLE_FORK`. The child's `compute_state` is `COMPUTE_COLD`. - `OPS-25`: `REQUIRES_MEMORY_SNAPSHOT` fork: `at_seq` other than the head MUST be - `FAILED_PRECONDITION` before any side effect. The host then takes the checkpoint mark, fences the - parent, ends its open streams, re-checks the head (moved is `ABORTED`), snapshots once, appends - `SUSPEND` to the parent with compare-and-swap at `at_seq`, and clones every child from that one - snapshot. A snapshot without an external handle is `FAILED_PRECONDITION`; the parent's `SUSPEND` - remains committed. + `FAILED_PRECONDITION` before any side effect. It applies `OPS-3`, installs the checkpoint mark + while still holding transient operation admission, fences the parent, re-checks the head (moved is + `ABORTED`), snapshots once, appends `SUSPEND` to the parent with compare-and-swap at `at_seq`, and + clones every child from that one snapshot. It never ends a local turn or pre-journal harness + preparation. A snapshot without an external handle is `FAILED_PRECONDITION`; the parent's + `SUSPEND` remains committed. - `OPS-26`: Children inherit `project`, `harness`, `model`, `annotations`, and `origin`. `labels` come from the request only (never merged). `name` is `child_names[i]` or empty. `identity` is unset. `parent_uid` and `fork_seq` record lineage. Children are returned in creation order. @@ -1543,7 +1558,7 @@ does not erase data or reclaim compute. | Missing required field, bad page token, unknown harness name, fork `count > 128`, `child_names` length mismatch, fork `identity` set | `INVALID_ARGUMENT` | | Unknown session (Get, Exec, Suspend, Resume, Fork, Approve, Delete) | `NOT_FOUND` | | Compare-and-swap conflict, stale fence, session busy (including an overlap with `DeleteSession`, `OPS-30`), checkpoint in progress, snapshot superseded, compute busy with another operation (`api.ErrComputeBusy`) | `ABORTED` | -| Unplaceable harness, descriptor mismatch, pin violation, memory-tier override (`OPS-7`), retired or unservable harness, static harness name with a registration row, approval state violation, inherited intent, undeclared trailing tool intent (`TOOL-10`), memory fork at a historical `seq`, deleted session (`OPS-34`), memory-tier compute gone or replaced (`api.ErrMemoryStateLost`, `RT-4e`, `RT-4h`), invalid, stale or local-only runtime checkpoint (`api.ErrInvalidCheckpoint`) | `FAILED_PRECONDITION` | +| Unplaceable harness, descriptor mismatch, pin violation, memory-tier override (`OPS-7`), retired or unservable harness, static harness name with a registration row, approval state violation, inherited intent, undeclared trailing tool intent (`TOOL-10`), memory fork at a historical `seq`, memory checkpoint with an incomplete turn (`OPS-3`), deleted session (`OPS-34`), memory-tier compute gone or replaced (`api.ErrMemoryStateLost`, `RT-4e`, `RT-4h`), invalid, stale or local-only runtime checkpoint (`api.ErrInvalidCheckpoint`) | `FAILED_PRECONDITION` | | A suspended actor's newest checkpoint still uploading to durable storage on `Exec`, `Suspend`, `Resume` or `Fork` (`api.ErrCheckpointPending`); once it completes, `Suspend` again to record it before `Resume` | `UNAVAILABLE` | | Harness `Describe` (admission `RT-1`, the `RT-3` recheck, or a `Describe` during the turn) could not reach the harness while the caller's context is live: the peer returned `UNAVAILABLE` or `DEADLINE_EXCEEDED`; or, on admission and the recheck, the host's own bound expired; or, during the turn, the error wraps `context.DeadlineExceeded` | `UNAVAILABLE` | | Any other `Describe` error on those paths, for example a peer `UNIMPLEMENTED` or `INTERNAL`, or a plain error from an in-process harness (during the turn, even one returned after the host's bound expired) | `INTERNAL` | @@ -1567,7 +1582,7 @@ or an unclassified error may supply none. | Code | Condition → reason (first matching condition within the code wins) | |---|---| | `ABORTED` | Append-CAS conflict → `STALE_CURSOR`; local session contention → `SESSION_BUSY`; fork snapshot superseded → `SNAPSHOT_SUPERSEDED`; compute contention → `COMPUTE_BUSY`; checkpoint in progress → `CHECKPOINT_IN_PROGRESS`; superseded writer fence → `FENCED` | -| `FAILED_PRECONDITION` | Deleted session → `SESSION_DELETED`; lost memory-tier state → `MEMORY_STATE_LOST`; refused checkpoint → `CHECKPOINT_INVALID`; known invalid compute configuration → `COMPUTE_CONFIG_INVALID` | +| `FAILED_PRECONDITION` | Deleted session → `SESSION_DELETED`; incomplete memory checkpoint boundary → `CHECKPOINT_INCOMPLETE_TURN`; lost memory-tier state → `MEMORY_STATE_LOST`; refused runtime checkpoint → `CHECKPOINT_INVALID`; known invalid compute configuration → `COMPUTE_CONFIG_INVALID` | | `UNAVAILABLE` | Checkpoint uploading → `CHECKPOINT_PENDING`; unreachable harness → `HARNESS_UNAVAILABLE`; compute unavailable → `COMPUTE_UNAVAILABLE` | | `RESOURCE_EXHAUSTED` | No eligible compute capacity → `COMPUTE_RESOURCE_EXHAUSTED` | @@ -1753,7 +1768,9 @@ sequenceDiagram - A refusal at the repeated check of a cursor-checked `Resume` leaves its early fence minted, so older writers are superseded (`LOG-12`) even though `Resume` refused. - `Fork` opens no execution connection and does not repeat admission. -- `Suspend` applies no admission check. +- On a backend that advertises `memory_snapshot`, `Suspend` runs admission to determine whether the + harness is `REQUIRES_MEMORY_SNAPSHOT` and must apply `OPS-3`; a refusal occurs before a fence, + snapshot or lifecycle append. A backend without memory snapshots retains no Suspend admission. ### 13.3 Runtime SPI @@ -1845,7 +1862,7 @@ The reference host takes it as `placement.Backend` in session, as `RT-5` reads it), or none. `Create` gets a reader for it in `SessionSpec.RecordedCheckpoint`, `Snapshot` gets it in `Incarnation.RecordedCheckpoint` (from `Suspend` and a stateful fork's capture of the parent), and `Restore` gets it as its ref. A - backend whose compute can hold a snapshot the journal never recorded MAY refuse, with + backend whose compute can hold a snapshot the journal never recorded MUST refuse, with `api.ErrMemoryStateLost` (`FAILED_PRECONDITION`) and before it resumes, attaches to or suspends anything, compute that holds another one; `runtime/substrate` does for a `REQUIRES_MEMORY_SNAPSHOT` harness (§13.4). A backend MAY also refuse that way, from `Create` or From fc848b1f38908c2a982e46962e66310d48eb8b77 Mon Sep 17 00:00:00 2001 From: Tatsat Mishra Date: Fri, 27 Nov 2026 21:52:50 +1300 Subject: [PATCH 2/5] test(placement): join refused prepared execution --- placement/transport_test.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/placement/transport_test.go b/placement/transport_test.go index 6cc51181..d8c931e9 100644 --- a/placement/transport_test.go +++ b/placement/transport_test.go @@ -429,9 +429,11 @@ func TestForkRefusesPreparedHarnessBeforeExecutionIsRecorded(t *testing.T) { return h, func() error { return nil }, nil })) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() execErr := make(chan error, 1) go func() { - _, err := p.Exec(context.Background(), log, "s1", []api.Message{*api.TextMessage("user", "hi")}, 0) + _, err := p.Exec(ctx, log, "s1", []api.Message{*api.TextMessage("user", "hi")}, 0) execErr <- err }() select { @@ -456,6 +458,20 @@ func TestForkRefusesPreparedHarnessBeforeExecutionIsRecorded(t *testing.T) { if kinds := journalKinds(t, log); len(kinds) != 0 { t.Fatalf("journal=%v, want no checkpoint record", kinds) } + cancel() + select { + case <-h.done: + case <-time.After(10 * time.Second): + t.Fatal("cancelled Connect preparation did not return") + } + select { + case err := <-execErr: + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled Exec returned %v, want context.Canceled", err) + } + case <-time.After(10 * time.Second): + t.Fatal("cancelled Exec did not return") + } } // The refusal applies whichever Placer of the Registry runs the turn. From 4b746b87b758e742c7577e4ed6ba0724d12def58 Mon Sep 17 00:00:00 2001 From: Tatsat Mishra Date: Sun, 29 Nov 2026 22:36:12 +1300 Subject: [PATCH 3/5] fix(placement): address checkpoint review feedback --- api/genpb/session_grpc.pb.go | 16 +- api/session.proto | 8 +- .../incomplete-memory-checkpoint-compat.md | 26 +++ docs/api-reference.md | 4 +- placement/cleanup.go | 10 +- placement/cleanup_context_test.go | 10 +- placement/placement.go | 148 +++--------------- session/error_reasons_test.go | 2 +- session/errors.go | 3 +- session/service.go | 4 +- spec.md | 21 ++- 11 files changed, 96 insertions(+), 156 deletions(-) create mode 100644 changelog/unreleased/incomplete-memory-checkpoint-compat.md diff --git a/api/genpb/session_grpc.pb.go b/api/genpb/session_grpc.pb.go index bd9625e6..e767bf07 100644 --- a/api/genpb/session_grpc.pb.go +++ b/api/genpb/session_grpc.pb.go @@ -174,6 +174,9 @@ type SessionsClient interface { // 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. Suspend(ctx context.Context, in *SuspendRequest, opts ...grpc.CallOption) (*Session, error) // A recorded override where either harness is REQUIRES_MEMORY_SNAPSHOT is // FAILED_PRECONDITION before compute changes or journal repair, as for Exec admission. @@ -194,7 +197,10 @@ type SessionsClient interface { // 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. Fork(ctx context.Context, in *ForkRequest, opts ...grpc.CallOption) (*ForkResponse, error) } @@ -480,6 +486,9 @@ type SessionsServer interface { // 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. Suspend(context.Context, *SuspendRequest) (*Session, error) // A recorded override where either harness is REQUIRES_MEMORY_SNAPSHOT is // FAILED_PRECONDITION before compute changes or journal repair, as for Exec admission. @@ -500,7 +509,10 @@ type SessionsServer interface { // 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. Fork(context.Context, *ForkRequest) (*ForkResponse, error) mustEmbedUnimplementedSessionsServer() } diff --git a/api/session.proto b/api/session.proto index f108fd5c..be527dc2 100644 --- a/api/session.proto +++ b/api/session.proto @@ -475,6 +475,9 @@ service Sessions { // 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. @@ -496,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); } diff --git a/changelog/unreleased/incomplete-memory-checkpoint-compat.md b/changelog/unreleased/incomplete-memory-checkpoint-compat.md new file mode 100644 index 00000000..7e13065e --- /dev/null +++ b/changelog/unreleased/incomplete-memory-checkpoint-compat.md @@ -0,0 +1,26 @@ +--- +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. 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. diff --git a/docs/api-reference.md b/docs/api-reference.md index 6f8d3fd4..cb7d2c8f 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -1854,9 +1854,9 @@ provide required-mode deployment or transport assembly. | Approve | [ApproveRequest](#agentsessions-v1-ApproveRequest) | [ApproveResponse](#agentsessions-v1-ApproveResponse) | Implemented durable approval decisions for STATELESS_REPLAY and REQUIRES_MEMORY_SNAPSHOT executions. OK commits only a decision; the caller must Resume to continue. An exact retry of the tuple, approved value, reason, identity and verified approver returns the existing decision, even after resolution. A changed decision/reason/identity, or a different verified approver, for that request is FAILED_PRECONDITION, never an overwrite. INVALID_ARGUMENT: missing session/execution/tool-call tuple, non-positive request_seq, or absent approved. NOT_FOUND: unknown session. FAILED_PRECONDITION: stale, inherited, or wrong request tuple, changed decision, or invalid recorded approval evidence. The gate cannot be created for an in-process harness that declares any other tier; a wire harness that omits its tier or sends an unknown one is read as STATELESS_REPLAY and gets the gate (spec APR-1, WIRE-3). Approve does not Describe or resolve a harness. ABORTED: local contention (including a live Resume or a stateful Fork), append-CAS conflict or superseded fence; retry after reading the session. Identity is unverified provenance, ignored by an enforcing Go host. Independent read+approve permission checks are opt-in. This method does not run a host's pre-dispatch tool policy hook (it runs when recovery dispatches the approved call) and implies no expiry, implicit Resume, or Cancel behavior. | | CloseApproval | [CloseApprovalRequest](#agentsessions-v1-CloseApprovalRequest) | [CloseApprovalResponse](#agentsessions-v1-CloseApprovalResponse) | Closes an approval gate the harness cannot re-issue, writing only journal records: no harness, executor or compute runs. OK returns the gate's decision and receipt; after it Exec admits a new turn. A retry, or a close of a gate that already has a receipt from any writer, returns the existing records without writing. The closed execution gets no END: Resume re-drives it and serves the receipt to a harness that re-issues the call. A REQUIRES_MEMORY_SNAPSHOT harness restored at the gate cannot continue there unless the gate is the execution's first effect (spec APR-19); Exec is that session's route. Closing an approved gate revokes the approval for later recovery but cannot stop an executor call another host already dispatched, so its receipt is OUTCOME_UNKNOWN. INVALID_ARGUMENT: missing session/execution/tool-call tuple or non-positive request_seq. NOT_FOUND: unknown session. FAILED_PRECONDITION: deleted session; wrong, inherited or superseded request tuple, or one whose request was never journaled; or invalid recorded approval evidence. DATA_LOSS: the journal fails hash-chain verification. ABORTED: local contention (including a live Resume or a stateful Fork), append-CAS conflict or superseded fence; retry after reading the session. Independent read+approval.close permission checks are opt-in. | | Cancel | [CancelRequest](#agentsessions-v1-CancelRequest) | [Session](#agentsessions-v1-Session) | In-flight control: cancel the running execution. Not implemented: the server returns UNIMPLEMENTED. | -| Suspend | [SuspendRequest](#agentsessions-v1-SuspendRequest) | [Session](#agentsessions-v1-Session) | Compute-layer durability. There is no warm Pause: no Runtime backend implements a 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. 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. cold, free worker | +| Suspend | [SuspendRequest](#agentsessions-v1-SuspendRequest) | [Session](#agentsessions-v1-Session) | Compute-layer durability. There is no warm Pause: no Runtime backend implements a 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. 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. cold, free worker | | Resume | [ResumeRequest](#agentsessions-v1-ResumeRequest) | [Session](#agentsessions-v1-Session) | A recorded override where either harness is REQUIRES_MEMORY_SNAPSHOT is FAILED_PRECONDITION before compute changes or journal repair, as for Exec admission. Otherwise an unresolved owned approval returns its current paused Session without runtime IO. A call-only cut repairs the request; neither outcome proves cold compute. After a decision, recovery uses the recorded invocation and SnapshotRef. It may park at another gate (without RESUME), or finish and commit RESUME. A missing executor is FAILED_PRECONDITION and leaves the decision recoverable, and so does a transient refusal from the host's optional tool policy. Approved executor failures are durable EXECUTOR_ERROR receipts and definitive policy refusals durable POLICY_DENIED receipts, available to the harness for continuation, not transport failures. Snapshots and unresolved requests are retained indefinitely; there is no approval expiry or automatic decision. | -| Fork | [ForkRequest](#agentsessions-v1-ForkRequest) | [ForkResponse](#agentsessions-v1-ForkResponse) | The differentiator: branch a session at a sequence into 1..128 children (ForkRequest.count). A STATELESS_REPLAY fork leaves the parent untouched. Forking a REQUIRES_MEMORY_SNAPSHOT harness, which only forks at the head, first checkpoints the parent once for the whole fan-out (it suspends, and a SUSPEND event lands on its chain) and clones every child from that 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). | +| Fork | [ForkRequest](#agentsessions-v1-ForkRequest) | [ForkResponse](#agentsessions-v1-ForkResponse) | The differentiator: branch a session at a sequence into 1..128 children (ForkRequest.count). A STATELESS_REPLAY fork leaves the parent untouched. Forking a REQUIRES_MEMORY_SNAPSHOT harness, which only forks at the head, first checkpoints the parent once for the whole fan-out (it suspends, and a SUSPEND event lands on its chain) and clones every child from that 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). 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. | diff --git a/placement/cleanup.go b/placement/cleanup.go index e8037080..25896c71 100644 --- a/placement/cleanup.go +++ b/placement/cleanup.go @@ -124,16 +124,12 @@ func callerContextError(ctx context.Context, err error) error { return err } -// Only the caller's context during start is an admission interruption. Confirmation -// uses an independent deadline, and checkpoint supersession remains ABORTED. A runtime -// that tears down before returning marks a failure the caller was still live for, so a -// context that ended during that teardown does not replace the primary failure. +// Only the caller's context during start is an admission interruption. Confirmation uses an +// independent deadline. A runtime that tears down before returning marks a failure the caller was +// still live for, so a context that ended during that teardown does not replace the primary failure. func allocationStartError(ctx context.Context, err error) error { if callerctx.LiveAtFailure(err) { return err } - if err != nil && errors.Is(context.Cause(ctx), errSuperseded) { - return fmt.Errorf("%w (compute start ended with: %v)", errSuperseded, err) - } return callerContextError(ctx, err) } diff --git a/placement/cleanup_context_test.go b/placement/cleanup_context_test.go index 3b4e44e4..8de7a32f 100644 --- a/placement/cleanup_context_test.go +++ b/placement/cleanup_context_test.go @@ -23,7 +23,7 @@ func (l *contextAllocationLog) ConfirmAllocation(context.Context, string, api.In } // Treating every wrapped deadline as caller cancellation would hide independent confirmation -// failures; treating checkpoint cancellation as caller cancellation would lose the retry path. +// failures. func TestAllocationContextFailureBoundaries(t *testing.T) { p := &Placer{} for _, tc := range []struct { @@ -33,14 +33,12 @@ func TestAllocationContextFailureBoundaries(t *testing.T) { effectErr error confirmErr error interrupted bool - superseded bool }{ {name: "caller during start", cancelCause: context.Canceled, effectErr: context.Canceled, interrupted: true}, {name: "tracked caller during start", tracked: true, cancelCause: context.Canceled, effectErr: context.Canceled, interrupted: true}, {name: "peer deadline", effectErr: context.DeadlineExceeded}, {name: "independent confirmation deadline", tracked: true, confirmErr: context.DeadlineExceeded}, {name: "caller ended but confirmation failed", tracked: true, cancelCause: context.Canceled, confirmErr: context.DeadlineExceeded}, - {name: "checkpoint superseded start", cancelCause: errSuperseded, effectErr: context.Canceled, superseded: true}, // The runtime's own teardown outlasted the caller after a failure the caller was live for. {name: "caller ended during runtime teardown", cancelCause: context.Canceled, effectErr: callerctx.MarkLive(api.ErrComputeUnavailable)}, } { @@ -57,10 +55,10 @@ func TestAllocationContextFailureBoundaries(t *testing.T) { } return api.Incarnation{ID: "instance"}, tc.effectErr }) - if errors.Is(err, ErrAdmissionInterrupted) != tc.interrupted || errors.Is(err, ErrCheckpointing) != tc.superseded { - t.Fatalf("allocation=%v: interrupted=%v superseded=%v", err, tc.interrupted, tc.superseded) + if errors.Is(err, ErrAdmissionInterrupted) != tc.interrupted { + t.Fatalf("allocation=%v: interrupted=%v", err, tc.interrupted) } - if tc.effectErr != nil && !tc.superseded && !errors.Is(err, tc.effectErr) { + if tc.effectErr != nil && !errors.Is(err, tc.effectErr) { t.Fatalf("lost start cause: %v", err) } if tc.confirmErr != nil && !errors.Is(err, tc.confirmErr) { diff --git a/placement/placement.go b/placement/placement.go index ae5aec49..e3f922d2 100644 --- a/placement/placement.go +++ b/placement/placement.go @@ -14,7 +14,6 @@ import ( "slices" "strings" "sync" - "sync/atomic" "time" "google.golang.org/grpc" @@ -483,7 +482,7 @@ func (p *Placer) Exec(ctx context.Context, log eventlog.Store, sessionUID string }() har := live.harness closeInvocation := func() error { - if err := live.checkSuperseded(ctx); err != nil { + if err := ctx.Err(); err != nil { return err } return p.releaseHarness(ctx, sessionUID, inc.ID, live) @@ -494,16 +493,13 @@ func (p *Placer) Exec(ctx context.Context, log eventlog.Store, sessionUID string _, fenceFinished := observability.BeginDebug(ctx, p.logger, "placement", "mint_fence", "session_uid", sessionUID) fence, err := log.NewFence() - live.fenceMinted() if err != nil { fenceFinished(err, "error_kind", "new_fence_failed") return inc, err } fenceFinished(nil) inc.FenceToken = fence // Placer-owned: the incarnation carries the token Suspend/Resume will need - // A checkpoint may have begun while the fence was being minted. Stop before the controller writes - // anything under a fence the checkpoint's does not cover. - if err := live.checkSuperseded(ctx); err != nil { + if err := ctx.Err(); err != nil { return inc, allocationStartError(operationCtx, err) } copts := append(p.controllerOpts(fence, sessionUID, cfg.observer), @@ -523,7 +519,7 @@ func (p *Placer) Exec(ctx context.Context, log eventlog.Store, sessionUID string // The park suspends or keeps the compute under the journal's approval gate. return inc, p.handoffPark(operationCtx, log, sessionUID, fence, park, closeInvocation, cfg.observer, guard) } - return inc, turnError(ctx, err) + return inc, controllerError(ctx, err) } return inc, nil } @@ -565,13 +561,6 @@ func (p *Placer) recheck(ctx context.Context, sessionUID string, har api.Harness if err == nil { err = refuseStatefulOverride(desc, override) } - if err != nil && errors.Is(context.Cause(ctx), errSuperseded) { - // A checkpoint of the session ended this turn's connection during the check. Report the - // checkpoint, as turnError does for a running turn, and format the check's error with %v so - // that ErrAdmissionInterrupted is not in the chain: the call is retryable (ABORTED), not - // cancelled by its caller. - return fmt.Errorf("%w (harness check ended with: %v)", errSuperseded, err) - } return err } @@ -804,64 +793,17 @@ func tcpDial(address string, opts []grpc.DialOption) (api.Harness, func() error, // retryable once that operation returns; session.Service maps it to codes.Aborted. var ErrCheckpointing = errors.New("placement: session is being checkpointed") -// errSuperseded is the cancellation cause of a turn whose harness connection a checkpoint ended. The -// checkpoint mints its fence before it ends the connection, so the turn has been superseded exactly -// as a fenced writer is, and the error says both. -var errSuperseded = fmt.Errorf("%w: in-flight turn superseded and its harness connection closed: %w", ErrCheckpointing, eventlog.ErrFenced) - -// turnError reports why a turn failed. When a checkpoint ended the turn's harness connection, the -// error the turn itself surfaced is incidental (a cancelled model call, a closed stream, a cut -// Describe), so the checkpoint is reported as the cause and the incidental error is kept for -// diagnosis; controllerError is not applied, because it would report the cut Describe as the -// caller's cancellation. Otherwise the controller's Describe boundary is mapped by controllerError. -func turnError(ctx context.Context, err error) error { - if cause := context.Cause(ctx); errors.Is(cause, errSuperseded) { - if errors.Is(err, errSuperseded) { - return err - } - return fmt.Errorf("%w (turn ended with: %w)", cause, err) - } - return controllerError(ctx, err) -} - -// liveHarness is one open harness connection and the means to end it from outside the turn that -// owns it. +// liveHarness is one registered harness connection and its idempotent cleanup. type liveHarness struct { harness api.Harness cancel context.CancelCauseFunc once sync.Once close func() error err error - // superseded is set, under sessionSet.mu, by the checkpoint that collects this connection, BEFORE - // that checkpoint mints its fence. A turn whose fence is newer than the checkpoint's is not - // fenced by it, but is guaranteed to observe this flag, so it checks the flag after minting. - superseded atomic.Bool - // minted is closed once the turn can no longer mint a fence: right after its one NewFence call - // returns, or when the turn releases the connection without having made it. A checkpoint waits - // on it so that no turn's fence can land after the fence the checkpoint records under. - minted chan struct{} - mintedOnce sync.Once -} - -// fenceMinted records that the turn has made its one NewFence call, successful or not. -func (l *liveHarness) fenceMinted() { - l.mintedOnce.Do(func() { close(l.minted) }) -} - -// checkSuperseded fails with errSuperseded if a checkpoint has claimed this connection or already -// ended it. The turn calls it right after minting its fence and before it writes anything. -func (l *liveHarness) checkSuperseded(ctx context.Context) error { - if l.superseded.Load() { - return errSuperseded - } - if ctx.Err() != nil { - return turnError(ctx, ctx.Err()) - } - return nil } // end cancels the turn's context, which ends its Connect stream, and closes the connection. It is -// idempotent, so the owning turn and a checkpoint can both call it. +// idempotent because approval handoff can close it before the turn's deferred cleanup runs. func (l *liveHarness) end(cause error) error { l.once.Do(func() { l.cancel(cause) @@ -870,20 +812,20 @@ func (l *liveHarness) end(cause error) error { return l.err } -// openHarness dials the incarnation's harness and registers the connection under the session, so a -// checkpoint of that session can end it. The returned context is the turn's: it is cancelled when -// the connection is ended from outside. +// openHarness dials the incarnation's harness and registers the connection under the session so +// connection registration and checkpoint-mark installation are atomic. The returned context is +// cancelled when the connection is closed. // // Registration is refused with ErrCheckpointing while a checkpoint of the session is in progress. -// The check and the registration happen under the same lock beginCheckpoint takes, so every turn -// either registered before the checkpoint began (and is ended by it) or never opens a stream. +// The check and registration happen under the same lock checkpoint marking takes, so a turn cannot +// slip a stream in after the mark is installed. func (p *Placer) openHarness(ctx context.Context, sessionUID string, inc api.Incarnation) (context.Context, *liveHarness, error) { har, closeHarness, err := p.dial(inc) if err != nil { return ctx, nil, err } ctx, cancel := context.WithCancelCause(ctx) - l := &liveHarness{harness: har, cancel: cancel, close: closeHarness, minted: make(chan struct{})} + l := &liveHarness{harness: har, cancel: cancel, close: closeHarness} p.sessions.mu.Lock() if _, ok := p.sessions.checkpoints[sessionUID]; ok { p.sessions.mu.Unlock() @@ -910,7 +852,6 @@ func (p *Placer) releaseHarness(ctx context.Context, sessionUID, incarnationID s delete(p.sessions.live, sessionUID) } p.sessions.mu.Unlock() - l.fenceMinted() // a turn that returns before minting never will _, finish := observability.BeginDebug(context.WithoutCancel(ctx), p.logger, "placement", "close_harness", "session_uid", sessionUID, "incarnation_id", incarnationID, @@ -941,17 +882,17 @@ func (p *Placer) refuseDuringCheckpoint(sessionUID string) error { // first one's SUSPEND record after the parent is already cold, or checkpoint the parent again and // replace the snapshot the first one's remaining children clone from; a fork beside a Suspend // would fail the Suspend's record the same way. -func (p *Placer) beginCheckpoint(sessionUID string) ([]*liveHarness, error) { +func (p *Placer) beginCheckpoint(sessionUID string) error { p.sessions.mu.Lock() defer p.sessions.mu.Unlock() if err := p.sessions.setCheckpointLocked(sessionUID); err != nil { - return nil, err + return err } if len(p.sessions.live[sessionUID]) != 0 { delete(p.sessions.checkpoints, sessionUID) - return nil, fmt.Errorf("%w: session %q has an open harness connection", ErrSessionBusy, sessionUID) + return fmt.Errorf("%w: session %q has an open harness connection", ErrSessionBusy, sessionUID) } - return nil, nil + return nil } // markCheckpoint excludes a stateful Fork during a guarded Suspend, approval decision, @@ -985,38 +926,6 @@ func (s *sessionSet) endCheckpoint(sessionUID string) { delete(s.checkpoints, sessionUID) } -// endHarnesses is retained for a checkpoint caller that explicitly collected connections. Stateful -// Fork holds operation admission through beginCheckpoint, so its set is empty and this is a no-op. -func (p *Placer) endHarnesses(ctx context.Context, sessionUID string, open []*liveHarness) (err error) { - if len(open) == 0 { - return nil - } - _, finish := observability.BeginDebug(ctx, p.logger, "placement", "end_harness_streams", - "session_uid", sessionUID, - "connections", len(open), - ) - var closeErrs []error - for _, l := range open { - closeErrs = append(closeErrs, l.end(errSuperseded)) - } - defer func() { - if err != nil { - finish(err, "error_kind", "superseded_turn_not_settled") - return - } - closeErr := errors.Join(closeErrs...) - finish(closeErr, "error_kind", closeErrorKind(closeErr)) - }() - for _, l := range open { - select { - case <-l.minted: - case <-ctx.Done(): - return fmt.Errorf("placement: waiting for the superseded turn on session %q to finish minting its fence: %w", sessionUID, context.Cause(ctx)) - } - } - return nil -} - // Suspend transitions the incarnation to cold via SnapshotExternal, then records the SnapshotRef // in a SUSPEND lifecycle event so Resume can recover it from the tamper-evident chain (§5.1). // Snapshot owns dedicated compute release and retains the handles Restore needs; Stop would @@ -1364,7 +1273,7 @@ func (p *Placer) resume(ctx context.Context, log eventlog.Store, sessionUID stri }() har := live.harness closeInvocation := func() error { - if err := live.checkSuperseded(ctx); err != nil { + if err := ctx.Err(); err != nil { return err } return p.releaseHarness(ctx, sessionUID, inc.ID, live) @@ -1372,18 +1281,17 @@ func (p *Placer) resume(ctx context.Context, log eventlog.Store, sessionUID stri if err := p.recheck(ctx, sessionUID, har, cfg.override); err != nil { return err } - // Retake the writer fence now that checkpoints can see this connection. Rechecking also - // catches a completed Fork during Restore, before any harness/model/tool redrive. + // Retake the writer fence after the connected-harness check, before any harness/model/tool + // redrive. _, fenceFinished := observability.BeginDebug(ctx, p.logger, "placement", "mint_fence", "session_uid", sessionUID) fence, err := p.resumeFence(log, sessionUID, cfg.expectedLastSeq) - live.fenceMinted() if err != nil { fenceFinished(err, "error_kind", "new_fence_failed") return err } fenceFinished(nil) inc.FenceToken = fence - if err := live.checkSuperseded(ctx); err != nil { + if err := ctx.Err(); err != nil { return allocationStartError(operationCtx, err) } copts := append(p.controllerOpts(fence, sessionUID, cfg.observer), controller.WithHarness(cfg.harness), @@ -1401,7 +1309,7 @@ func (p *Placer) resume(ctx context.Context, log eventlog.Store, sessionUID stri // The park suspends or keeps the compute under the journal's approval gate. return p.handoffPark(operationCtx, log, sessionUID, fence, park, closeInvocation, cfg.observer, guard) } - return turnError(ctx, err) + return controllerError(ctx, err) } head, err := log.Head() if err != nil { @@ -1689,9 +1597,9 @@ func (p *Placer) forkSource(ctx context.Context, parent eventlog.Store, parentUI return api.SnapshotRef{}, nil, fmt.Errorf("%w: harness %q requires %s, which can only fork at the log head (%d), not seq %d", ErrUnplaceable, desc.ID, desc.Capabilities.Resumability, head, atSeq) } - // Refuse before the checkpoint mark, fence, or stream cancellation. A memory snapshot must not - // capture RAM changed by a turn whose END is absent: Resume could otherwise run that turn again - // and apply the mutation twice. + // Refuse before the checkpoint mark, fence, snapshot, or journal write. A memory snapshot must + // not capture RAM changed by a turn whose END is absent: Resume could otherwise run that turn + // again and apply the mutation twice. recs, err := parent.Read(1) if err != nil { return api.SnapshotRef{}, nil, fmt.Errorf("placement: read parent journal: %w", err) @@ -1704,8 +1612,7 @@ func (p *Placer) forkSource(ctx context.Context, parent eventlog.Store, parentUI } // Atomically prevent a new stream from opening. The operation hold above excludes both running // turns and pre-journal connection preparation, so no stream is cancelled by Fork. - open, err := p.beginCheckpoint(parentUID) - if err != nil { + if err := p.beginCheckpoint(parentUID); err != nil { return api.SnapshotRef{}, nil, err } // The mark now excludes new local turns and competing checkpoints. Release ordinary operation @@ -1725,17 +1632,14 @@ func (p *Placer) forkSource(ctx context.Context, parent eventlog.Store, parentUI return api.SnapshotRef{}, nil, err } // A writer on another host could still have committed in the window before that fence landed. - // Re-check now, while - // aborting is free: after the snapshot the parent is cold whether or not the fork proceeds. + // Re-check now, while aborting is free: after the snapshot the parent is cold whether or not the + // fork proceeds. if head, err = parent.Head(); err != nil { return api.SnapshotRef{}, nil, err } if atSeq != head { return api.SnapshotRef{}, nil, fmt.Errorf("%w: parent advanced from seq %d to %d while the fork was being prepared", eventlog.ErrConflict, atSeq, head) } - if err := p.endHarnesses(ctx, parentUID, open); err != nil { - return api.SnapshotRef{}, nil, allocationStartError(ctx, err) - } // Mint the fence the record is written under now, and re-check the head while aborting is still // free. The local checkpoint mark excludes new streams; the second fence narrows the race with a // writer on another host. diff --git a/session/error_reasons_test.go b/session/error_reasons_test.go index 5241162f..3d27f212 100644 --- a/session/error_reasons_test.go +++ b/session/error_reasons_test.go @@ -63,7 +63,7 @@ func TestOperationErrorReasons(t *testing.T) { {"compute busy", api.ErrComputeBusy, codes.Aborted, "COMPUTE_BUSY"}, {"fenced", eventlog.ErrFenced, codes.Aborted, "FENCED"}, {"checkpoint", placement.ErrCheckpointing, codes.Aborted, "CHECKPOINT_IN_PROGRESS"}, - {"checkpoint supersedes fence", errors.Join(placement.ErrCheckpointing, eventlog.ErrFenced, context.Canceled), codes.Aborted, "CHECKPOINT_IN_PROGRESS"}, + {"checkpoint before fence", errors.Join(placement.ErrCheckpointing, eventlog.ErrFenced, context.Canceled), codes.Aborted, "CHECKPOINT_IN_PROGRESS"}, {"deleted", eventlog.ErrDeleted, codes.FailedPrecondition, "SESSION_DELETED"}, {"memory lost", api.ErrMemoryStateLost, codes.FailedPrecondition, "MEMORY_STATE_LOST"}, {"invalid checkpoint", api.ErrInvalidCheckpoint, codes.FailedPrecondition, "CHECKPOINT_INVALID"}, diff --git a/session/errors.go b/session/errors.go index 239eae9c..1b1a4679 100644 --- a/session/errors.go +++ b/session/errors.go @@ -56,8 +56,7 @@ func errorReason(code codes.Code, err error) string { // cause. Report the fork point that invalidated the operation. {api.ErrSnapshotSuperseded, "SNAPSHOT_SUPERSEDED"}, {api.ErrComputeBusy, "COMPUTE_BUSY"}, - // A checkpoint supersedes a live turn by fencing it; report the operation, - // not its incidental fence or canceled model call. + // Checkpoint contention takes precedence if an error also carries a stale fence. {placement.ErrCheckpointing, "CHECKPOINT_IN_PROGRESS"}, {eventlog.ErrFenced, "FENCED"}, } diff --git a/session/service.go b/session/service.go index 0d22353e..8e0bb7d9 100644 --- a/session/service.go +++ b/session/service.go @@ -1273,8 +1273,8 @@ func resumeError(uid string, err error) error { case errors.Is(err, placement.ErrHarnessUnavailable): return statusError(codes.Unavailable, err, fmt.Sprintf("resume: %v", err)) case errors.Is(err, placement.ErrCheckpointing), errors.Is(err, api.ErrComputeBusy): - // A stateful Fork of this session superseded this Resume's turn, or the session's compute - // is in the middle of another operation; retry once it completes. + // A checkpoint mark refused this Resume, or the session's compute is in the middle of another + // operation; retry once it completes. return statusError(codes.Aborted, err, fmt.Sprintf("resume: %v", err)) case errors.Is(err, api.ErrCheckpointPending): return statusError(codes.Unavailable, err, fmt.Sprintf("resume: session %q: %v", uid, err)) diff --git a/spec.md b/spec.md index 5eb2c41c..6f70a87e 100644 --- a/spec.md +++ b/spec.md @@ -1423,10 +1423,11 @@ records only. from the journal. - `OPS-18`: `Suspend` routes to the stored harness, except that an owned unreceipted approval routes to its recorded harness (`OPS-8`). -- The reference host accepts `Suspend` on a session that is already cold or has never run, and - appends another `SUSPEND`. `Resume` without a prior `Suspend` is also accepted. The host does not - check either case itself; whether the call succeeds is up to the backend (`RT-4b`, `RT-4c`). With - `runtime/local` and `runtime/remote` both succeed. With `runtime/substrate`, both fail when no +- Except for an `OPS-3` incomplete-turn refusal, the reference host accepts `Suspend` on a session + that is already cold or has never run, and appends another `SUSPEND`. `Resume` without a prior + `Suspend` is also accepted. The host does not check either case itself; whether the call succeeds + is up to the backend (`RT-4b`, `RT-4c`). `runtime/local` and `runtime/remote` both succeed. With + `runtime/substrate`, both fail when no actor exists for the session uid, for example a fresh session before any `Create` reached `CreateActor` (a fork child gets its actor from `Fork`): `SuspendActor` and `ResumeActor` return `NOT_FOUND` and no marker is appended. For a `REQUIRES_MEMORY_SNAPSHOT` harness the backend @@ -1587,10 +1588,10 @@ or an unclassified error may supply none. | `RESOURCE_EXHAUSTED` | No eligible compute capacity → `COMPUTE_RESOURCE_EXHAUSTED` | A stale cursor requires reading the head before retrying. Session/compute contention can be -retried after the current operation finishes; a superseded fence needs a new writer. A checkpoint -that fenced an in-flight turn reports CHECKPOINT_IN_PROGRESS rather than its incidental fence -or canceled model call. Deleted sessions and lost memory state retain FAILED_PRECONDITION, not a -retryable compute outage. Other existing preconditions retain their codes without a reason. +retried after the current operation finishes; a superseded fence needs a new writer. Contention +with a checkpoint holder reports CHECKPOINT_IN_PROGRESS; an independently stale writer reports +FENCED. Deleted sessions and lost memory state retain FAILED_PRECONDITION, not a retryable compute +outage. Other existing preconditions retain their codes without a reason. The Go runtime SPI's `ErrComputeUnavailable`, `ErrComputeResourceExhausted` and `ErrComputeConfigInvalid` explicitly classify compute-start failures. Existing lifecycle refusals @@ -1959,9 +1960,7 @@ The reference host takes it as `placement.Backend` in (`api.ErrMemoryStateLost`), and `LIVE` is the replaced instance. The host returns the error unchanged. - Another owner may hold it: a record committed during the call, or the call failed on a - checkpoint in progress, a newer fence, or a deleted session. A checkpoint that superseded the - turn (`OPS-2`) counts as in progress: a stateful fork may still be snapshotting the compute, or - may fail before it suspends it. The host releases nothing. + checkpoint in progress, a newer fence, or a deleted session. The host releases nothing. - The owner is unknown: the host cannot read the journal or verify its chain, the journal ends before the head it had when the call began (a lost tail can leave a prefix that verifies and reads `LIVE`), the journal reads `LIVE` but does not attribute every turn to one harness, or From a8a60c88a2f6d03051ebee3a725d8c4f1df36362 Mon Sep 17 00:00:00 2001 From: Tatsat Mishra Date: Sun, 29 Nov 2026 23:33:40 +1300 Subject: [PATCH 4/5] fix(placement): classify approval handoff races --- placement/approval_test.go | 58 ++++++++++++++++++++++++++++++++++++++ placement/placement.go | 15 ++++++---- 2 files changed, 68 insertions(+), 5 deletions(-) diff --git a/placement/approval_test.go b/placement/approval_test.go index b5fe3cba..40e00e39 100644 --- a/placement/approval_test.go +++ b/placement/approval_test.go @@ -360,6 +360,64 @@ func TestPlacementApprovalHandoffPhases(t *testing.T) { } } +func TestApprovalHandoffRefusesPeerDecisionBeforeCheckpoint(t *testing.T) { + for _, operation := range []string{"Exec", "Resume"} { + t.Run(operation, func(t *testing.T) { + log := newSuspendStore(t).Session("s") + har := memoryGateHarness{} + desc, err := har.Describe(t.Context()) + if err != nil { + t.Fatal(err) + } + ctl := newSuspendControl() + if operation == "Resume" { + seedPlacementApproval(t, log, "gate", api.EventExecutionStart) + ctl.actors[substrate.ActorRef{Atespace: "space", Name: "s"}] = &suspendActor{ + status: substrate.StatusRunning, worker: true, uid: ctl.newUID(), + } + } + b := &approvalBackend{Backend: substrate.New(ctl, "space", substrate.ObjectRef{Name: "gate"}, desc)} + closes := 0 + p := placement.New(b, nil, placement.WithDialer(func(api.Incarnation) (api.Harness, func() error, error) { + return har, func() error { + closes++ + state, err := controller.InspectApproval(log, 0) + if err != nil || state == nil || state.Request == nil || state.Decision != nil { + t.Fatalf("gate before peer decision=%+v, %v", state, err) + } + _, err = controller.Approve(log, api.ApprovalDecision{ + ExecutionID: state.ExecutionID, ToolCallID: state.Call.ID, + RequestSeq: state.Request.Seq, Approved: true, + }) + return err + }, nil + })) + + if operation == "Exec" { + _, err = p.Exec(t.Context(), log, "s", nil, 0) + } else { + err = p.Resume(t.Context(), log, "s") + } + if !errors.Is(err, eventlog.ErrConflict) || errors.Is(err, controller.ErrCheckpointIncompleteTurn) || + errors.Is(err, placement.ErrComputeLeftRunning) { + t.Fatalf("%s handoff=%v, want ErrConflict only", operation, err) + } + if closes != 1 || b.snapshots != 0 { + t.Fatalf("%s handoff closes=%d snapshots=%d, want 1/0", operation, closes, b.snapshots) + } + state, inspectErr := controller.InspectApproval(log, 0) + if inspectErr != nil || state == nil || state.Decision == nil || state.Receipt != nil { + t.Fatalf("gate after peer decision=%+v, %v", state, inspectErr) + } + for _, rec := range suspendRecords(t, log) { + if rec.Event.Kind == api.EventLifecycle && rec.Event.Lifecycle.Kind == api.LifecycleSuspend { + t.Fatalf("%s handoff recorded SUSPEND after peer movement", operation) + } + } + }) + } +} + func TestResumeApprovalHandoffSnapshotFailureKeepsOperationalCause(t *testing.T) { log := newSuspendStore(t).Session("s") seedPlacementApproval(t, log, "gate", api.EventExecutionStart) diff --git a/placement/placement.go b/placement/placement.go index e3f922d2..c5da9d6e 100644 --- a/placement/placement.go +++ b/placement/placement.go @@ -985,6 +985,15 @@ func (p *Placer) suspend(ctx context.Context, log eventlog.Store, sessionUID str if err != nil { return api.SnapshotRef{}, fmt.Errorf("placement: read session journal: %w", err) } + head := int64(0) + if len(recs) > 0 { + head = recs[len(recs)-1].Seq + } + // A peer may decide the gate after handoffPark's inspection. Report that movement before the + // newer state can be mistaken for an unsafe checkpoint boundary. + if cursor != nil && head != cursor.head { + return api.SnapshotRef{}, fmt.Errorf("%w: session head changed from seq %d to %d while approval handoff was being prepared", eventlog.ErrConflict, cursor.head, head) + } // Stateless snapshots carry no process memory, so replaying an incomplete turn is safe. A // memory-capable backend can host either tier, so read its descriptor before applying the // memory-only checkpoint rule. Backends without memory snapshots keep Suspend's no-admission path. @@ -1001,13 +1010,9 @@ func (p *Placer) suspend(ctx context.Context, log eventlog.Store, sessionUID str } } } - head := int64(0) - if len(recs) > 0 { - head = recs[len(recs)-1].Seq - } fence := int64(0) if cursor != nil { - head, fence = cursor.head, cursor.fence + fence = cursor.fence } else if memoryCheckpoint { // Bind the irreversible capture to the exact journal state validated above. A peer writer // that moves the head after this fence makes the later SUSPEND CAS fail instead of widening From e878df3552347f079140fb80334ae36d8826b4f5 Mon Sep 17 00:00:00 2001 From: Tatsat Mishra Date: Mon, 30 Nov 2026 10:49:50 +1300 Subject: [PATCH 5/5] fix(placement): classify fork reread races --- .../incomplete-memory-checkpoint-compat.md | 4 +- placement/placement.go | 7 +++ placement/placement_test.go | 63 +++++++++++++++++++ spec.md | 14 +++-- 4 files changed, 81 insertions(+), 7 deletions(-) diff --git a/changelog/unreleased/incomplete-memory-checkpoint-compat.md b/changelog/unreleased/incomplete-memory-checkpoint-compat.md index 7e13065e..8072adc4 100644 --- a/changelog/unreleased/incomplete-memory-checkpoint-compat.md +++ b/changelog/unreleased/incomplete-memory-checkpoint-compat.md @@ -9,7 +9,9 @@ category: Compatibility 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. Earlier hosts accepted and checkpointed that boundary. + 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 diff --git a/placement/placement.go b/placement/placement.go index c5da9d6e..7c48fb3e 100644 --- a/placement/placement.go +++ b/placement/placement.go @@ -1669,6 +1669,13 @@ func (p *Placer) forkSource(ctx context.Context, parent eventlog.Store, parentUI if err != nil { return api.SnapshotRef{}, nil, fmt.Errorf("placement: read parent journal: %w", err) } + rereadHead := int64(0) + if len(recs) > 0 { + rereadHead = recs[len(recs)-1].Seq + } + if rereadHead != atSeq { + return api.SnapshotRef{}, nil, fmt.Errorf("%w: parent advanced from seq %d to %d while the fork was being prepared", eventlog.ErrConflict, atSeq, rereadHead) + } if err := controller.ValidateCheckpointState(recs); err != nil { return api.SnapshotRef{}, nil, err } diff --git a/placement/placement_test.go b/placement/placement_test.go index 0c11a05a..f692fad4 100644 --- a/placement/placement_test.go +++ b/placement/placement_test.go @@ -950,6 +950,69 @@ func TestForkAbortsWhenParentAdvancesUnderIt(t *testing.T) { } } +type forkRereadRaceLog struct { + eventlog.Store + fences int + beforeFinalReread func() +} + +func (l *forkRereadRaceLog) NewFence() (int64, error) { + fence, err := l.Store.NewFence() + if err == nil { + l.fences++ + } + return fence, err +} + +func (l *forkRereadRaceLog) Read(from int64) ([]eventlog.Record, error) { + if l.fences == 2 && l.beforeFinalReread != nil { + hook := l.beforeFinalReread + l.beforeFinalReread = nil + hook() + } + return l.Store.Read(from) +} + +// A peer can append after Fork's final Head check but before its journal reread. That movement is a +// retryable conflict, even when the new tail is an incomplete turn; Fork must classify the moved +// head before classifying checkpoint safety and must not reach the runtime. +func TestForkClassifiesAdvanceBeforeFinalRereadAsConflict(t *testing.T) { + store, err := sqlitelog.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + parent, peer, child := store.Session("parent"), store.Session("parent"), store.Session("child") + head := appendCompletedLegacyTurn(t, parent, "one") + raced := false + wrapped := &forkRereadRaceLog{Store: parent} + wrapped.beforeFinalReread = func() { + raced = true + fence, err := peer.NewFence() + if err != nil { + t.Fatal(err) + } + _, err = peer.Append(head, fence, api.Event{ExecutionID: "peer", Kind: api.EventExecutionStart, + ExecutionStart: &api.ExecutionStart{Harness: "mem", InputCount: proto.Int64(0)}}) + if err != nil { + t.Fatal(err) + } + } + + ctl := &cloningControl{snapshot: "snap-parent-1"} + err = memorySubstratePlacer(ctl).Fork(t.Context(), wrapped, "parent", + []placement.ForkChild{{UID: "child", Log: child}}, head) + if !raced || !errors.Is(err, eventlog.ErrConflict) || errors.Is(err, controller.ErrCheckpointIncompleteTurn) { + t.Fatalf("Fork = %v raced=%t, want ErrConflict rather than ErrCheckpointIncompleteTurn", err, raced) + } + if len(ctl.calls) != 0 { + t.Fatalf("conflicted Fork reached the runtime: %v", ctl.calls) + } + if childHead, err := child.Head(); err != nil || childHead != 0 { + t.Fatalf("conflicted Fork wrote child head=%d err=%v", childHead, err) + } +} + // A fan-out that fails partway must not strand the children it already provisioned: their UIDs are // never returned to the caller, so an un-rolled-back actor is unreachable and unstoppable. func TestForkFanOutRollsBackProvisionedChildren(t *testing.T) { diff --git a/spec.md b/spec.md index 6f70a87e..b0ade2bb 100644 --- a/spec.md +++ b/spec.md @@ -1316,12 +1316,14 @@ records only. approval repair refuse with `ABORTED` during a checkpoint? - `OPS-3`: A `REQUIRES_MEMORY_SNAPSHOT` fork MUST refuse a locally active parent execution with `ABORTED`, without ending its harness stream, fencing it, snapshotting or writing. A trailing - execution without `END` that is no longer locally active MUST be `FAILED_PRECONDITION` - (`CHECKPOINT_INCOMPLETE_TURN`) before those effects: its RAM may contain a mutation not represented - by the journal, and recovery could apply it again. The approval park in `APR-3` is an intentional - exception while it remains undecided, as are an inherited unresolved gate that recovery refuses - and a partial input prefix that never reached `Harness.Run`. A decided unreceipted gate is refused: - a prior recovery may have changed RAM before failing without a receipt. + execution without `END` that is not locally active MUST be `FAILED_PRECONDITION` + (`CHECKPOINT_INCOMPLETE_TURN`) before those effects. This includes a turn still running through + another writer that shares the journal; once it records `END`, a retry passes this completeness + check. Its RAM may contain a mutation not represented by the journal, and recovery could apply it + again. The approval park in `APR-3` is an intentional exception while it remains undecided, as are + an inherited unresolved gate that recovery refuses and a partial input prefix that never reached + `Harness.Run`. A decided unreceipted gate is refused: a prior recovery may have changed RAM before + failing without a receipt. - `CreateSession`, `GetSession`, `ListSessions`, and `Replay` take no guard. Every Fork takes only the deletion exclusion (`OPS-30`) for its full operation. A `REQUIRES_MEMORY_SNAPSHOT` fork also takes the `OPS-1` session guard transiently through validation and checkpoint-mark installation,