refactor(orchestrator): collapse env-reuse helpers into reuseExistingEnvironment

The two env-reuse helpers (`applyExistingEnvironment` and
`applyExistingEnvironmentRuntimeMetadata`) were always called together
and shared the same intent: carry the previous TaskEnvironment forward
into the launch request. Merge them into a single
`reuseExistingEnvironment(ctx, req, env)` so the executor-type gate
runs once for both env-level fields and runtime metadata, and callers
have a single entry point.

Document the layered metadata rule (running wins for container_id;
env wins for sprite_name and other stable IDs) inline so the next
reader doesn't have to reverse-engineer it from two functions.
This commit is contained in:
José Almeida
2026-05-07 00:39:51 +01:00
parent e4096c17f3
commit 470c545bf9
3 changed files with 51 additions and 55 deletions
@@ -20,11 +20,11 @@ func newEnvTestExecutor(t *testing.T) *Executor {
return &Executor{logger: log}
}
func TestApplyExistingEnvironment_NilEnv(t *testing.T) {
func TestReuseExistingEnvironment_NilEnv(t *testing.T) {
e := newEnvTestExecutor(t)
req := &LaunchAgentRequest{TaskID: "task-1"}
e.applyExistingEnvironment(req, nil)
e.reuseExistingEnvironment(context.Background(), req, nil)
if req.Metadata != nil {
t.Error("expected nil metadata for nil env")
@@ -34,21 +34,21 @@ func TestApplyExistingEnvironment_NilEnv(t *testing.T) {
}
}
func TestApplyExistingEnvironment_WorktreeReuse(t *testing.T) {
func TestReuseExistingEnvironment_WorktreeReuse(t *testing.T) {
e := newEnvTestExecutor(t)
req := &LaunchAgentRequest{TaskID: "task-1", UseWorktree: true}
env := &models.TaskEnvironment{
WorktreeID: "wt-1",
}
e.applyExistingEnvironment(req, env)
e.reuseExistingEnvironment(context.Background(), req, env)
if req.WorktreeID != "wt-1" {
t.Errorf("expected WorktreeID=wt-1, got %s", req.WorktreeID)
}
}
func TestApplyExistingEnvironment_SkipsReuseOnExecutorTypeMismatch(t *testing.T) {
func TestReuseExistingEnvironment_SkipsReuseOnExecutorTypeMismatch(t *testing.T) {
// Switching the task's executor profile to a different type must invalidate
// reuse: stale PreviousExecutionID/ContainerID/sprite_name from the old
// backend would otherwise leak into the new launch and overwrite the
@@ -65,7 +65,7 @@ func TestApplyExistingEnvironment_SkipsReuseOnExecutorTypeMismatch(t *testing.T)
WorktreeID: "wt-1",
}
e.applyExistingEnvironment(req, env)
e.reuseExistingEnvironment(context.Background(), req, env)
if req.WorktreeID != "" {
t.Errorf("expected WorktreeID to be empty on executor mismatch, got %q", req.WorktreeID)
@@ -78,28 +78,28 @@ func TestApplyExistingEnvironment_SkipsReuseOnExecutorTypeMismatch(t *testing.T)
}
}
func TestApplyExistingEnvironment_WorktreeSkippedWhenNotRequested(t *testing.T) {
func TestReuseExistingEnvironment_WorktreeSkippedWhenNotRequested(t *testing.T) {
e := newEnvTestExecutor(t)
req := &LaunchAgentRequest{TaskID: "task-1", UseWorktree: false}
env := &models.TaskEnvironment{
WorktreeID: "wt-1",
}
e.applyExistingEnvironment(req, env)
e.reuseExistingEnvironment(context.Background(), req, env)
if req.WorktreeID != "" {
t.Errorf("expected empty WorktreeID when UseWorktree=false, got %s", req.WorktreeID)
}
}
func TestApplyExistingEnvironment_ContainerReuse(t *testing.T) {
func TestReuseExistingEnvironment_ContainerReuse(t *testing.T) {
e := newEnvTestExecutor(t)
req := &LaunchAgentRequest{TaskID: "task-1"}
env := &models.TaskEnvironment{
ContainerID: "container-abc",
}
e.applyExistingEnvironment(req, env)
e.reuseExistingEnvironment(context.Background(), req, env)
if req.PreviousExecutionID != "" {
t.Errorf("expected empty PreviousExecutionID, got %s", req.PreviousExecutionID)
@@ -109,7 +109,7 @@ func TestApplyExistingEnvironment_ContainerReuse(t *testing.T) {
}
}
func TestApplyExistingEnvironment_DockerBranchReuse(t *testing.T) {
func TestReuseExistingEnvironment_DockerBranchReuse(t *testing.T) {
e := newEnvTestExecutor(t)
req := &LaunchAgentRequest{TaskID: "task-1", ExecutorType: "local_docker"}
env := &models.TaskEnvironment{
@@ -118,14 +118,14 @@ func TestApplyExistingEnvironment_DockerBranchReuse(t *testing.T) {
WorktreeBranch: "feature/existing-task-abc",
}
e.applyExistingEnvironment(req, env)
e.reuseExistingEnvironment(context.Background(), req, env)
if req.Metadata[lifecycle.MetadataKeyWorktreeBranch] != "feature/existing-task-abc" {
t.Fatalf("metadata worktree_branch = %v, want existing branch", req.Metadata[lifecycle.MetadataKeyWorktreeBranch])
}
}
func TestApplyExistingEnvironmentRuntimeMetadata_CarriesPersistentSecrets(t *testing.T) {
func TestReuseExistingEnvironment_RuntimeMetadata_CarriesPersistentSecrets(t *testing.T) {
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
if err != nil {
t.Fatalf("failed to create logger: %v", err)
@@ -152,7 +152,7 @@ func TestApplyExistingEnvironmentRuntimeMetadata_CarriesPersistentSecrets(t *tes
e := &Executor{logger: log, repo: repo}
req := &LaunchAgentRequest{TaskID: "task-1"}
e.applyExistingEnvironmentRuntimeMetadata(context.Background(), req, &models.TaskEnvironment{
e.reuseExistingEnvironment(context.Background(), req, &models.TaskEnvironment{
ID: "env-1",
})
@@ -173,7 +173,7 @@ func TestApplyExistingEnvironmentRuntimeMetadata_CarriesPersistentSecrets(t *tes
}
}
func TestApplyExistingEnvironmentRuntimeMetadata_FallsBackToMatchingContainer(t *testing.T) {
func TestReuseExistingEnvironment_RuntimeMetadata_FallsBackToMatchingContainer(t *testing.T) {
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
if err != nil {
t.Fatalf("failed to create logger: %v", err)
@@ -198,7 +198,7 @@ func TestApplyExistingEnvironmentRuntimeMetadata_FallsBackToMatchingContainer(t
e := &Executor{logger: log, repo: repo}
req := &LaunchAgentRequest{TaskID: "task-1"}
e.applyExistingEnvironmentRuntimeMetadata(context.Background(), req, &models.TaskEnvironment{
e.reuseExistingEnvironment(context.Background(), req, &models.TaskEnvironment{
ID: "env-1",
ContainerID: "container-old",
})
@@ -294,14 +294,14 @@ func TestBuildResumeRequest_ReusesTaskEnvironmentRuntimeMetadata(t *testing.T) {
}
}
func TestApplyExistingEnvironment_SandboxReuse(t *testing.T) {
func TestReuseExistingEnvironment_SandboxReuse(t *testing.T) {
e := newEnvTestExecutor(t)
req := &LaunchAgentRequest{TaskID: "task-1"}
env := &models.TaskEnvironment{
SandboxID: "kandev-sprite-abc",
}
e.applyExistingEnvironment(req, env)
e.reuseExistingEnvironment(context.Background(), req, env)
if req.PreviousExecutionID != "" {
t.Errorf("expected empty PreviousExecutionID, got %s", req.PreviousExecutionID)
@@ -311,7 +311,7 @@ func TestApplyExistingEnvironment_SandboxReuse(t *testing.T) {
}
}
func TestApplyExistingEnvironment_WorktreeAndContainer(t *testing.T) {
func TestReuseExistingEnvironment_WorktreeAndContainer(t *testing.T) {
e := newEnvTestExecutor(t)
req := &LaunchAgentRequest{TaskID: "task-1", UseWorktree: true}
env := &models.TaskEnvironment{
@@ -319,7 +319,7 @@ func TestApplyExistingEnvironment_WorktreeAndContainer(t *testing.T) {
ContainerID: "container-abc",
}
e.applyExistingEnvironment(req, env)
e.reuseExistingEnvironment(context.Background(), req, env)
if req.WorktreeID != "wt-1" {
t.Errorf("expected WorktreeID=wt-1, got %s", req.WorktreeID)
@@ -332,12 +332,12 @@ func TestApplyExistingEnvironment_WorktreeAndContainer(t *testing.T) {
}
}
func TestApplyExistingEnvironment_EmptyEnvFieldsDoNothing(t *testing.T) {
func TestReuseExistingEnvironment_EmptyEnvFieldsDoNothing(t *testing.T) {
e := newEnvTestExecutor(t)
req := &LaunchAgentRequest{TaskID: "task-1"}
env := &models.TaskEnvironment{}
e.applyExistingEnvironment(req, env)
e.reuseExistingEnvironment(context.Background(), req, env)
if req.Metadata != nil {
t.Error("expected nil metadata when no container/sandbox IDs")
@@ -452,8 +452,7 @@ func (e *Executor) LaunchPreparedSession(ctx context.Context, task *v1.Task, ses
}
// Check for an existing task environment to reuse worktree, container, or sandbox
e.applyExistingEnvironment(req, existingEnv)
e.applyExistingEnvironmentRuntimeMetadata(ctx, req, existingEnv)
e.reuseExistingEnvironment(ctx, req, existingEnv)
e.logger.Info("launching agent for prepared session",
zap.String("task_id", task.ID),
@@ -1084,16 +1083,25 @@ func (e *Executor) persistTaskEnvironmentRepos(ctx context.Context, envID string
}
}
// applyExistingEnvironment propagates worktree, container, and sandbox IDs from
// an existing TaskEnvironment into the launch request so that executor backends
// can reuse the existing execution environment.
// reuseExistingEnvironment carries forward worktree, container, sandbox, and
// runtime metadata from an existing TaskEnvironment into the launch request
// so that executor backends can reuse the prior execution.
//
// Reuse is gated on the env's executor_type matching the launch request: if
// the user switched the task's executor profile to a different type, we must
// NOT pass stale `PreviousExecutionID`/container_id/sprite_name to the wrong
// backend (it would either fail loudly or, worse, overwrite the persisted env
// with mixed resource IDs on the next save).
func (e *Executor) applyExistingEnvironment(req *LaunchAgentRequest, env *models.TaskEnvironment) {
// NOT pass stale PreviousExecutionID / container_id / sprite_name to the
// wrong backend (it would either fail loudly or, worse, overwrite the
// persisted env with mixed resource IDs on the next save).
//
// Two layers of metadata feed in:
// - env-level (stable IDs: worktree id, container id, sandbox id, branch)
// - the latest matching ExecutorRunning row (live runtime metadata: agent
// execution id, secret references, anything in persistentMetadataKeys)
//
// applyExecutorRunningMetadata overwrites container_id with running.ContainerID
// (running wins for live runtime values) but only adds keys that don't already
// exist for the rest (env wins for sprite_name and other stable IDs).
func (e *Executor) reuseExistingEnvironment(ctx context.Context, req *LaunchAgentRequest, env *models.TaskEnvironment) {
if env == nil {
return
}
@@ -1105,7 +1113,6 @@ func (e *Executor) applyExistingEnvironment(req *LaunchAgentRequest, env *models
return
}
// Worktree reuse
if env.WorktreeID != "" && req.UseWorktree {
req.WorktreeID = env.WorktreeID
e.logger.Info("reusing existing task environment worktree",
@@ -1113,40 +1120,30 @@ func (e *Executor) applyExistingEnvironment(req *LaunchAgentRequest, env *models
zap.String("worktree_id", env.WorktreeID))
}
// Container/sandbox reuse
if env.ContainerID != "" || env.SandboxID != "" {
if req.Metadata == nil {
req.Metadata = make(map[string]interface{})
}
metadata := ensureLaunchMetadata(req)
if env.ContainerID != "" {
req.Metadata[lifecycle.MetadataKeyContainerID] = env.ContainerID
metadata[lifecycle.MetadataKeyContainerID] = env.ContainerID
}
if env.SandboxID != "" {
// Sprites executor reads "sprite_name" from metadata for reconnection
req.Metadata["sprite_name"] = env.SandboxID
metadata["sprite_name"] = env.SandboxID
}
}
// Forward the persisted feature branch so the in-sandbox prepare script can
// re-create or reuse it. Applies to every clone-based remote executor (the
// preparer is responsible for stamping env.WorktreeBranch in the first
// place); the host-side worktree path uses req.WorktreeID instead and
// doesn't need this metadata.
// Forward the persisted feature branch so the in-sandbox prepare script
// can re-create or reuse it. Applies to every clone-based remote executor
// (the preparer is responsible for stamping env.WorktreeBranch in the
// first place); the host-side worktree path uses req.WorktreeID instead.
if env.WorktreeBranch != "" && isContainerizedExecutor(req.ExecutorType) {
metadata := ensureLaunchMetadata(req)
metadata[lifecycle.MetadataKeyWorktreeBranch] = env.WorktreeBranch
ensureLaunchMetadata(req)[lifecycle.MetadataKeyWorktreeBranch] = env.WorktreeBranch
}
}
func (e *Executor) applyExistingEnvironmentRuntimeMetadata(ctx context.Context, req *LaunchAgentRequest, env *models.TaskEnvironment) {
if env == nil || env.ID == "" {
if env.ID == "" {
return
}
running := e.latestExecutorRunningForEnvironment(ctx, req.TaskID, env)
if running == nil {
return
if running := e.latestExecutorRunningForEnvironment(ctx, req.TaskID, env); running != nil {
applyExecutorRunningMetadata(req, running)
}
applyExecutorRunningMetadata(req, running)
}
func (e *Executor) latestExecutorRunningForEnvironment(ctx context.Context, taskID string, env *models.TaskEnvironment) *models.ExecutorRunning {
@@ -487,8 +487,7 @@ func (e *Executor) buildResumeRequest(ctx context.Context, task *v1.Task, sessio
return nil, "", execConfig, nil, err
}
e.applyExistingEnvironment(req, existingEnv)
e.applyExistingEnvironmentRuntimeMetadata(ctx, req, existingEnv)
e.reuseExistingEnvironment(ctx, req, existingEnv)
// Activate config-mode MCP tools when config_mode is set in session metadata.
if isConfigModeSession(session) {