Files
pipelines/internal/server/execution_safety_test.go
T
alan f061675fc1 Claude stages survive server restarts; non-repo folders don't falsely overlap; busy scheduled runs wait
- Claude stage CLIs now run in their own session (setsid) with the prompt from
  a file and stream-json written straight to cli-<n>.out in the evidence
  directory; owner.json records pid/pgid, session, invocation and output. A
  server shutdown leaves the CLI running and owned (ErrDetached). Start-up
  recovery re-adopts it (stage.ClaudeStageReattachable): the next process
  re-reads the output, follows the live CLI until it exits, or reads the
  result it left while the server was down; one that ended without a result
  marks the run interrupted with a clear reason. The outcome repair follow-up
  is re-adopted too (or asked again if its CLI died without a reply).
- Workspace overlap: two folders outside any repository overlap only when
  they are the same folder or the inner one lies within the outer run's
  declared write paths; nested-repository rules are unchanged.
- Scheduled admissions refused for a busy workspace are recorded as
  "delayed" and retried every 5 min for up to 2 h (env-configurable), then
  started or skipped with the reason; the operator gets a low-priority app
  notice (and ntfy when enabled) when a scheduled run is delayed or skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 12:55:12 +00:00

252 lines
9.7 KiB
Go

package server
import (
"context"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func TestCancelWaitsForContextIgnoringExecutor(t *testing.T) {
ctx, r, pipelineID := concurrentStore(t)
entered, release := make(chan struct{}, 1), make(chan struct{})
var releaseOnce sync.Once
stopExecutor := func() { releaseOnce.Do(func() { close(release) }) }
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
entered <- struct{}{}
<-release // Deliberately ignore the canceled context.
return stage.Result{Outcome: "success", Output: stage.Values{}}, nil
}
defer func() { stopExecutor(); r.wg.Wait() }()
workspace := t.TempDir()
request := protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "blocking", Workspace: workspace, Input: map[string]any{"prompt": "task"}}
run, err := r.start(request)
if err != nil {
t.Fatal(err)
}
waitEntered(t, entered)
if err := r.cancel(run.ID); err != nil {
t.Fatal(err)
}
if err := r.cancel(run.ID); err != nil {
t.Fatal("repeated stop must be idempotent", err)
}
detail, err := r.getRun(run.ID)
if err != nil || detail.Status != "running" || !detail.Executing || !detail.CancelRequested || detail.FinishedAt != "" || detail.Steps[0].Status != "running" || detail.Steps[0].FinishedAt != "" {
t.Fatalf("stop request falsely settled execution: %+v %v", detail, err)
}
request.RequestKey = "conflict"
if _, err := r.start(request); err == nil {
t.Fatal("stopping workspace was released")
}
// An actual second server must fail before recovery can touch this live row.
other, err := pipeline.Open(filepath.Join(r.store.Directory(), "test.db"))
if err != nil {
t.Fatal(err)
}
defer other.Close()
if _, err := newRunner(ctx, other); err == nil || !strings.Contains(err.Error(), "another server owns") {
t.Fatalf("second server did not fail before recovery: %v", err)
}
detail, _ = r.store.GetRun(ctx, run.ID)
if detail.Status != "running" || detail.Steps[0].Status != "running" {
t.Fatal("second server recovered live execution", detail)
}
stopExecutor()
r.wg.Wait()
detail, err = r.store.GetRun(ctx, run.ID)
if err != nil || detail.Status != "canceled" || detail.Outcome != "" || detail.FinishedAt == "" || detail.Steps[0].Status != "canceled" {
t.Fatalf("late success beat stop: %+v %v", detail, err)
}
r.mu.Lock()
err = r.checkWorkspaceFree(workspace)
r.mu.Unlock()
if err != nil {
t.Fatal("confirmed stop did not release workspace", err)
}
}
func TestCleanupUnconfirmedReservesWorkspaceAcrossRecovery(t *testing.T) {
ctx := context.Background()
r, store, pipelineID := submitRunner(t, ctx, pipeline.Template([]string{"one"}, true))
path := filepath.Join(store.Directory(), "test.db")
defer func() { store.Close() }()
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{}, stage.ErrStageCleanup
}
workspace := t.TempDir()
request := protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "cleanup", Workspace: workspace, Input: map[string]any{"prompt": "task"}}
run, err := r.start(request)
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if err := r.cancel(run.ID); err != nil {
t.Fatal(err)
}
detail, err := r.getRun(run.ID)
if err != nil || detail.Status != "running" || !detail.CleanupUnconfirmed || detail.FinishedAt != "" || !detail.Executing {
t.Fatalf("cleanup failure became terminal: %+v %v", detail, err)
}
request.RequestKey = "blocked"
if _, err := r.start(request); err == nil {
t.Fatal("unconfirmed cleanup released workspace")
}
if err := store.Close(); err != nil {
t.Fatal(err)
}
store, err = pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
recovered, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
// No recoverable session pointer exists in this fixture: fail closed rather
// than claiming a restart proved an external process stopped.
if _, err := recovered.start(request); err == nil {
t.Fatal("restart released unconfirmed workspace without stop evidence")
}
detail, _ = recovered.getRun(run.ID)
if !detail.CleanupUnconfirmed || detail.Status != "running" || detail.FinishedAt != "" {
t.Fatal("recovery invented stop confirmation", detail)
}
}
func TestWorkspaceOverlapIncludesParentsDescendantsAndSymlinks(t *testing.T) {
_, r, pipelineID := concurrentStore(t)
// One repository: its folder and a folder inside it are one shared tree.
workspace := t.TempDir()
child := filepath.Join(workspace, "child")
for _, dir := range []string{filepath.Join(workspace, ".git"), child} {
if err := os.Mkdir(dir, 0700); err != nil {
t.Fatal(err)
}
}
alias := filepath.Join(t.TempDir(), "alias")
if err := os.Symlink(child, alias); err != nil {
t.Fatal(err)
}
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{}, nil
}
// Admission resolves aliases; the overlap check must cover both directions.
for _, pair := range [][2]string{{workspace, child}, {child, workspace}, {workspace, alias}} {
r.mu.Lock()
resolved, _ := filepath.EvalSymlinks(pair[0])
r.active[99] = activeRun{cancel: func() {}, workspace: resolved}
r.mu.Unlock()
_, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "overlap", Workspace: pair[1], Input: map[string]any{"prompt": "task"}})
if err == nil || !strings.Contains(err.Error(), "already active") {
t.Fatal("overlapping workspace admission", pair, err)
}
}
for _, pair := range [][2]string{{"/repo", "/repo-other"}, {"/repo/a", "/repo/b"}} {
if workspacesOverlap(pair[0], pair[1]) {
t.Fatal("sibling/prefix falsely overlaps", pair)
}
}
}
// A hub folder holding separate repositories (the operator's ~/caplens with
// clones under repos/) must not block, nor be blocked by, a run inside one of
// those repositories; the same repository still overlaps itself.
func TestWorkspaceOverlapSeparatesNestedRepositories(t *testing.T) {
hub := t.TempDir()
repo := filepath.Join(hub, "repos", "fix-d")
inner := filepath.Join(repo, "src")
nested := filepath.Join(repo, "vendor", "lib")
for _, dir := range []string{filepath.Join(repo, ".git"), inner, filepath.Join(nested, ".git")} {
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
}
for _, pair := range [][2]string{{hub, repo}, {repo, hub}, {hub, inner}, {repo, nested}} {
if workspacesOverlap(pair[0], pair[1]) {
t.Fatal("separate repositories falsely overlap", pair)
}
}
for _, pair := range [][2]string{{repo, repo}, {repo, inner}, {inner, repo}} {
if !workspacesOverlap(pair[0], pair[1]) {
t.Fatal("one repository does not overlap itself", pair)
}
}
}
// Two folders outside any repository (the operator's ~/caplens and a sibling
// project folder under it) are not one tree merely because neither is in a
// repository: nested, they overlap only where the outer run's declared write
// paths reach the inner folder. The same folder always overlaps.
func TestWorkspaceOverlapNonRepositoryFolders(t *testing.T) {
hub := t.TempDir()
brief := filepath.Join(hub, "brief")
notes := filepath.Join(hub, "notes", "deep")
for _, dir := range []string{brief, notes} {
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
}
paths := func(p ...string) func() []string { return func() []string { return p } }
for _, test := range []struct {
a, b string
aPaths, bPaths func() []string
want bool
}{
{hub, hub, nil, nil, true},
{brief, brief, nil, nil, true},
{hub, brief, nil, nil, false},
{brief, hub, nil, nil, false},
{brief, notes, nil, nil, false},
{hub, brief, paths("notes"), nil, false},
{hub, brief, paths("brief"), nil, true},
{hub, notes, paths("notes"), nil, true},
{hub, notes, paths("notes/deep/file.md"), nil, true},
{notes, hub, nil, paths("notes"), true},
{notes, hub, paths("notes"), nil, false}, // The inner run's paths do not reach out.
{hub, brief, paths("."), nil, true},
} {
if got := workspaceScopesOverlap(test.a, test.b, test.aPaths, test.bPaths); got != test.want {
t.Errorf("overlap(%s, %s) = %v, want %v", test.a, test.b, got, test.want)
}
}
// Nested repository rules stay: a repository inside a plain folder is its
// own tree whatever the folder's write paths.
repo := filepath.Join(hub, "repo")
if err := os.MkdirAll(filepath.Join(repo, ".git"), 0700); err != nil {
t.Fatal(err)
}
if workspaceScopesOverlap(hub, repo, paths("repo"), nil) {
t.Fatal("a repository inside a plain folder overlaps it")
}
// End to end: a scheduled brief in the hub is admitted while a run works in
// a sibling folder below it, and refused only when it declares a write
// path reaching that folder.
_, r, pipelineID := concurrentStore(t)
release := make(chan struct{})
defer close(release)
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
select {
case <-release:
case <-ctx.Done():
}
return stage.Result{Outcome: "success"}, nil
}
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "notes", Workspace: notes, Input: map[string]any{"prompt": "task"}}); err != nil {
t.Fatal(err)
}
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief-scoped", Workspace: hub, WritePaths: []string{"notes"}, Input: map[string]any{"prompt": "task"}}); err == nil || !strings.Contains(err.Error(), "already active") {
t.Fatal("a hub run writing into the active folder was admitted:", err)
}
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief", Workspace: hub, Input: map[string]any{"prompt": "task"}}); err != nil {
t.Fatal("a hub run was refused for a sibling folder's run:", err)
}
}