Skip to content

Commit 16faff1

Browse files
authored
Bind the Runtime to its Environment and serve one Session at a time (#926)
* Add agent.RemoveSessionState to delete other Sessions' native state * Bind the Runtime to its Environment and serve one Session at a time Remove the Session from runtime_prepare, workspace_write and the capability identity (proto 0.26.0). A prepare for another Session closes an idle executor, removes the other Sessions' native state and then prepares; a busy executor answers resource_unavailable. With one Session per Runtime, the executor capacity limits are gone. * Limit the one-Session rule to Runtimes bound to an Environment An unbound Runtime, such as the service-side host for environment: none, serves Sessions concurrently again: restore the executor capacity limits, idle eviction and session_binding_conflict with their tests. * Switch Sessions inside the new Executor's preparation Run every non-destructive admission check before closing another Session, close and remove state outside the receive loop, ignore the enrollment receipt's Session, require a canonical Session key on bound Runtimes, skip stray files under the runtime directory, and fix stale docs.
1 parent a4f74df commit 16faff1

55 files changed

Lines changed: 363 additions & 201 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/daemon/internal/agent/codex/preparation_router_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ func TestPreparationRouterRetainsActualNativeChild(t *testing.T) {
3939
if err := os.MkdirAll(workspace, 0700); err != nil {
4040
t.Fatal(err)
4141
}
42-
binding, err := localworkspace.NewWithCapabilityDirectory(environment, session, workspace, filepath.Join(t.TempDir(), "capabilities"))
42+
binding, err := localworkspace.NewWithCapabilityDirectory(environment, workspace, filepath.Join(t.TempDir(), "capabilities"))
4343
if err != nil {
4444
t.Fatal(err)
4545
}

‎apps/daemon/internal/agent/mcode/tool_environment_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ func TestWorkspaceCredentialsRemainInRuntimeSnapshotAcrossReconnect(t *testing.T
4444
req.AgentSessionID = "native-1"
4545
write(source, `{"MCP_TEST_TOKEN":"changed","TOOL_SECRET":"changed"}`)
4646
}
47-
binding, err := localworkspace.NewWithCapabilityDirectory(environment, session, config.Directory, capabilityDirectory)
47+
binding, err := localworkspace.NewWithCapabilityDirectory(environment, config.Directory, capabilityDirectory)
4848
if err != nil {
4949
t.Fatal(err)
5050
}
@@ -97,7 +97,7 @@ func TestWorkspaceCredentialsRemainInRuntimeSnapshotAcrossReconnect(t *testing.T
9797
if err := os.Remove(filepath.Join(initialization, "tool-env.json")); err != nil {
9898
t.Fatal(err)
9999
}
100-
binding, err := localworkspace.NewWithCapabilityDirectory(environment, session, config.Directory, capabilityDirectory)
100+
binding, err := localworkspace.NewWithCapabilityDirectory(environment, config.Directory, capabilityDirectory)
101101
if err != nil {
102102
t.Fatal(err)
103103
}

‎apps/daemon/internal/agent/runtime_paths.go‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package agent
22

33
import (
44
"fmt"
5+
"os"
56
"path/filepath"
67
"strings"
78
)
@@ -49,3 +50,41 @@ func safeRuntimePathPart(value string) string {
4950
}
5051
return value
5152
}
53+
54+
// RemoveSessionState deletes the state directory of every key but keepKey under
55+
// both roots, for every agent kind. It lists directories instead of tracking
56+
// Sessions, so it also covers state left by earlier processes and checkpoints.
57+
func RemoveSessionState(stateRoot, runtimeRoot, keepKey string) error {
58+
keep := safeRuntimePathParts(keepKey)
59+
if len(keep) != 1 {
60+
return fmt.Errorf("agent: invalid agent state key %q", keepKey)
61+
}
62+
for _, root := range []string{stateRoot, runtimeRoot} {
63+
if !filepath.IsAbs(root) || filepath.Clean(root) != root {
64+
return fmt.Errorf("agent: state root must be a clean absolute directory")
65+
}
66+
kinds, err := os.ReadDir(filepath.Join(root, "runtime"))
67+
if err != nil && !os.IsNotExist(err) {
68+
return err
69+
}
70+
for _, kind := range kinds {
71+
if !kind.IsDir() {
72+
continue
73+
}
74+
states := filepath.Join(root, "runtime", kind.Name(), "state")
75+
entries, err := os.ReadDir(states)
76+
if err != nil && !os.IsNotExist(err) {
77+
return err
78+
}
79+
for _, entry := range entries {
80+
if entry.Name() == keep[0] {
81+
continue
82+
}
83+
if err := os.RemoveAll(filepath.Join(states, entry.Name())); err != nil {
84+
return err
85+
}
86+
}
87+
}
88+
}
89+
return nil
90+
}

‎apps/daemon/internal/agent/runtime_paths_test.go‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package agent
22

33
import (
4+
"os"
45
"path/filepath"
56
"testing"
67
)
@@ -31,3 +32,42 @@ func TestStateDirRequiresAgentState(t *testing.T) {
3132
t.Fatalf("sanitized state = %q, %v; want %q", got, err, want)
3233
}
3334
}
35+
36+
func TestRemoveSessionStateKeepsOnlyTheNamedKey(t *testing.T) {
37+
stateRoot, runtimeRoot := t.TempDir(), t.TempDir()
38+
var kept, removed []string
39+
for _, root := range []string{stateRoot, runtimeRoot} {
40+
for _, kind := range []string{"codex", "claude-sdk"} {
41+
keep, err := StateDir(root, kind, "keep")
42+
if err != nil {
43+
t.Fatal(err)
44+
}
45+
other, _ := StateDir(root, kind, "other")
46+
for _, dir := range []string{keep, other} {
47+
if err := os.MkdirAll(filepath.Join(dir, "history"), 0o700); err != nil {
48+
t.Fatal(err)
49+
}
50+
}
51+
kept, removed = append(kept, keep), append(removed, other)
52+
}
53+
}
54+
if err := os.WriteFile(filepath.Join(stateRoot, "runtime", ".DS_Store"), nil, 0o600); err != nil {
55+
t.Fatal(err)
56+
}
57+
if err := RemoveSessionState(stateRoot, runtimeRoot, "keep"); err != nil {
58+
t.Fatal(err)
59+
}
60+
for _, dir := range kept {
61+
if _, err := os.Stat(dir); err != nil {
62+
t.Fatalf("kept state removed: %v", err)
63+
}
64+
}
65+
for _, dir := range removed {
66+
if _, err := os.Stat(dir); !os.IsNotExist(err) {
67+
t.Fatalf("other state kept: %s", dir)
68+
}
69+
}
70+
if err := RemoveSessionState(t.TempDir(), t.TempDir(), "keep"); err != nil {
71+
t.Fatalf("empty roots: %v", err)
72+
}
73+
}

‎apps/daemon/internal/cli/connect_bootstrap.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ func bootstrapProfile(path string) (*auth.Profile, bool, error) {
1919
if err != nil {
2020
return nil, false, err
2121
}
22-
if err = localworkspace.Bind(input.EnvironmentID, input.SessionID, input.Workspace, localworkspace.CapabilityDirectory); err != nil {
22+
if err = localworkspace.Bind(input.EnvironmentID, input.Workspace, localworkspace.CapabilityDirectory); err != nil {
2323
return nil, false, errors.New("connect: Runtime workspace binding unavailable")
2424
}
2525
return &auth.Profile{ServerURL: input.CoreURL, RuntimeID: input.DeviceID, RunnerCredential: input.Credential}, input.SuspendControl, nil

‎apps/daemon/internal/cli/connect_environment_binding.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,10 @@ func bindEnvironmentRuntime(remote string, bound machineapi.Enrollment, workspac
6262
if bound.WorkspaceDirectory != runtimebootstrap.PublicWorkspace && bound.WorkspaceDirectory != workspace {
6363
return errors.New("connect: enrollment does not match the Runtime workspace")
6464
}
65-
if err := localworkspace.Bind(bound.EnvironmentID, bound.SessionID, workspace, capabilityDirectory); err != nil {
65+
if err := localworkspace.Bind(bound.EnvironmentID, workspace, capabilityDirectory); err != nil {
6666
return errors.New("connect: local Runtime layout unavailable")
6767
}
68+
bound.SessionID = "" // The Runtime binds to its Environment; the receipt's Session is not part of it.
6869
return saveEnvironmentBinding(root, environmentBinding{RemoteURL: remote, Enrollment: bound, LocalWorkspace: workspace, CapabilityDirectory: capabilityDirectory})
6970
}
7071

‎apps/daemon/internal/cli/connect_environment_binding_test.go‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,14 @@ func TestBindEnvironmentRuntimeUsesCanonicalOperatorWorkspace(t *testing.T) {
4444
t.Fatal(err)
4545
}
4646
var receipt environmentBinding
47-
if decodeEnvironmentJSON(raw, &receipt) != nil || receipt.LocalWorkspace != workspace || receipt.Enrollment != bound {
47+
want := bound
48+
want.SessionID = ""
49+
if decodeEnvironmentJSON(raw, &receipt) != nil || receipt.LocalWorkspace != workspace || receipt.Enrollment != want {
4850
t.Fatal("workspace identity changed", receipt)
4951
}
52+
bound.SessionID = uuid.NewString()
5053
if err := bindEnvironmentRuntime(receipt.RemoteURL, bound, workspace, localworkspace.CapabilityDirectory); err != nil {
51-
t.Fatal("same binding refused", err)
54+
t.Fatal("same Environment refused for another Session", err)
5255
}
5356
replacement := filepath.Join(filepath.Dir(workspace), "replacement")
5457
if err := os.Mkdir(replacement, 0700); err != nil {

‎apps/daemon/internal/cli/connect_suspend_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ func TestQuiesceRetainsExecutorAcrossReconnectAndShutdownConfirmsCleanup(t *test
342342
environment, session := uuid.NewString(), uuid.NewString()
343343
t.Setenv("OAC_RUNTIME_HOME", t.TempDir())
344344
t.Setenv("OAC_RUNTIME_STATE_DIRECTORY", t.TempDir())
345-
if err := localworkspace.Bind(environment, session, t.TempDir(), t.TempDir()); err != nil {
345+
if err := localworkspace.Bind(environment, t.TempDir(), t.TempDir()); err != nil {
346346
t.Fatal(err)
347347
}
348348
t.Cleanup(localworkspace.Unbind)

‎apps/daemon/internal/cli/suspend_control_linux_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ func TestResumeControlRejectsStaleIdentityAndDiscardsPreParkSignals(t *testing.T
2222
}
2323
path := filepath.Join(dir, "control.json")
2424
environment := uuid.NewString()
25-
if err := localworkspace.Bind(environment, uuid.NewString(), t.TempDir(), t.TempDir()); err != nil {
25+
if err := localworkspace.Bind(environment, t.TempDir(), t.TempDir()); err != nil {
2626
t.Fatal(err)
2727
}
2828
t.Cleanup(localworkspace.Unbind)

‎apps/daemon/internal/dispatch/executor.go‎

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,18 @@ func (r *Router) handleExecutorPrepare(ctx context.Context, env proto.Envelope,
101101
return r.rejectPreparation(env, "preparation_capacity")
102102
}
103103
active := 0
104+
// A Runtime bound to an Environment serves one Session at a time; the new
105+
// executor closes the other Sessions' idle executors before it prepares.
106+
var others []*executorState
104107
for _, candidate := range r.executors {
105-
if candidate.sessionID != input.SessionID && candidate.stateKey == req.AgentStateKey {
108+
switch {
109+
case candidate.sessionID == input.SessionID:
110+
case r.localWorkspace != nil && (candidate.preparing || candidate.admission != nil || candidate.run != nil):
111+
r.mu.Unlock()
112+
return r.rejectPreparation(env, "resource_unavailable")
113+
case r.localWorkspace != nil:
114+
others = append(others, candidate)
115+
case candidate.stateKey == req.AgentStateKey:
106116
r.mu.Unlock()
107117
return r.rejectPreparation(env, "session_binding_conflict")
108118
}
@@ -169,12 +179,15 @@ func (r *Router) handleExecutorPrepare(ctx context.Context, env proto.Envelope,
169179
if reused {
170180
r.publishPreparation(p, status)
171181
} else {
172-
go r.prepareExecutor(p, req, factory)
182+
go r.prepareExecutor(p, req, factory, others)
173183
}
174184
return nil
175185
}
176186

177-
func (r *Router) prepareExecutor(p *preparationState, req proto.PromptRequestPayload, factory agent.ExecutorFactory) {
187+
// prepareExecutor confirms the close of the other Sessions' executors and
188+
// removes their native state, which also covers state left by expired
189+
// executors and earlier processes, before it prepares the new executor.
190+
func (r *Router) prepareExecutor(p *preparationState, req proto.PromptRequestPayload, factory agent.ExecutorFactory, others []*executorState) {
178191
defer r.shutdownWG.Done()
179192
owner := p.executor
180193
started := time.Now()
@@ -184,15 +197,21 @@ func (r *Router) prepareExecutor(p *preparationState, req proto.PromptRequestPay
184197
if !r.sendPreparation(p.requestID, p.trace, initial) {
185198
r.abandonExecutorAdmission(p, "failed", "status_delivery_failed", false)
186199
}
187-
var native agent.Executor
188-
var err error
189-
if owner.ctx.Err() == nil {
190-
req, err = r.localWorkspace.Prepare(owner.ctx, req)
191-
if err == nil && owner.ctx.Err() == nil {
192-
native, err = factory(owner.ctx, req)
200+
err := owner.ctx.Err()
201+
for _, other := range others {
202+
if err == nil {
203+
err = r.closeExecutor(other)
193204
}
194-
} else {
195-
err = owner.ctx.Err()
205+
}
206+
if err == nil {
207+
err = r.localWorkspace.RemoveOtherSessionState(req.AgentStateKey)
208+
}
209+
if err == nil {
210+
req, err = r.localWorkspace.Prepare(owner.ctx, req)
211+
}
212+
var native agent.Executor
213+
if err == nil && owner.ctx.Err() == nil {
214+
native, err = factory(owner.ctx, req)
196215
}
197216
r.mu.Lock()
198217
owner.native, owner.preparing = native, false

0 commit comments

Comments
 (0)