Repository navigation
fix(placement): refuse unsafe memory checkpoints #296
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Tatsat (Tats) Mishra 🐉 (Tatsinnit)
wants to merge
5
commits into
agent-primitives:main
Choose a base branch
from
Tatsinnit:fix/98-incomplete-memory-checkpoint
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
7e06d5f
fix(placement): refuse unsafe memory checkpoints
Tatsinnit fc848b1
test(placement): join refused prepared execution
Tatsinnit 4b746b8
fix(placement): address checkpoint review feedback
Tatsinnit a8a60c8
fix(placement): classify approval handoff races
Tatsinnit e878df3
fix(placement): classify fork reread races
Tatsinnit File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
28 changes: 28 additions & 0 deletions
28
changelog/unreleased/incomplete-memory-checkpoint-compat.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| --- | ||
| category: Compatibility | ||
| --- | ||
|
|
||
| - A `REQUIRES_MEMORY_SNAPSHOT` Fork of a locally active parent now returns `ABORTED` with | ||
| `agentsessions/SESSION_BUSY` without ending or fencing the turn. Earlier hosts let Fork proceed: | ||
| they fenced and ended the turn, which returned `ABORTED` with | ||
| `agentsessions/CHECKPOINT_IN_PROGRESS`, before attempting the parent checkpoint. Pre-journal | ||
| preparation is now refused the same way as an active turn. | ||
| - Memory-tier Suspend and Fork now return `FAILED_PRECONDITION` with | ||
| `agentsessions/CHECKPOINT_INCOMPLETE_TURN` when the latest turn is incomplete and recovery may run | ||
| it again. This includes a turn still running through another writer that shares the journal; a | ||
| retry passes this check after it records `END`. Earlier hosts accepted and checkpointed that | ||
| boundary. | ||
| - On a backend that advertises memory snapshots, Suspend now admits the harness before fencing or | ||
| snapshotting. While the caller remains live, an unreachable harness returns `UNAVAILABLE` with | ||
| `agentsessions/HARNESS_UNAVAILABLE`; a descriptor mismatch or invalid harness class returns | ||
| `FAILED_PRECONDITION`. | ||
| - Fork failures wrapping `controller.ErrInvalidExecutionLog` or `controller.ErrReplayDiverged` now | ||
| return `FAILED_PRECONDITION` instead of `INTERNAL`. Suspend failures wrapping | ||
| `eventlog.ErrTampered` now return `DATA_LOSS` instead of `INTERNAL`. | ||
| - A custom memory `api.Runtime` whose compute can retain captures must compare its held capture with | ||
| `SessionSpec.RecordedCheckpoint`, `Incarnation.RecordedCheckpoint`, or the ref passed to | ||
| `Restore`, and return `api.ErrMemoryStateLost` before attaching, resuming, or recapturing when | ||
| they differ. | ||
| Upgrade every such Runtime before, or atomically with, Sessions hosts built with this change. On | ||
| rollback, roll back Sessions hosts first; do not restore a non-enforcing Runtime while an | ||
| unrecorded capture may remain. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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`. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| package controller | ||
|
|
||
| import ( | ||
| "errors" | ||
|
|
||
| "github.com/agent-primitives/sessions/api" | ||
| "github.com/agent-primitives/sessions/eventlog" | ||
| ) | ||
|
|
||
| // ErrCheckpointIncompleteTurn refuses a memory checkpoint whose latest execution recovery may run | ||
| // again. Capturing RAM after the harness changed it but before END committed would let Resume apply | ||
| // the same mutation twice. | ||
| var ErrCheckpointIncompleteTurn = errors.New("controller: checkpoint refused because the latest execution is incomplete and recovery may run it again") | ||
|
|
||
| // ValidateCheckpointState verifies records and reports whether a memory checkpoint can be taken | ||
| // without capturing a turn that Resume may run again. A partial input prefix is safe because the | ||
| // harness was not invoked. An owned undecided approval request and an inherited unresolved request | ||
| // are also safe: recovery parks or refuses them without invoking the harness. A decided gate is not | ||
| // safe: an earlier recovery may have changed RAM before failing without a receipt. | ||
| func ValidateCheckpointState(records []eventlog.Record) error { | ||
| if err := verifyRecords("", records); err != nil { | ||
| return err | ||
| } | ||
| events := make([]api.Event, 0, len(records)) | ||
| for _, record := range records { | ||
| events = append(events, record.Event) | ||
| } | ||
| executions, err := recordedExecutions(events) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| scan, err := scanApprovalRecords(records, 0) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| execution, err := pendingResumeExecution(events, executions) | ||
| if err != nil { | ||
| if errors.Is(err, ErrIncompleteInvocation) && len(executions) > 0 && | ||
| incompleteInputPrefix(events, executions[len(executions)-1]) { | ||
| return nil | ||
| } | ||
| return err | ||
| } | ||
| if execution == nil { | ||
| return nil | ||
| } | ||
| if state := scan.selected; state != nil && state.ExecutionID == execution.id && state.Receipt == nil { | ||
| if state.Inherited || state.Request != nil && state.Decision == nil { | ||
| return nil | ||
| } | ||
| } | ||
| return ErrCheckpointIncompleteTurn | ||
| } | ||
|
|
||
| // incompleteInputPrefix recognizes only the prefix Exec can leave before Harness.Run: one valid | ||
| // start followed by fewer valid inputs than it declared, with no later event from any execution. | ||
| func incompleteInputPrefix(events []api.Event, execution recordedExecution) bool { | ||
| if !execution.hasStart || execution.completed || execution.inputCount == nil || | ||
| execution.inputRecords != len(execution.inputs) || int64(execution.inputRecords) >= *execution.inputCount { | ||
| return false | ||
| } | ||
| for i, event := range events[execution.start:] { | ||
| if event.Kind == api.EventLifecycle { | ||
| continue | ||
| } | ||
| if event.ExecutionID != execution.id { | ||
| return false | ||
| } | ||
| switch event.Kind { | ||
| case api.EventExecutionStart: | ||
| if i != 0 || event.ExecutionStart == nil { | ||
| return false | ||
| } | ||
| case api.EventInput: | ||
| if event.Message == nil { | ||
| return false | ||
| } | ||
| default: | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| package controller | ||
|
|
||
| import ( | ||
| "errors" | ||
| "testing" | ||
|
|
||
| "github.com/agent-primitives/sessions/api" | ||
| "github.com/agent-primitives/sessions/eventlog" | ||
| ) | ||
|
|
||
| func checkpointRecords(t *testing.T, events ...api.Event) []eventlog.Record { | ||
| t.Helper() | ||
| log := gateLog(t, events...) | ||
| records, err := log.Read(1) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| return records | ||
| } | ||
|
|
||
| func TestValidateCheckpointState(t *testing.T) { | ||
| zero, one, two := int64(0), int64(1), int64(2) | ||
| start := func(id string, count *int64) api.Event { | ||
| return api.Event{ExecutionID: id, Kind: api.EventExecutionStart, ExecutionStart: &api.ExecutionStart{InputCount: count}} | ||
| } | ||
| input := func(id string) api.Event { | ||
| return api.Event{ExecutionID: id, Kind: api.EventInput, Message: api.TextMessage("user", "hi")} | ||
| } | ||
| end := func(id string) api.Event { | ||
| return api.Event{ExecutionID: id, Kind: api.EventEnd, End: &api.HarnessEnd{State: "COMPLETED"}} | ||
| } | ||
| failure := api.Event{ExecutionID: "e", Kind: api.EventError, Err: &api.Error{Description: "failed"}} | ||
| lifecycle := api.Event{Kind: api.EventLifecycle, Lifecycle: &api.Lifecycle{Kind: api.LifecycleSuspend}} | ||
|
|
||
| for _, tc := range []struct { | ||
| name string | ||
| events []api.Event | ||
| want error | ||
| }{ | ||
| {name: "empty"}, | ||
| {name: "lifecycle only", events: []api.Event{lifecycle}}, | ||
| {name: "completed", events: []api.Event{start("e", &one), input("e"), end("e")}}, | ||
| {name: "modern pending", events: []api.Event{start("e", &one), input("e")}, want: ErrCheckpointIncompleteTurn}, | ||
| {name: "modern error remains pending", events: []api.Event{start("e", &zero), failure}, want: ErrCheckpointIncompleteTurn}, | ||
| {name: "markerless modern pending", events: []api.Event{input("e")}, want: ErrCheckpointIncompleteTurn}, | ||
| {name: "partial input prefix", events: []api.Event{start("e", &two), input("e")}}, | ||
| {name: "partial input with error is invalid", events: []api.Event{start("e", &two), input("e"), failure}, want: ErrInvalidExecutionLog}, | ||
| {name: "legacy pending", events: []api.Event{{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}}, want: ErrCheckpointIncompleteTurn}, | ||
| {name: "legacy end", events: []api.Event{{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}, {Kind: api.EventEnd}}}, | ||
| {name: "legacy error", events: []api.Event{{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}, {Kind: api.EventError, Err: &api.Error{Description: "failed"}}}}, | ||
| {name: "older incomplete superseded", events: []api.Event{start("old", &zero), start("new", &zero), end("new")}}, | ||
| {name: "approval call only", events: gateEvents()[:2], want: ErrCheckpointIncompleteTurn}, | ||
| {name: "approval pending", events: gateEvents()[:3]}, | ||
| {name: "approval decided", events: gateEvents()[:4], want: ErrCheckpointIncompleteTurn}, | ||
| {name: "approval decided recovery failed", events: append(append([]api.Event(nil), gateEvents()[:4]...), failure), want: ErrCheckpointIncompleteTurn}, | ||
| {name: "approval receipt remains pending", events: gateEvents()[:5], want: ErrCheckpointIncompleteTurn}, | ||
| {name: "approval completed", events: gateEvents()}, | ||
| } { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| err := ValidateCheckpointState(checkpointRecords(t, tc.events...)) | ||
| if tc.want == nil && err != nil || tc.want != nil && !errors.Is(err, tc.want) { | ||
| t.Fatalf("ValidateCheckpointState = %v, want %v", err, tc.want) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestValidateCheckpointStateAllowsInheritedOpenApproval(t *testing.T) { | ||
| parent := gateLog(t, gateEvents()[:4]...) | ||
| child := gateLog(t) | ||
| if err := Fork(parent, child, 4); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| records, err := child.Read(1) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if err := ValidateCheckpointState(records); err != nil { | ||
| t.Fatalf("ValidateCheckpointState = %v", err) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.