Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8233: fix Pi cancellation and guard unconfirmed cleanup (#9557)

Multica Evebcf40040e0e3
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 8ee67b35c8..a5a093dca1 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -258,6 +258,12 @@ For the internal context that the daemon injects into agent tasks, see [Task run
Precedence is command-line flag → environment variable → `~/.multica/config.json` → built-in default. For watchdog behavior, see [Daemon and runtimes](/daemon-runtimes).
+On Linux and macOS, Pi and omp cancellation gives the runtime two seconds to stop its tools before forced termination, with a ten-second cleanup budget. The daemon also retains identities of observed descendant processes, including detached tools. Windows uses the existing owned Job Object cleanup. The daemon releases output pipes and publishes the result after cleanup. Identity checks require Linux pidfds (kernel 5.3 or newer) or supported macOS kernel identity signalling. A failed final cleanup check or a surviving process produces `cleanup_unconfirmed`. Normal completion releases pipes and tracking handles without terminating background services on Linux and macOS; interruption, watchdog expiry, provider-error grace expiry, and a runtime exit with an unfinished tool use the joined cleanup path. Transient observation errors are logged and rechecked during cleanup.
+
+An unconfirmed cleanup blocks automatic retries and subsequent starts for the same agent on that runtime. Check for remaining background processes, then explicitly rerun the task; successful completion of that manual run releases the block. For tasks that negotiated `pi-process-cleanup-v1` when starting, the server waits for an explicit cleanup acknowledgement during user cancellation; a missing acknowledgement remains unconfirmed after 30 seconds. Older daemons do not negotiate this capability and retain their existing cancellation behavior without acquiring this new acknowledgement block. A newer daemon still performs local cleanup against an older server, which cannot enforce the continuation block. No coordinated rollout is required; other runtimes keep their existing cancellation behavior. No new environment variable is required, and watchdog thresholds retain their existing meaning.
+
+Descendant discovery is best effort: a process that forks and reparents between observations can escape discovery. It is not operating-system containment such as a Linux cgroup.
+
### Cleanup and retention [#gc]
The daemon periodically cleans up run directories, repository caches, session records, and temporary directories; what is removed when is described in [Cleanup and retention](/daemon-runtimes#cleanup). Durations accept Go duration syntax plus `d` for days (for example `14d` or `1d12h`).
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 2149d6c5f6..27f91651aa 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -140,6 +140,7 @@ var pgBigmOperatorClass = extensionOperatorClass{
// they are still pending: a fresh self-hosted install, which is exactly where an
// interrupted build would otherwise leave a permanently unusable index.
var concurrentIndexCleanups = map[string]string{
+ "594_agent_task_process_cleanup_index": "idx_agent_task_queue_process_cleanup",
"563_search_index_change_changed_at_index": "idx_search_index_change_changed_at",
"562_search_index_change_workspace_index": "idx_search_index_change_workspace_xid",
"552_agent_task_history_page_index": "idx_agent_task_queue_history_page",
diff --git a/server/cmd/migrate/migrate_task_process_cleanup_index_test.go b/server/cmd/migrate/migrate_task_process_cleanup_index_test.go
new file mode 100644
index 0000000000..ce6e546e2b
--- /dev/null
+++ b/server/cmd/migrate/migrate_task_process_cleanup_index_test.go
@@ -0,0 +1,130 @@
+package main
+
+import (
+ "context"
+ "math/rand/v2"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestTaskProcessCleanupIndexMigrationAndPlans(t *testing.T) {
+ adminPool := openTestPool(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+ schema := createScratchSchema(t, ctx, adminPool, "migrate_task_cleanup_")
+ pool := openTestPoolWithSearchPath(t, schema)
+ for _, statement := range []string{
+ `CREATE TABLE agent_task_queue (
+ id UUID PRIMARY KEY, agent_id UUID NOT NULL, runtime_id UUID NOT NULL,
+ status TEXT NOT NULL, failure_reason TEXT, result JSONB,
+ created_at TIMESTAMPTZ NOT NULL, completed_at TIMESTAMPTZ,
+ rerun_of_task_id UUID, retry_of_task_id UUID
+ )`,
+ `CREATE INDEX idx_agent_task_queue_agent ON agent_task_queue (agent_id, status)`,
+ `INSERT INTO agent_task_queue (id, agent_id, runtime_id, status, created_at, completed_at)
+ SELECT md5('history-' || n)::uuid, md5('agent')::uuid, md5('runtime')::uuid,
+ 'completed', now() - interval '1 day', now() - interval '1 day'
+ FROM generate_series(1, 30000) AS n`,
+ `INSERT INTO agent_task_queue (id, agent_id, runtime_id, status, created_at)
+ VALUES (md5('candidate')::uuid, md5('agent')::uuid, md5('runtime')::uuid, 'dispatched', now()),
+ (md5('unsafe')::uuid, md5('agent')::uuid, md5('runtime')::uuid, 'completed', now())`,
+ `ANALYZE agent_task_queue`,
+ } {
+ if _, err := pool.Exec(ctx, statement); err != nil {
+ t.Fatalf("fixture: %v", err)
+ }
+ }
+ // Exercise the real guard predicates: a failure-only partial index misses
+ // the pending-ack branch of the OR and leaves ordinary history scans intact.
+ source, err := os.ReadFile(filepath.Join("..", "..", "pkg", "db", "queries", "task_cleanup.sql"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ queries := make(map[string]string)
+ for _, name := range []string{"TaskBlockedByProcessCleanup", "TaskWaitingForProcessCleanup"} {
+ _, query, ok := strings.Cut(string(source), "-- name: "+name+" :one\n")
+ if !ok {
+ t.Fatalf("missing query %s", name)
+ }
+ lines := strings.Split(query, "\n")
+ for i, line := range lines {
+ if strings.HasPrefix(strings.TrimSpace(line), "--") {
+ lines[i] = ""
+ }
+ }
+ query = strings.Join(lines, "\n")
+ query, _, ok = strings.Cut(query, ";")
+ if !ok {
+ t.Fatalf("missing query terminator for %s", name)
+ }
+ query = strings.NewReplacer("@task_id", "md5('candidate')::uuid", "@id", "md5('candidate')::uuid").Replace(query)
+ queries[name] = query
+ t.Logf("before index, %s:\n%s", name, explainAnalyze(t, ctx, pool, query))
+ }
+ const version = "594_agent_task_process_cleanup_index"
+ const indexName = "idx_agent_task_queue_process_cleanup"
+ options := runOptions{
+ Direction: "up", Files: realMigrationFiles(t, []string{version}, "up"),
+ SchemaMigrationsTable: schema + ".schema_migrations",
+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,
+ Hooks: hooksForDirection("up"),
+ }
+ if err := runMigrations(ctx, pool, options); err != nil {
+ t.Fatal(err)
+ }
+ assertIndexValidity(t, pool, schema, indexName, true)
+ for _, tc := range []struct {
+ name, status, reason, result, age string
+ blocked, waiting bool
+ }{
+ {name: "ordinary history", status: "completed", result: `{}`, age: "-1 minute"},
+ {name: "cleanup failure", status: "failed", reason: "cleanup_unconfirmed", result: `{}`, age: "-1 minute", blocked: true},
+ {name: "expired acknowledgement", status: "cancelled", result: `{"process_cleanup_pending":true}`, age: "-1 minute", blocked: true},
+ {name: "recent acknowledgement", status: "cancelled", result: `{"process_cleanup_pending":true}`, age: "0 seconds", waiting: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status=$1, failure_reason=$2,
+ result=$3::jsonb, completed_at=now()+$4::interval WHERE id=md5('unsafe')::uuid`, tc.status, tc.reason, tc.result, tc.age); err != nil {
+ t.Fatal(err)
+ }
+ for name, query := range queries {
+ var got bool
+ if err := pool.QueryRow(ctx, query).Scan(&got); err != nil {
+ t.Fatal(err)
+ }
+ want := tc.blocked
+ if name == "TaskWaitingForProcessCleanup" {
+ want = tc.waiting
+ }
+ if got != want {
+ t.Fatalf("%s = %v, want %v", name, got, want)
+ }
+ plan := explainAnalyze(t, ctx, pool, query)
+ if !strings.Contains(plan, indexName) {
+ t.Fatalf("%s must use cleanup index instead of filtering ordinary history:\n%s", name, plan)
+ }
+ t.Logf("%s:\n%s", name, plan)
+ }
+ })
+ }
+ options.Direction = "down"
+ options.Files = realMigrationFiles(t, []string{version}, "down")
+ options.Hooks = hooksForDirection("down")
+ if err := runMigrations(ctx, pool, options); err != nil {
+ t.Fatal(err)
+ }
+ assertIndexExists(t, pool, schema, indexName, false)
+ assertMigrationVersionRecorded(t, ctx, pool, schema, version, false)
+ options.Direction = "up"
+ options.Files = realMigrationFiles(t, []string{version}, "up")
+ options.Hooks = hooksForDirection("up")
+ for range 2 { // Rebuild after rollback, then replay the recorded migration.
+ if err := runMigrations(ctx, pool, options); err != nil {
+ t.Fatal(err)
+ }
+ assertIndexValidity(t, pool, schema, indexName, true)
+ }
+}
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index f3f1dab12b..71a89dfb76 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -541,6 +541,8 @@ func (c *Client) MarkTaskWaitingLocalDirectory(ctx context.Context, taskID, reas
// TaskCancelAck is the payload of the daemon's cancel acknowledgement.
type TaskCancelAck struct {
+ // Nil is an older daemon with no explicit cleanup acknowledgement.
+ ProcessCleanupConfirmed *bool
// BranchName: a cancelled worktree task has already finalized — its
// partial work is committed to a branch in the user's repo. The cancel
// path discards the rest of the result, so this ack is the only channel
@@ -574,6 +576,9 @@ type TaskCancelAck struct {
// The server never overwrites already-recorded values, so replays are safe.
func (c *Client) AckTaskCancelled(ctx context.Context, taskID string, ack TaskCancelAck) error {
body := map[string]any{}
+ if ack.ProcessCleanupConfirmed != nil {
+ body["process_cleanup_confirmed"] = *ack.ProcessCleanupConfirmed
+ }
if ack.BranchName != "" {
body["branch_name"] = ack.BranchName
}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 1e6ffb42aa..e90e08b279 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -5792,6 +5792,10 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
taskLog.Info("discarding rejected start claim", "error", err)
return
}
+ if result.FailureReason == taskfailure.ReasonProcessCleanupUnconfirmed.String() && err != nil {
+ result.Comment += "; " + err.Error()
+ err = nil // Cleanup uncertainty must outrank worktree-finalization errors.
+ }
// Report usage before any early return — the agent accumulates tokens
// whether the task completes, errors, or is cancelled mid-run by the poll
@@ -5822,12 +5826,7 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
// RetiredSessionID rides along too: a resumed session the run never
// got a single message out of must not stay this issue's resume
// pointer (MUL-8188).
- ack := TaskCancelAck{BranchName: result.BranchName, DurableWorkDir: result.DurableWorkDir, RetiredSessionID: result.RetiredSessionID}
- var preserved *worktreePreservedError
- if errors.As(err, &preserved) {
- ack.ErrorMessage = preserved.Error()
- ack.FailureReason = "local_directory_error"
- }
+ ack := taskCancelAcknowledgement(result, err, provider)
if ackErr := d.client.AckTaskCancelled(ctx, task.ID, ack); ackErr != nil {
taskLog.Warn("cancel ack failed; server sweeper will finalize", "error", ackErr)
}
@@ -5878,7 +5877,7 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
// completed/failed rows the complete/fail callback is the
// authoritative channel and a stale run's late ack must not touch
// them.
- if ackErr := d.client.AckTaskCancelled(ctx, task.ID, TaskCancelAck{BranchName: result.BranchName, DurableWorkDir: result.DurableWorkDir, RetiredSessionID: result.RetiredSessionID}); ackErr != nil {
+ if ackErr := d.client.AckTaskCancelled(ctx, task.ID, taskCancelAcknowledgement(result, nil, provider)); ackErr != nil {
taskLog.Warn("cancel ack failed; server sweeper will finalize", "error", ackErr)
}
return
@@ -5952,6 +5951,27 @@ func (e *environmentSetupError) Unwrap() error { return e.err }
// except taskRunFailureReason.
func asEnvironmentSetupFailure(err error) error { return &environmentSetupError{err: err} }
+func taskCancelAcknowledgement(result TaskResult, runErr error, provider string) TaskCancelAck {
+ ack := TaskCancelAck{BranchName: result.BranchName, DurableWorkDir: result.DurableWorkDir, RetiredSessionID: result.RetiredSessionID}
+ var preserved *worktreePreservedError
+ if errors.As(runErr, &preserved) {
+ ack.ErrorMessage = preserved.Error()
+ ack.FailureReason = "local_directory_error"
+ }
+ confirmed := result.FailureReason != taskfailure.ReasonProcessCleanupUnconfirmed.String()
+ if provider == "pi" || provider == "omp" {
+ ack.ProcessCleanupConfirmed = &confirmed
+ }
+ if !confirmed {
+ ack.ErrorMessage = result.Comment
+ if preserved != nil {
+ ack.ErrorMessage += "; " + preserved.Error()
+ }
+ ack.FailureReason = result.FailureReason
+ }
+ return ack
+}
+
func taskRunFailureReason(err error) string {
if errors.Is(err, errInvalidTaskIdentity) {
return taskfailure.ReasonInvalidTaskIdentity.String()
@@ -8380,6 +8400,9 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// in place, leave them behind in the user's tree.
if env.LocalDirectory || env.LocalWorktree != nil {
defer func() {
+ if taskResult.FailureReason == taskfailure.ReasonProcessCleanupUnconfirmed.String() {
+ return // Preserve files that an unconfirmed process may still use.
+ }
var cleanupErr error
if cerr := execenv.CleanupRuntimeConfig(env.WorkDir, provider); cerr != nil {
cleanupErr = cerr
@@ -8447,6 +8470,9 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// "start task failed: <…>" string and the same failure_reason
// taxonomy as before — see MUL-2946 for the classifier contract.
var taskCapabilities []string
+ if provider == "pi" || provider == "omp" {
+ taskCapabilities = append(taskCapabilities, protocol.DaemonCapabilityPiProcessCleanupV1)
+ }
var cursorHookCommand []string
supplementSupported := agent.SupportsTaskSupplement(provider, resolvedVersion) && task.IssueID != ""
if supplementSupported && provider == "cursor" {
@@ -8867,6 +8893,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if err != nil {
return TaskResult{}, err
}
+ if result.Status == "cleanup_unconfirmed" {
+ if env.LocalWorktree != nil {
+ env.LocalWorktree.AbortWithReason(errors.New(result.Error))
+ }
+ }
if shouldRetryWithFreshSession(result, task.PriorSessionID, tools, provider) {
firstResult := result
@@ -9009,6 +9040,12 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
defer func() { taskResult.SessionRolloutMissing = sessionRolloutMissing }()
switch result.Status {
+ case "cleanup_unconfirmed":
+ return TaskResult{
+ Status: "blocked", Comment: result.Error, SessionID: result.SessionID,
+ WorkDir: env.WorkDir, EnvRoot: env.RootDir, Usage: usageEntries,
+ FailureReason: taskfailure.ReasonProcessCleanupUnconfirmed.String(),
+ }, nil
case "completed":
if result.Output == "" {
// The agent completed successfully but produced no text output.
@@ -9929,15 +9966,24 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
return agent.Result{}, false, false
}
}
+ cleanupUnconfirmed := func() (agent.Result, int32, error) {
+ return agent.Result{
+ Status: "cleanup_unconfirmed",
+ Error: "Runtime did not confirm process cleanup; background processes may still be running. Check them before manually rerunning this task.",
+ }, toolCount.Load(), nil
+ }
select {
- case result := <-session.Result:
+ case result, ok := <-session.Result:
stopWatchdog()
waitForDrain()
+ if !ok && session.CleanupRequired {
+ return cleanupUnconfirmed()
+ }
// terminalObserved outranks a watchdog that fired anyway: if the backend
// had already read its authoritative result, this is the real outcome and
// re-tagging it would report a completed run as a hang.
- if idleWatchdogFired.Load() && !terminalObserved() {
+ if idleWatchdogFired.Load() && !terminalObserved() && result.Status != "cleanup_unconfirmed" {
// The backend's wait goroutine (e.g. claude.go) translates the
// SIGKILL we delivered via agentCancel into Status="aborted".
// Re-tag it as "idle_watchdog" so runTask routes the
@@ -9977,6 +10023,9 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
// this is the real outcome, not a hang.
return result, toolCount.Load(), nil
} else if delivered {
+ if result.Status == "cleanup_unconfirmed" {
+ return result, toolCount.Load(), nil
+ }
// The backend's wait goroutine (e.g. claude.go) translates the
// SIGKILL we delivered via agentCancel into Status="aborted".
// Re-tag it so runTask routes the disposition through the
@@ -9987,6 +10036,9 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
}
return result, toolCount.Load(), nil
}
+ if session.CleanupRequired {
+ return cleanupUnconfirmed()
+ }
return agent.Result{
Status: "idle_watchdog",
Error: idleWatchdogReason(time.Duration(idleWatchdogThreshold.Load())),
@@ -9998,14 +10050,23 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
// upstream runCtx fired runCancel(); context.DeadlineExceeded is the
// drain deadline expiring on its own.
if errors.Is(drainCtx.Err(), context.Canceled) {
- if result, _, authoritative := awaitTerminalResult("upstream_context"); authoritative {
+ if result, delivered, authoritative := awaitTerminalResult("upstream_context"); authoritative || (delivered && result.Status == "cleanup_unconfirmed") {
return result, toolCount.Load(), nil
+ } else if session.CleanupRequired && !delivered {
+ return cleanupUnconfirmed()
}
return agent.Result{
Status: "cancelled",
Error: "task cancelled by upstream context (server cancel or daemon shutdown)",
}, toolCount.Load(), nil
}
+ if session.CleanupRequired {
+ agentCancel()
+ if result, delivered, _ := awaitTerminalResult("drain_timeout"); delivered {
+ return result, toolCount.Load(), nil
+ }
+ return cleanupUnconfirmed()
+ }
return agent.Result{
Status: "timeout",
Error: "agent did not produce result within drain timeout",
diff --git a/server/internal/daemon/pi_cleanup_test.go b/server/internal/daemon/pi_cleanup_test.go
new file mode 100644
index 0000000000..90fb91981f
--- /dev/null
+++ b/server/internal/daemon/pi_cleanup_test.go
@@ -0,0 +1,64 @@
+package daemon
+
+import (
+ "context"
+ "log/slog"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
+)
+
+type unconfirmedCleanupBackend struct{ omitResult bool }
+
+func (b unconfirmedCleanupBackend) Execute(ctx context.Context, _ string, _ agent.ExecOptions) (*agent.Session, error) {
+ messages := make(chan agent.Message, 1)
+ results := make(chan agent.Result, 1)
+ messages <- agent.Message{Type: agent.MessageToolUse, Tool: "bash", CallID: "t"}
+ go func() {
+ <-ctx.Done()
+ close(messages)
+ if !b.omitResult {
+ results <- agent.Result{Status: "cleanup_unconfirmed", Error: "Background processes may still be running"}
+ }
+ close(results)
+ }()
+ return &agent.Session{Messages: messages, Result: results, CleanupRequired: true, TerminalObserved: func() bool { return false }}, nil
+}
+
+func TestPiCleanupUnconfirmedOutranksCancellation(t *testing.T) {
+ for _, manual := range []bool{false, true} {
+ for _, omitted := range []bool{false, true} {
+ d := newTestDaemon(t)
+ d.cfg.AgentIdleWatchdog, d.cfg.AgentToolWatchdog = 50*time.Millisecond, 50*time.Millisecond
+ ctx, cancel := context.WithCancel(context.Background())
+ if manual {
+ time.AfterFunc(30*time.Millisecond, cancel)
+ }
+ result, _, err := d.executeAndDrain(ctx, unconfirmedCleanupBackend{omitResult: omitted}, "test", agent.ExecOptions{}, slog.Default(), "cleanup", "", new(atomic.Int32))
+ cancel()
+ if err != nil || result.Status != "cleanup_unconfirmed" {
+ t.Fatalf("manual=%v omitted=%v result=%+v err=%v", manual, omitted, result, err)
+ }
+ if shouldRetryWithFreshSession(result, "existing-session", 0, "pi") {
+ t.Fatal("unconfirmed cleanup allowed an in-turn retry")
+ }
+ }
+ }
+}
+
+func TestPiCleanupCancelAcknowledgement(t *testing.T) {
+ for _, provider := range []string{"pi", "omp"} {
+ failed := TaskResult{Status: "blocked", FailureReason: taskfailure.ReasonProcessCleanupUnconfirmed.String(), Comment: "Unconfirmed background process", BranchName: "work"}
+ ack := taskCancelAcknowledgement(failed, nil, provider)
+ if ack.ProcessCleanupConfirmed == nil || *ack.ProcessCleanupConfirmed || ack.FailureReason != failed.FailureReason || ack.ErrorMessage != failed.Comment || ack.BranchName != "work" {
+ t.Fatalf("cancel acknowledgement lost cleanup failure: %+v", ack)
+ }
+ ack = taskCancelAcknowledgement(TaskResult{Status: "cancelled"}, nil, provider)
+ if ack.ProcessCleanupConfirmed == nil || !*ack.ProcessCleanupConfirmed {
+ t.Fatal("confirmed cleanup was not acknowledged")
+ }
+ }
+}
diff --git a/server/internal/daemon/pi_cleanup_unix_test.go b/server/internal/daemon/pi_cleanup_unix_test.go
new file mode 100644
index 0000000000..22cf2e22a5
--- /dev/null
+++ b/server/internal/daemon/pi_cleanup_unix_test.go
@@ -0,0 +1,99 @@
+//go:build linux || darwin
+
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "sync/atomic"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+type cancelPiAtTool struct {
+ agent.Backend
+ cancel context.CancelFunc
+}
+
+func (b cancelPiAtTool) Execute(ctx context.Context, prompt string, opts agent.ExecOptions) (*agent.Session, error) {
+ s, err := b.Backend.Execute(ctx, prompt, opts)
+ if err != nil || b.cancel == nil {
+ return s, err
+ }
+ input, output := s.Messages, make(chan agent.Message, 16)
+ s.Messages = output
+ go func() {
+ defer close(output)
+ for msg := range input {
+ output <- msg
+ if msg.Type == agent.MessageToolUse {
+ b.cancel()
+ }
+ }
+ }()
+ return s, nil
+}
+
+func TestPiCleanupWatchdogAndManualCancel(t *testing.T) {
+ for _, provider := range []string{"pi", "omp"} {
+ for _, trigger := range []string{"watchdog", "manual"} {
+ t.Run(provider+"/"+trigger, func(t *testing.T) {
+ t.Parallel()
+ fake, dir, env := testutil.PiCleanupExecutable(t, "ignore")
+ backend, err := agent.ResolveBackend(provider, agent.Config{ExecutablePath: fake, Env: env, Logger: slog.Default()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "session.jsonl"), nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+ defer cancel()
+ var onTool context.CancelFunc
+ want := "idle_watchdog"
+ if trigger == "manual" {
+ onTool, want = cancel, "cancelled"
+ }
+ d := newTestDaemon(t)
+ d.cfg.AgentIdleWatchdog, d.cfg.AgentToolWatchdog = 3*time.Second, 100*time.Millisecond
+ started := time.Now()
+ result, _, err := d.executeAndDrain(ctx, cancelPiAtTool{Backend: backend, cancel: onTool}, "test", agent.ExecOptions{
+ Cwd: dir, ResumeSessionID: filepath.Join(dir, "session.jsonl"),
+ }, slog.Default(), "pi-cleanup", "", new(atomic.Int32))
+ if err != nil || result.Status != want {
+ t.Fatalf("result=%+v err=%v, want %s", result, err, want)
+ }
+ if time.Since(started) > 6*time.Second {
+ t.Fatal("cleanup did not return within its budget")
+ }
+ data, _ := os.ReadFile(filepath.Join(dir, "pids.json"))
+ var pids []int
+ if json.Unmarshal(data, &pids) != nil || len(pids) != 2 {
+ t.Fatal("fixture did not record the processes before cancellation")
+ }
+ for _, pid := range pids {
+ until := time.Now().Add(2 * time.Second)
+ for syscall.Kill(pid, 0) == nil && time.Now().Before(until) {
+ time.Sleep(20 * time.Millisecond)
+ }
+ if syscall.Kill(pid, 0) == nil {
+ t.Fatalf("process %d still alive after daemon result", pid)
+ }
+ }
+ before, _ := os.ReadFile(filepath.Join(dir, "receipt"))
+ time.Sleep(100 * time.Millisecond)
+ after, _ := os.ReadFile(filepath.Join(dir, "receipt"))
+ if len(before) == 0 || len(before) != len(after) {
+ t.Fatalf("writer still active after handoff: %d -> %d", len(before), len(after))
+ }
+ })
+ }
+ }
+}
diff --git a/server/internal/daemon/testmain_test.go b/server/internal/daemon/testmain_test.go
index 1a91c5abf1..b8ea0752d1 100644
--- a/server/internal/daemon/testmain_test.go
+++ b/server/internal/daemon/testmain_test.go
@@ -17,6 +17,9 @@ import (
// LOCALAPPDATA on Windows. Process-wide redirection isolates tests that forget
// their own redirect; per-test t.Setenv overrides still take precedence.
func TestMain(m *testing.M) {
+ if testutil.RunPiCleanupFixture() {
+ os.Exit(0)
+ }
for _, key := range []string{
"MULTICA_AGENT_ID",
"MULTICA_TASK_ID",
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 28d4446242..9261cb5c14 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -504,6 +504,9 @@ type AgentTaskResponse struct {
TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author
NewCommentCount int `json:"new_comment_count,omitempty"` // ISSUE-WIDE comments since this agent's last run — every thread, not just the triggering one (CountNewCommentsSince); excludes the injected trigger and the agent's own comments; omitempty so old daemons ignore it
NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; omitempty so old daemons ignore it. Suppressed with the count when the delta is zero — NewCommentsDeltaKnown, not this field, is what says the server looked
+
+ ProcessCleanupCapability string `json:"process_cleanup_capability,omitempty"`
+
// MUL-8218: set only when the trigger comment was edited AFTER the run
// whose session this claim resumes had started, so that session's history
// may still hold an earlier version of the text. EditedAt is RFC3339;
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 93f5a4d9d7..78dcfd9ae0 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -4599,7 +4599,7 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {
taskID := chi.URLParam(r, "taskId")
// Verify the caller owns this task's workspace.
- _, workspaceID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, taskID)
+ startTask, workspaceID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, taskID)
if !ok {
return
}
@@ -4615,15 +4615,9 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {
return
}
}
- enableTaskSupplement := slices.Contains(req.Capabilities, protocol.DaemonCapabilityTaskSupplementV1)
- var task *db.AgentTaskQueue
- var err error
legacy := req.RuntimeID == "" && req.DispatchedAt == ""
- if legacy {
- // Older daemons send {}. Keep their single-winner behavior; in
- // particular, they cannot acknowledge an already-running task.
- task, err = h.TaskService.StartTask(r.Context(), parseUUID(taskID), enableTaskSupplement)
- } else {
+ var claim db.LockAgentTaskStartClaimParams
+ if !legacy {
runtimeID, ok := parseUUIDOrBadRequest(w, req.RuntimeID, "runtime_id")
if !ok {
return
@@ -4633,10 +4627,55 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "dispatched_at must be a PostgreSQL claim timestamp")
return
}
- task, err = h.TaskService.StartTaskForClaim(r.Context(), db.LockAgentTaskStartClaimParams{
- ID: parseUUID(taskID), RuntimeID: runtimeID,
+ if startTask.RuntimeID != runtimeID || !startTask.DispatchedAt.Valid || !startTask.DispatchedAt.Time.Equal(generation) {
+ writeError(w, http.StatusConflict, "task claim is stale")
+ return
+ }
+ claim = db.LockAgentTaskStartClaimParams{
+ ID: startTask.ID, RuntimeID: runtimeID,
DispatchedAt: pgtype.Timestamptz{Time: generation, Valid: true},
- }, enableTaskSupplement)
+ }
+ }
+ // Check the requested generation before a cleanup guard can mutate a claim.
+ waiting, waitErr := h.Queries.TaskWaitingForProcessCleanup(r.Context(), startTask.ID)
+ if waitErr != nil {
+ writeError(w, http.StatusInternalServerError, "could not verify pending process cleanup")
+ return
+ }
+ if waiting {
+ if _, err := h.TaskService.RequeueTaskAfterClaimFailure(r.Context(), startTask); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to defer task until process cleanup")
+ return
+ }
+ writeError(w, http.StatusConflict, "previous run is still stopping; task was requeued")
+ return
+ }
+ blocked, blockErr := h.Queries.TaskBlockedByProcessCleanup(r.Context(), startTask.ID)
+ if blockErr != nil {
+ writeError(w, http.StatusInternalServerError, "could not verify prior process cleanup")
+ return
+ }
+ if blocked {
+ if _, err := h.TaskService.FailTask(r.Context(), startTask.ID,
+ "A previous run's process cleanup is unconfirmed. Check background processes, then manually rerun the task to resume this agent.",
+ "", "", "", taskfailure.ReasonProcessCleanupBlocked.String(), false, "", ""); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to record process cleanup block")
+ return
+ }
+ writeError(w, http.StatusConflict, "task blocked by unconfirmed process cleanup; manual rerun required")
+ return
+ }
+ offered := service.TaskStartCapabilities{
+ Supplement: slices.Contains(req.Capabilities, protocol.DaemonCapabilityTaskSupplementV1),
+ ProcessCleanup: slices.Contains(req.Capabilities, protocol.DaemonCapabilityPiProcessCleanupV1),
+ }
+ var task *db.AgentTaskQueue
+ var err error
+ if legacy {
+ // Older daemons send {} and retain their single-winner behavior.
+ task, err = h.TaskService.StartTask(r.Context(), startTask.ID, offered)
+ } else {
+ task, err = h.TaskService.StartTaskForClaim(r.Context(), claim, offered)
}
if err != nil {
slog.Warn("start task failed", "task_id", taskID, "error", err)
@@ -4654,6 +4693,12 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {
slog.Info("task started", "task_id", taskID, "agent_id", uuidToString(task.AgentID))
resp := taskToResponse(*task, workspaceID)
+ var result struct {
+ ProcessCleanupCapability string `json:"process_cleanup_capability"`
+ }
+ if json.Unmarshal(task.Result, &result) == nil {
+ resp.ProcessCleanupCapability = result.ProcessCleanupCapability
+ }
// Echo the capability the server actually committed for this exact run.
// A daemon must use this response rather than its own offer: an old server
// ignores the offer and omits the field, which keeps daemon-first rollouts
@@ -5761,6 +5806,8 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {
// transcript (#5219); idempotent when nothing was deferred.
// TaskCancelAckRequest is the body of the daemon's cancel acknowledgement.
type TaskCancelAckRequest struct {
+ // Absent on older daemons: a pending Pi cleanup cannot be assumed clean.
+ ProcessCleanupConfirmed *bool `json:"process_cleanup_confirmed,omitempty"`
// BranchName: a cancelled worktree task has already committed whatever the
// agent produced — the worktree is finalized before the daemon learns of
// the cancellation. The rest of the result is discarded on this path, so
@@ -5838,7 +5885,7 @@ func (h *Handler) AckTaskCancelled(w http.ResponseWriter, r *http.Request) {
}
delivered = true
}
- if msg := strings.TrimSpace(req.ErrorMessage); msg != "" {
+ if msg := strings.TrimSpace(req.ErrorMessage); msg != "" && req.FailureReason != taskfailure.ReasonProcessCleanupUnconfirmed.String() {
reason := strings.TrimSpace(req.FailureReason)
if err := h.Queries.SetAgentTaskErrorIfEmpty(r.Context(), db.SetAgentTaskErrorIfEmptyParams{
ID: task.ID,
@@ -5863,6 +5910,24 @@ func (h *Handler) AckTaskCancelled(w http.ResponseWriter, r *http.Request) {
return
}
}
+ var cancellationResult map[string]any
+ _ = json.Unmarshal(task.Result, &cancellationResult)
+ needsConfirmation, _ := cancellationResult["process_cleanup_pending"].(bool)
+ if req.FailureReason == taskfailure.ReasonProcessCleanupUnconfirmed.String() || (needsConfirmation && (req.ProcessCleanupConfirmed == nil || !*req.ProcessCleanupConfirmed)) {
+ msg := strings.TrimSpace(req.ErrorMessage)
+ if msg == "" {
+ msg = "Process cleanup is unconfirmed; background processes may still be running. Check them before manually rerunning the task."
+ }
+ _, err := h.TaskService.FailTask(r.Context(), task.ID, msg, "", "", "", taskfailure.ReasonProcessCleanupUnconfirmed.String(), false, "", "")
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to record process cleanup failure")
+ return
+ }
+ }
+ if err := h.Queries.ClearTaskProcessCleanupPending(r.Context(), task.ID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to acknowledge process cleanup")
+ return
+ }
if delivered {
// The task:cancelled broadcast fired at cancel time, before this ack —
// clients may already hold a refetched row without the branch/error
diff --git a/server/internal/handler/daemon_process_cleanup_test.go b/server/internal/handler/daemon_process_cleanup_test.go
new file mode 100644
index 0000000000..0484e9b545
--- /dev/null
+++ b/server/internal/handler/daemon_process_cleanup_test.go
@@ -0,0 +1,215 @@
+package handler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
+)
+
+func TestProcessCleanupFence(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("PostgreSQL is required")
+ }
+ agentID := dbfx.Agent(t, "cleanup-fenced agent", testRuntimeID)
+ issue := dbfx.Issue(t, "process cleanup fence")
+ unsafe := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": testRuntimeID, "issue_id": issue, "status": "failed",
+ "failure_reason": "cleanup_unconfirmed", "completed_at": testutil.Raw("now() - interval '1 minute'"),
+ })
+ queued := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": testRuntimeID, "issue_id": issue, "status": "dispatched", "dispatched_at": time.Now().UTC(),
+ })
+ req := withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+queued+"/start", nil), "taskId", queued)
+ testutil.Call(t, testHandler.StartTask, req).Want(http.StatusConflict)
+ var status, reason string
+ dbfx.QueryRow(t, `SELECT status, failure_reason FROM agent_task_queue WHERE id=$1`, queued).Scan(&status, &reason)
+ if status != "failed" || reason != "cleanup_blocked" {
+ t.Fatalf("automatic successor = %s/%s", status, reason)
+ }
+ manual := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": testRuntimeID, "issue_id": issue, "status": "dispatched",
+ "rerun_of_task_id": unsafe, "initiator_user_id": testUserID,
+ })
+ blocked, err := testHandler.Queries.TaskBlockedByProcessCleanup(context.Background(), parseUUID(manual))
+ if err != nil || blocked {
+ t.Fatalf("new manual rerun blocked=%v err=%v", blocked, err)
+ }
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status='completed' WHERE id=$1`, manual)
+ next := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": testRuntimeID, "issue_id": issue, "status": "dispatched"})
+ blocked, err = testHandler.Queries.TaskBlockedByProcessCleanup(context.Background(), parseUUID(next))
+ if err != nil || blocked {
+ t.Fatalf("successful manual recovery did not release fence: blocked=%v err=%v", blocked, err)
+ }
+}
+
+func TestProcessCleanupCancelAckUnconfirmed(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("PostgreSQL is required")
+ }
+ agentID := dbfx.Agent(t, "cancel cleanup agent", testRuntimeID)
+ issue := dbfx.Issue(t, "cancel cleanup")
+ task := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": testRuntimeID, "issue_id": issue, "status": "cancelled",
+ "started_at": testutil.Raw("now() - interval '1 minute'"),
+ "completed_at": testutil.Raw("now()"), "result": `{"process_cleanup_pending":true}`,
+ })
+ for range 2 { // Lost acknowledgement/replay must not duplicate failure output.
+ ackCancelled(t, task, map[string]any{
+ "failure_reason": taskfailure.ReasonProcessCleanupUnconfirmed.String(),
+ "error_message": "Background processes may still be running; check before manually rerunning.",
+ })
+ }
+ var status, reason, message string
+ var pending bool
+ dbfx.QueryRow(t, `SELECT status, failure_reason, error, COALESCE(result->>'process_cleanup_pending'='true',false) FROM agent_task_queue WHERE id=$1`, task).Scan(&status, &reason, &message, &pending)
+ if status != "failed" || reason != "cleanup_unconfirmed" || pending || !strings.Contains(message, "Background processes") {
+ t.Fatalf("cancel-ack lost cleanup failure: status=%s reason=%s pending=%v error=%s", status, reason, pending, message)
+ }
+ var attempts int
+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE retry_of_task_id=$1`, task).Scan(&attempts)
+ if attempts != 0 {
+ t.Fatal("cleanup failure created an automatic retry")
+ }
+}
+
+func TestProcessCleanupPendingDefersSuccessor(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("PostgreSQL is required")
+ }
+ agentID := dbfx.Agent(t, "pending cleanup agent", testRuntimeID)
+ issue := dbfx.Issue(t, "pending cleanup")
+ stopping := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": testRuntimeID, "issue_id": issue, "status": "cancelled",
+ "started_at": testutil.Raw("now() - interval '1 minute'"), "completed_at": testutil.Raw("now()"),
+ "result": `{"process_cleanup_pending":true}`,
+ })
+ successor := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": testRuntimeID, "issue_id": issue, "status": "dispatched", "dispatched_at": time.Now().UTC(),
+ })
+ var generation pgtype.Timestamptz
+ dbfx.QueryRow(t, `SELECT dispatched_at FROM agent_task_queue WHERE id=$1`, successor).Scan(&generation)
+ testutil.Call(t, testHandler.StartTask, startClaimRequest(successor, testRuntimeID, generation.Time.Add(-time.Microsecond))).Want(http.StatusConflict)
+ var before string
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id=$1`, successor).Scan(&before)
+ if before != "dispatched" {
+ t.Fatal("a stale start changed another delivery's claim")
+ }
+ testutil.Call(t, testHandler.StartTask, withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+successor+"/start", nil), "taskId", successor)).Want(http.StatusConflict)
+ var state string
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id=$1`, successor).Scan(&state)
+ if state != "queued" {
+ t.Fatalf("successor was not deferred: %s", state)
+ }
+ ackCancelled(t, stopping, map[string]any{"process_cleanup_confirmed": true})
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status='dispatched',dispatched_at=now() WHERE id=$1`, successor)
+ testutil.Call(t, testHandler.StartTask, withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+successor+"/start", nil), "taskId", successor)).Want(http.StatusOK)
+}
+
+func TestProcessCleanupCapabilityNegotiation(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("PostgreSQL is required")
+ }
+ for _, provider := range []string{"pi", "omp", "codex"} {
+ for _, capable := range []bool{false, true} {
+ for _, claimFenced := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/capable=%v/claim=%v", provider, capable, claimFenced), func(t *testing.T) {
+ runtime := dbfx.Runtime(t, "cleanup runtime", testutil.Cols{"provider": provider})
+ agentID := dbfx.Agent(t, "cleanup negotiation", runtime)
+ issue := dbfx.Issue(t, "cleanup negotiation")
+ id := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtime, "issue_id": issue, "status": "dispatched", "dispatched_at": time.Now().UTC()})
+ body := map[string]any{}
+ if capable {
+ body["capabilities"] = []string{"pi-process-cleanup-v1"}
+ }
+ if claimFenced {
+ var generation pgtype.Timestamptz
+ dbfx.QueryRow(t, `SELECT dispatched_at FROM agent_task_queue WHERE id=$1`, id).Scan(&generation)
+ body["runtime_id"], body["dispatched_at"] = runtime, generation.Time.Format(time.RFC3339Nano)
+ }
+ req := withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+id+"/start", body), "taskId", id)
+ started := testutil.Decode[map[string]any](t, testHandler.StartTask, req, http.StatusOK)
+ wantPending := capable && (provider == "pi" || provider == "omp")
+ if got := started["process_cleanup_capability"] == "pi-process-cleanup-v1"; got != wantPending {
+ t.Fatalf("negotiated cleanup=%v, want %v", got, wantPending)
+ }
+ if claimFenced {
+ // Replaying a start with the opposite offer must not renegotiate a run.
+ if capable {
+ delete(body, "capabilities")
+ } else {
+ body["capabilities"] = []string{"pi-process-cleanup-v1"}
+ }
+ req = withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+id+"/start", body), "taskId", id)
+ testutil.Call(t, testHandler.StartTask, req).Want(http.StatusOK)
+ }
+ if _, err := testHandler.TaskService.CancelTask(t.Context(), parseUUID(id)); err != nil {
+ t.Fatal(err)
+ }
+ var pending bool
+ dbfx.QueryRow(t, `SELECT COALESCE(result->>'process_cleanup_pending'='true',false) FROM agent_task_queue WHERE id=$1`, id).Scan(&pending)
+ if pending != wantPending {
+ t.Fatalf("pending=%v, want %v", pending, wantPending)
+ }
+ ackCancelled(t, id, map[string]any{})
+ var state string
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id=$1`, id).Scan(&state)
+ wantState := "cancelled"
+ if wantPending {
+ wantState = "failed"
+ }
+ if state != wantState {
+ t.Fatalf("missing acknowledgement = %s, want %s", state, wantState)
+ }
+ successor := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtime, "issue_id": issue, "status": "dispatched"})
+ blocked, err := testHandler.Queries.TaskBlockedByProcessCleanup(t.Context(), parseUUID(successor))
+ if err != nil || blocked != wantPending {
+ t.Fatalf("successor blocked=%v, want %v, err=%v", blocked, wantPending, err)
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestProcessCleanupExpiredAcknowledgementStaysBlocked(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("PostgreSQL is required")
+ }
+ agentID := dbfx.Agent(t, "expired cleanup agent", testRuntimeID)
+ issue := dbfx.Issue(t, "expired cleanup")
+ stopping := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": testRuntimeID, "issue_id": issue, "status": "cancelled",
+ "completed_at": testutil.Raw("now() - interval '1 minute'"),
+ "result": `{"process_cleanup_pending":true}`,
+ })
+ next := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": testRuntimeID, "issue_id": issue, "status": "dispatched",
+ })
+ blocked, err := testHandler.Queries.TaskBlockedByProcessCleanup(context.Background(), parseUUID(next))
+ if err != nil || !blocked {
+ t.Fatalf("expired acknowledgement released automatic work: blocked=%v err=%v", blocked, err)
+ }
+ dbfx.Exec(t, `UPDATE agent_task_queue SET rerun_of_task_id=$2,created_at=now()-interval '45 seconds' WHERE id=$1`, next, stopping)
+ blocked, err = testHandler.Queries.TaskBlockedByProcessCleanup(context.Background(), parseUUID(next))
+ if err != nil || !blocked {
+ t.Fatalf("a rerun queued before cleanup became unconfirmed bypassed the fence: blocked=%v err=%v", blocked, err)
+ }
+ dbfx.Exec(t, `UPDATE agent_task_queue SET created_at=now() WHERE id=$1`, next)
+ blocked, err = testHandler.Queries.TaskBlockedByProcessCleanup(context.Background(), parseUUID(next))
+ if err != nil || blocked {
+ t.Fatalf("new explicit recovery was refused: blocked=%v err=%v", blocked, err)
+ }
+ other := dbfx.Agent(t, "unrelated cleanup agent", testRuntimeID)
+ otherTask := dbfx.Task(t, other, testutil.Cols{"runtime_id": testRuntimeID, "issue_id": issue, "status": "dispatched"})
+ blocked, err = testHandler.Queries.TaskBlockedByProcessCleanup(context.Background(), parseUUID(otherTask))
+ if err != nil || blocked {
+ t.Fatalf("cleanup fence affected another agent: blocked=%v err=%v", blocked, err)
+ }
+}
diff --git a/server/internal/handler/task_supplement_test.go b/server/internal/handler/task_supplement_test.go
index 80a18a1240..bddd12196d 100644
--- a/server/internal/handler/task_supplement_test.go
+++ b/server/internal/handler/task_supplement_test.go
@@ -13,6 +13,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -219,7 +220,7 @@ func TestTaskSupplementCapabilityDoesNotBreakNonIssueStarts(t *testing.T) {
runtimeID := dbfx.Runtime(t, "supplement-no-issue", testutil.Cols{"provider": provider})
agentID := dbfx.Agent(t, "Supplement no issue", runtimeID)
taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "issue_id": nil, "status": "dispatched"})
- started, err := testHandler.TaskService.StartTask(t.Context(), parseUUID(taskID), true)
+ started, err := testHandler.TaskService.StartTask(t.Context(), parseUUID(taskID), service.TaskStartCapabilities{Supplement: true})
if err != nil || started.Status != "running" {
t.Fatalf("non-issue start = %#v: %v", started, err)
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index acedd5518c..2171ed092a 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -3010,6 +3010,9 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UU
return err
}
task = cancelled
+ if err := qtx.MarkPiTaskProcessCleanupPending(ctx, task.ID); err != nil {
+ return fmt.Errorf("mark cancelled runtime cleanup pending: %w", err)
+ }
// CancelAgentTaskByUser appends the recovery receipt in the same
// statement, so the returned row already carries it.
if err := SettleTerminalTaskState(ctx, qtx, cancelled); err != nil {
@@ -4352,15 +4355,25 @@ func (s *TaskService) maybeLogClaimSlow(agentID pgtype.UUID, outcome string, sta
)
}
+// TaskStartCapabilities records the capabilities offered for this exact run.
+// Persist these in the same transaction as running, before cancellation can win.
+type TaskStartCapabilities struct {
+ Supplement bool
+ ProcessCleanup bool
+}
+
// StartTask transitions a dispatched task to running.
// Local agents manage issue status via the CLI; Qoder runs use guarded server transitions.
-func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID, supplementSupport ...bool) (*db.AgentTaskQueue, error) {
- enableTaskSupplement := len(supplementSupport) > 0 && supplementSupport[0]
+func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID, capabilities ...TaskStartCapabilities) (*db.AgentTaskQueue, error) {
+ var offered TaskStartCapabilities
+ if len(capabilities) > 0 {
+ offered = capabilities[0]
+ }
var task db.AgentTaskQueue
var change *qoderIssueChange
err := s.runInTx(ctx, func(q *db.Queries) error {
var err error
- task, err = q.StartAgentTaskWithSupplement(ctx, db.StartAgentTaskWithSupplementParams{TaskID: taskID, EnableTaskSupplement: enableTaskSupplement})
+ task, err = q.StartAgentTaskWithSupplement(ctx, db.StartAgentTaskWithSupplementParams{TaskID: taskID, EnableTaskSupplement: offered.Supplement, EnableProcessCleanup: offered.ProcessCleanup})
if err != nil {
return err
}
@@ -4378,7 +4391,7 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID, supplem
// StartTaskForClaim serializes the ownership check and transition with reclaim,
// cancellation and other start requests. A replay linearizes at the locked read;
// a cancellation that commits later can still cancel the acknowledged task.
-func (s *TaskService) StartTaskForClaim(ctx context.Context, claim db.LockAgentTaskStartClaimParams, supplementSupport ...bool) (*db.AgentTaskQueue, error) {
+func (s *TaskService) StartTaskForClaim(ctx context.Context, claim db.LockAgentTaskStartClaimParams, capabilities ...TaskStartCapabilities) (*db.AgentTaskQueue, error) {
if !claim.ID.Valid || !claim.RuntimeID.Valid || !claim.DispatchedAt.Valid {
return nil, fmt.Errorf("start task: incomplete claim")
}
@@ -4395,9 +4408,14 @@ func (s *TaskService) StartTaskForClaim(ctx context.Context, claim db.LockAgentT
var change *qoderIssueChange
replay := task.Status == "running"
if !replay {
+ var offered TaskStartCapabilities
+ if len(capabilities) > 0 {
+ offered = capabilities[0]
+ }
task, err = qtx.StartAgentTaskWithSupplement(ctx, db.StartAgentTaskWithSupplementParams{
TaskID: task.ID,
- EnableTaskSupplement: len(supplementSupport) > 0 && supplementSupport[0],
+ EnableTaskSupplement: offered.Supplement,
+ EnableProcessCleanup: offered.ProcessCleanup,
})
if err != nil {
return nil, fmt.Errorf("start claimed task: %w", err)
@@ -5096,6 +5114,9 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.
SessionRolloutMissing: sessionRolloutMissing,
RetiredSessionID: pgtype.Text{String: retiredSessionID, Valid: retiredSessionID != ""},
})
+ if errors.Is(err, pgx.ErrNoRows) && failureReason == taskfailure.ReasonProcessCleanupUnconfirmed.String() {
+ t, err = qtx.FailCancelledTaskProcessCleanup(ctx, db.FailCancelledTaskProcessCleanupParams{ID: taskID, ErrorMessage: errMsg})
+ }
if err != nil {
return err
}
@@ -5354,7 +5375,7 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.
// platform-authored comment on the source task's issue, routed explicitly to
// that task's agent; recoverDelegatedTaskFailure coalesces it with an
// existing coordinator run and deduplicates by the failed task id.
- if retried == nil {
+ if retried == nil && failureReason != taskfailure.ReasonProcessCleanupUnconfirmed.String() && failureReason != taskfailure.ReasonProcessCleanupBlocked.String() {
_, recoveryErr := s.recoverDelegatedTaskFailure(ctx, task)
if recoveryErr != nil {
slog.Warn("delegated task failure recovery failed",
diff --git a/server/internal/testutil/pi_cleanup_other.go b/server/internal/testutil/pi_cleanup_other.go
new file mode 100644
index 0000000000..d872312764
--- /dev/null
+++ b/server/internal/testutil/pi_cleanup_other.go
@@ -0,0 +1,5 @@
+//go:build !linux && !darwin
+
+package testutil
+
+func RunPiCleanupFixture() bool { return false }
diff --git a/server/internal/testutil/pi_cleanup_unix.go b/server/internal/testutil/pi_cleanup_unix.go
new file mode 100644
index 0000000000..3496c2c084
--- /dev/null
+++ b/server/internal/testutil/pi_cleanup_unix.go
@@ -0,0 +1,117 @@
+//go:build linux || darwin
+
+package testutil
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "syscall"
+ "testing"
+ "time"
+)
+
+const piCleanupFixtureMode = "MULTICA_TEST_PI_CLEANUP_MODE"
+
+// RunPiCleanupFixture dispatches before testing parses the runtime's argv.
+// Both agent and daemon tests use the same fake, never a user-installed CLI.
+func RunPiCleanupFixture() bool {
+ mode := os.Getenv(piCleanupFixtureMode)
+ if mode == "" {
+ return false
+ }
+ dir := os.Getenv("MULTICA_TEST_PI_CLEANUP_DIR")
+ if mode == "writer" {
+ signal.Ignore(syscall.SIGTERM)
+ f, err := os.OpenFile(filepath.Join(dir, "receipt"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
+ if err != nil {
+ panic(err)
+ }
+ defer f.Close()
+ end := time.Now().Add(15 * time.Second)
+ for time.Now().Before(end) {
+ _, _ = f.WriteString("x")
+ time.Sleep(20 * time.Millisecond)
+ }
+ return true
+ }
+ _, _ = io.Copy(io.Discard, os.Stdin)
+ term := make(chan os.Signal, 1)
+ if mode == "graceful" {
+ signal.Notify(term, syscall.SIGTERM)
+ } else {
+ signal.Ignore(syscall.SIGTERM)
+ }
+ writer := exec.Command(os.Args[0])
+ writer.Env = append(os.Environ(), piCleanupFixtureMode+"=writer")
+ writer.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
+ writer.Stdout, writer.Stderr = os.Stdout, os.Stderr
+ if err := writer.Start(); err != nil {
+ panic(err)
+ }
+ data, _ := json.Marshal([]int{os.Getpid(), writer.Process.Pid})
+ _ = os.WriteFile(filepath.Join(dir, "pids.json"), data, 0o600)
+ for until := time.Now().Add(3 * time.Second); time.Now().Before(until); {
+ if info, err := os.Stat(filepath.Join(dir, "receipt")); err == nil && info.Size() > 0 {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ fmt.Println(`{"type":"agent_start"}`)
+ fmt.Println(`{"type":"tool_execution_start","toolName":"bash","toolCallId":"fixture"}`)
+ if mode == "success" {
+ fmt.Println(`{"type":"tool_execution_end","toolCallId":"fixture","result":"server started"}`)
+ fmt.Println(`{"type":"agent_end"}`)
+ // A successful run may intentionally leave a detached service. Keep
+ // inherited output open too: finalization must not wait for the service.
+ return true
+ }
+ if mode == "exit" {
+ time.Sleep(200 * time.Millisecond)
+ return true
+ }
+ select {
+ case <-term:
+ _ = os.WriteFile(filepath.Join(dir, "term"), []byte("received"), 0o600)
+ _ = writer.Process.Kill()
+ _ = writer.Wait()
+ case <-time.After(15 * time.Second):
+ _ = writer.Process.Kill()
+ _ = writer.Wait()
+ }
+ return true
+}
+
+// PiCleanupExecutable returns an isolated executable plus a scratch directory
+// containing pids.json, receipt, and (for graceful shutdown) the TERM receipt.
+func PiCleanupExecutable(t *testing.T, mode string) (string, string, map[string]string) {
+ t.Helper()
+ dir := t.TempDir()
+ bin, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ fake := filepath.Join(dir, "pi-fixture")
+ // Match the agent package's executable fixture writer: sibling forks must
+ // not inherit an open write descriptor and cause Linux ETXTBSY on exec.
+ syscall.ForkLock.RLock()
+ err = os.WriteFile(fake, []byte(fmt.Sprintf("#!/bin/sh\nexec %q \"$@\"\n", bin)), 0o700)
+ syscall.ForkLock.RUnlock()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ data, _ := os.ReadFile(filepath.Join(dir, "pids.json"))
+ var pids []int
+ if json.Unmarshal(data, &pids) == nil {
+ for _, pid := range pids {
+ _ = syscall.Kill(pid, syscall.SIGKILL)
+ }
+ }
+ })
+ return fake, dir, map[string]string{piCleanupFixtureMode: mode, "MULTICA_TEST_PI_CLEANUP_DIR": dir}
+}
diff --git a/server/migrations/594_agent_task_process_cleanup_index.down.sql b/server/migrations/594_agent_task_process_cleanup_index.down.sql
new file mode 100644
index 0000000000..e0d5531d0a
--- /dev/null
+++ b/server/migrations/594_agent_task_process_cleanup_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_process_cleanup;
diff --git a/server/migrations/594_agent_task_process_cleanup_index.up.sql b/server/migrations/594_agent_task_process_cleanup_index.up.sql
new file mode 100644
index 0000000000..d29f7f716e
--- /dev/null
+++ b/server/migrations/594_agent_task_process_cleanup_index.up.sql
@@ -0,0 +1,7 @@
+-- Both cleanup failures and pending cancellation acknowledgements participate
+-- in the start guard. Exclude ordinary history while serving the OR predicate
+-- and the latest-unsafe-run ordering from one small index.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_process_cleanup
+ ON agent_task_queue (agent_id, runtime_id, completed_at DESC, id DESC)
+ WHERE failure_reason = 'cleanup_unconfirmed'
+ OR (status = 'cancelled' AND result->>'process_cleanup_pending' = 'true');
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index ea0799f744..0e37c1f766 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -164,6 +164,10 @@ func runContext(ctx context.Context, timeout time.Duration) (context.Context, co
// Session represents a running agent execution.
type Session struct {
+ // CleanupRequired means Result is also the acknowledgement that the
+ // backend's bounded process cleanup finished. A missing acknowledgement
+ // must prevent automatic continuation, even after upstream cancellation.
+ CleanupRequired bool
// Supplement delivers an additional human instruction to the currently
// active provider turn. Nil means the backend cannot safely do so.
// Adapters bound their own transport calls; a hook-based adapter may wait
diff --git a/server/pkg/agent/claude_deadlock_test.go b/server/pkg/agent/claude_deadlock_test.go
index 0e19cebc33..6296840c6b 100644
--- a/server/pkg/agent/claude_deadlock_test.go
+++ b/server/pkg/agent/claude_deadlock_test.go
@@ -10,6 +10,8 @@ import (
"strings"
"testing"
"time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
)
// TestMain intercepts when the test binary is re-executed as a fake
@@ -20,6 +22,9 @@ import (
// invoked with a real agent CLI's argv: TestMain runs before the testing
// package parses flags, so arguments like `run --format json` never reach it.
func TestMain(m *testing.M) {
+ if testutil.RunPiCleanupFixture() {
+ os.Exit(0)
+ }
if os.Getenv(codeartsModelHelperEnv) == "1" {
runFakeCodeArtsModelHelper()
os.Exit(0)
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.go
index ac2c880d87..012e7c66b3 100644
--- a/server/pkg/agent/pi.go
+++ b/server/pkg/agent/pi.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"log/slog"
@@ -37,6 +38,7 @@ type piBackend struct {
// error. Production uses defaultPiTurnErrorGrace; tests shorten it without
// changing concurrent executions through package-global state.
turnErrorGrace time.Duration
+ terminateGrace time.Duration
}
var (
@@ -444,6 +446,8 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
args = buildPiArgs(sessionPath, opts, b.cfg.Logger)
}
cmd, _, _ := b.cfg.commandAt(execName).execVia(processCtx, choosePiInvocation, lookedUp, args, b.cfg.Logger)
+ // The joined cleanup below owns TERM, escalation and pipe release.
+ cmd.Cancel = func() error { return nil }
hideAgentWindow(cmd)
b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(args))
cmd.WaitDelay = 10 * time.Second
@@ -505,6 +509,16 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
_, _ = io.Copy(stderrWatch, stderrRead)
close(stderrDone)
}()
+ cleanup := newPiRunCleanup(cmd)
+ grace := b.terminateGrace
+ if grace <= 0 {
+ grace = 2 * time.Second
+ }
+ closePipes := func() {
+ closePiReadPipe(stdout)
+ closePiReadPipe(stderrRead)
+ }
+ finishCleanup := func() error { return cleanup.finish(cmd, closeStdin, closePipes, grace) }
b.cfg.Logger.Info(label+" started", "pid", cmd.Process.Pid, "cwd", opts.Cwd, "model", opts.Model)
@@ -516,14 +530,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
}
turnErrors := newPiTurnErrorGuard(turnErrorGrace, func() {
b.cfg.Logger.Info(label + " turn error recovery grace expired; stopping runtime")
- // CommandContext owns process-tree cancellation for every runtime
- // command. An escaped descendant can nevertheless retain stdout/stderr
- // write ends after that group dies, so close the adapter-owned pipes too:
- // finalization must not depend on an unowned process eventually exiting.
cancelProcess()
- closeStdin()
- closePiReadPipe(stdout)
- closePiReadPipe(stderrRead)
})
// Write concurrently with stdout consumption. A large prompt can fill the
@@ -536,14 +543,24 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
writeErrCh <- err
}()
- // Close every adapter-owned pipe when the context is cancelled. Closing stdin
- // releases a writer blocked on a child that stopped reading; closing the read
- // pipes releases the stdout scanner and stderr copier.
go func() {
- <-runCtx.Done()
- closeStdin()
- closePiReadPipe(stdout)
- closePiReadPipe(stderrRead)
+ select {
+ case <-processCtx.Done():
+ _ = finishCleanup()
+ case <-cleanup.exited:
+ // Descendants can inherit stdout after a successful parent exit. Allow
+ // buffered protocol events to drain before ending that read. In-flight
+ // tool accounting below decides whether termination is required.
+ if pipe, ok := stdout.(interface{ SetReadDeadline(time.Time) error }); ok {
+ _ = pipe.SetReadDeadline(time.Now().Add(250 * time.Millisecond))
+ }
+ select {
+ case <-processCtx.Done():
+ _ = finishCleanup()
+ case <-cleanup.done:
+ }
+ case <-cleanup.done:
+ }
}()
releaseExtension = nil
@@ -576,6 +593,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
continue
}
turnErrors.observeEvent(evt.Type)
+ cleanup.observe(evt.Type)
switch evt.Type {
case "agent_start":
@@ -695,6 +713,15 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
}
}
scanErr := scanner.Err()
+ if errors.Is(scanErr, os.ErrDeadlineExceeded) {
+ select {
+ case <-cleanup.exited:
+ // This deadline only releases an inherited pipe after the runtime's
+ // own exit; all available events were consumed before the deadline.
+ scanErr = nil
+ default:
+ }
+ }
if scanErr != nil {
// Scanner stopped consuming stdout. Close the pipe before Wait so Pi,
// still writing an oversized event, cannot deadlock on the full OS
@@ -706,23 +733,29 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
trySend(msgCh, Message{Type: MessageText, Content: d})
}
- // Finish the user-owned stderr read before Wait closes StderrPipe. Normal
- // exit gets the same 10s backstop cmd.WaitDelay used to provide when
- // os/exec owned the copier. Cancellation and error-grace expiry close
- // stderrRead above, so their finalization does not pay it.
- stderrTimer := time.NewTimer(cmd.WaitDelay)
- select {
- case <-stderrDone:
- stderrTimer.Stop()
- case <-stderrTimer.C:
- closePiReadPipe(stderrRead)
- <-stderrDone
+ // Do not reap the root before the cancellation owner releases its numeric
+ // process group: an unreaped root prevents PGID reuse during cleanup.
+ if scanErr == nil && cleanup.tools.Load() == 0 && processCtx.Err() == nil && piCanObserveRuntimeExit && !piRuntimeExited(cmd) {
+ select {
+ case <-cleanup.exited:
+ case <-processCtx.Done():
+ }
+ }
+ var cleanupErr error
+ if scanErr != nil || cleanup.tools.Load() > 0 || processCtx.Err() != nil {
+ cleanupErr = finishCleanup()
+ } else {
+ cleanupErr = cleanup.complete(closeStdin, closePipes)
}
+ <-stderrDone
waitErr := cmd.Wait()
releaseProcessGroup(cmd)
duration := time.Since(startTime)
lastTurnError, turnErrorGraceExpired := turnErrors.finish()
+ if cleanupErr == nil && cleanup.tools.Load() > 0 && cleanup.unobserved {
+ cleanupErr = fmt.Errorf("runtime exited before tool process ownership could be recorded")
+ }
// Wait closes the process pipes, so a prompt write still blocked when the
// child exited has returned by now. The writer sends exactly once.
@@ -800,6 +833,11 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
finalError = fmt.Sprintf("omp session file: %v", sessionErr)
}
}
+ if cleanupErr != nil {
+ finalStatus = "cleanup_unconfirmed"
+ finalError = fmt.Sprintf("%s process cleanup unconfirmed: %v; background processes may still be running. Check them before manually rerunning this task. %s", label, cleanupErr, finalError)
+ authoritativeTerminal = true
+ }
b.cfg.Logger.Info(label+" finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
// Publish the authoritative terminal boundary before Result. The daemon
@@ -831,6 +869,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
}()
return &Session{
+ CleanupRequired: true,
Messages: msgCh,
Result: resCh,
TerminalObserved: turnErrors.terminalObserved,
diff --git a/server/pkg/agent/pi_cleanup.go b/server/pkg/agent/pi_cleanup.go
new file mode 100644
index 0000000000..46d2edd83f
--- /dev/null
+++ b/server/pkg/agent/pi_cleanup.go
@@ -0,0 +1,165 @@
+package agent
+
+import (
+ "errors"
+ "fmt"
+ "log/slog"
+ "os/exec"
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "time"
+)
+
+const piCleanupBudget = 10 * time.Second
+
+type piProcessTracker interface {
+ snapshot(bool) error
+ signal(syscall.Signal) error
+ remaining() ([]int, error)
+ unobservedTools() bool
+ close()
+}
+
+// piRunCleanup retains descendant identities while the parent still exists.
+// Process groups alone do not own Pi's detached Unix tools. This is bounded,
+// best-effort discovery, not containment of arbitrary double-forking programs.
+type piRunCleanup struct {
+ mu sync.Mutex
+ tracker piProcessTracker
+ err error
+ tools atomic.Int32
+ once sync.Once
+ done chan struct{}
+ stop chan struct{}
+ observed chan struct{}
+ exited chan struct{}
+ finished bool
+ unobserved bool
+}
+
+func newPiRunCleanup(cmd *exec.Cmd) *piRunCleanup {
+ c := &piRunCleanup{tracker: newPiProcessTracker(cmd), done: make(chan struct{}), stop: make(chan struct{}), observed: make(chan struct{}), exited: make(chan struct{})}
+ c.snapshot()
+ go func() {
+ defer close(c.observed)
+ ticker := time.NewTicker(500 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-c.stop:
+ return
+ case <-ticker.C:
+ if c.tools.Load() > 0 {
+ c.snapshot()
+ }
+ if piRuntimeExited(cmd) {
+ close(c.exited)
+ return
+ }
+ }
+ }
+ }()
+ return c
+}
+
+func (c *piRunCleanup) snapshot() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.finished {
+ return
+ }
+ if err := c.tracker.snapshot(c.tools.Load() > 0); err != nil {
+ // Discovery can recover on a later observation. Only the final cleanup
+ // verification may turn this run into an unconfirmed-cleanup failure.
+ slog.Warn("Pi process observation failed; will verify at cleanup", "error", err)
+ }
+}
+
+func (c *piRunCleanup) observe(event string) {
+ switch event {
+ case "tool_execution_start":
+ c.tools.Add(1)
+ c.snapshot()
+ case "tool_execution_end":
+ if c.tools.Load() > 0 {
+ c.tools.Add(-1)
+ }
+ c.snapshot()
+ case "agent_end":
+ c.tools.Store(0)
+ }
+}
+
+// finish joins cancellation, provider-error expiry and interrupted tools.
+// A normal completion releases handles and pipes without signalling processes.
+func (c *piRunCleanup) finish(cmd *exec.Cmd, closeStdin, closePipes func(), grace time.Duration) error {
+ return c.finalize(cmd, closeStdin, closePipes, grace, true)
+}
+
+func (c *piRunCleanup) complete(closeStdin, closePipes func()) error {
+ return c.finalize(nil, closeStdin, closePipes, 0, false)
+}
+
+func (c *piRunCleanup) finalize(cmd *exec.Cmd, closeStdin, closePipes func(), grace time.Duration, terminate bool) error {
+ c.once.Do(func() {
+ defer close(c.done)
+ close(c.stop)
+ <-c.observed
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.finished = true
+ defer c.tracker.close()
+ defer closePipes()
+ closeStdin()
+ if !terminate {
+ return
+ }
+ deadline := time.Now().Add(piCleanupBudget)
+ if err := c.tracker.snapshot(c.tools.Load() > 0); err != nil {
+ slog.Warn("Pi process observation failed before termination", "error", err)
+ }
+ // cmd.Wait has not run yet: the unreaped leader still reserves this
+ // process-group ID. Detached descendants use retained identities below.
+ signalProcessGroup(cmd, syscall.SIGTERM)
+ graceEnd := time.Now().Add(grace)
+ for time.Now().Before(graceEnd) {
+ remaining, err := c.tracker.remaining()
+ if err == nil && len(remaining) == 0 {
+ break
+ }
+ if err := c.tracker.snapshot(c.tools.Load() > 0); err != nil {
+ slog.Warn("Pi process observation failed during termination", "error", err)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ // Re-scan before killing the parent, then stop every retained identity.
+ // Never signal a detached numeric PGID after its leader has exited.
+ c.err = errors.Join(c.err, c.tracker.snapshot(c.tools.Load() > 0))
+ c.unobserved = c.tracker.unobservedTools()
+ signalProcessGroup(cmd, syscall.SIGKILL)
+ signalErr := c.tracker.signal(syscall.SIGKILL)
+ for {
+ remaining, err := c.tracker.remaining()
+ if err != nil {
+ c.err = errors.Join(c.err, signalErr, err)
+ break
+ }
+ if len(remaining) == 0 {
+ // A signal may race exit or exec. A positive final check that
+ // every retained identity exited supersedes that transient error.
+ break
+ }
+ if time.Now().After(deadline) {
+ c.err = errors.Join(c.err, signalErr, fmt.Errorf("processes still active: %v", remaining))
+ break
+ }
+ // A retained Darwin process may exec between identity lookup and
+ // signalling. Retry against its birth identity, never a reused PID.
+ signalErr = c.tracker.signal(syscall.SIGKILL)
+ time.Sleep(20 * time.Millisecond)
+ }
+ })
+ <-c.done
+ return c.err
+}
diff --git a/server/pkg/agent/pi_cleanup_darwin.go b/server/pkg/agent/pi_cleanup_darwin.go
new file mode 100644
index 0000000000..d049f97d95
--- /dev/null
+++ b/server/pkg/agent/pi_cleanup_darwin.go
@@ -0,0 +1,59 @@
+//go:build darwin
+
+package agent
+
+import (
+ "errors"
+ "fmt"
+ "syscall"
+)
+
+type piDarwinProcessIdentity struct {
+ pid int
+ unique uint64
+}
+
+func piProcessMissing(pid int, err error) bool {
+ if errors.Is(err, syscall.ESRCH) {
+ return true
+ }
+ // sysctl returns EIO for a PID that exited between enumeration and lookup.
+ if errors.Is(err, syscall.EIO) {
+ _, identityErr := readCursorDarwinIdentity(pid)
+ return errors.Is(identityErr, syscall.ESRCH)
+ }
+ return false
+}
+
+func capturePiProcessIdentity(info cursorUnixProcessInfo) (piProcessIdentity, error) {
+ identity, err := readCursorDarwinIdentity(info.pid)
+ if err != nil {
+ return nil, err
+ }
+ current, err := readCursorUnixProcessInfo(info.pid)
+ if piProcessMissing(info.pid, err) {
+ return nil, syscall.ESRCH
+ }
+ if err != nil || current.start != info.start {
+ return nil, fmt.Errorf("process identity changed during capture: %d", info.pid)
+ }
+ // Probe the kernel-checked signalling operation; no numeric-PID fallback.
+ if err := signalCursorDarwinIdentity(1<<31-1, 0, syscall.SIGKILL); err != syscall.ESRCH {
+ return nil, fmt.Errorf("kernel process identity signalling is unavailable: %v", err)
+ }
+ return &piDarwinProcessIdentity{pid: info.pid, unique: identity.unique}, nil
+}
+
+func (p *piDarwinProcessIdentity) signal(sig syscall.Signal) error {
+ identity, err := readCursorDarwinIdentity(p.pid)
+ if err != nil {
+ return err
+ }
+ if identity.unique != p.unique {
+ return syscall.ESRCH
+ }
+ // exec changes pidversion but preserves the birth identity. Use the current
+ // version only after proving it is still the process we originally owned.
+ return signalCursorDarwinIdentity(p.pid, identity.version, sig)
+}
+func (*piDarwinProcessIdentity) close() {}
diff --git a/server/pkg/agent/pi_cleanup_exit_other.go b/server/pkg/agent/pi_cleanup_exit_other.go
new file mode 100644
index 0000000000..83b9504227
--- /dev/null
+++ b/server/pkg/agent/pi_cleanup_exit_other.go
@@ -0,0 +1,9 @@
+//go:build !linux && !darwin && !windows
+
+package agent
+
+import "os/exec"
+
+const piCanObserveRuntimeExit = false
+
+func piRuntimeExited(*exec.Cmd) bool { return false }
diff --git a/server/pkg/agent/pi_cleanup_exit_windows.go b/server/pkg/agent/pi_cleanup_exit_windows.go
new file mode 100644
index 0000000000..d8b7cba604
--- /dev/null
+++ b/server/pkg/agent/pi_cleanup_exit_windows.go
@@ -0,0 +1,22 @@
+//go:build windows
+
+package agent
+
+import (
+ "os/exec"
+
+ "golang.org/x/sys/windows"
+)
+
+const piCanObserveRuntimeExit = true
+
+func piRuntimeExited(cmd *exec.Cmd) bool {
+ // exec.Cmd still holds the process handle, preventing PID reuse until Wait.
+ handle, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(cmd.Process.Pid))
+ if err != nil {
+ return false
+ }
+ defer windows.CloseHandle(handle)
+ state, err := windows.WaitForSingleObject(handle, 0)
+ return err == nil && state == windows.WAIT_OBJECT_0
+}
diff --git a/server/pkg/agent/pi_cleanup_linux.go b/server/pkg/agent/pi_cleanup_linux.go
new file mode 100644
index 0000000000..10980d39e2
--- /dev/null
+++ b/server/pkg/agent/pi_cleanup_linux.go
@@ -0,0 +1,39 @@
+//go:build linux
+
+package agent
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "syscall"
+
+ "golang.org/x/sys/unix"
+)
+
+type piLinuxProcessIdentity struct{ fd int }
+
+func piProcessMissing(_ int, err error) bool {
+ return errors.Is(err, syscall.ESRCH) || errors.Is(err, os.ErrNotExist)
+}
+
+func capturePiProcessIdentity(info cursorUnixProcessInfo) (piProcessIdentity, error) {
+ fd, err := unix.PidfdOpen(info.pid, 0)
+ if err != nil {
+ return nil, err
+ }
+ current, err := readCursorUnixProcessInfo(info.pid)
+ if err != nil || current.start != info.start {
+ _ = unix.Close(fd)
+ if piProcessMissing(info.pid, err) {
+ return nil, syscall.ESRCH
+ }
+ return nil, fmt.Errorf("process identity changed during capture: %d", info.pid)
+ }
+ return &piLinuxProcessIdentity{fd: fd}, nil
+}
+
+func (p *piLinuxProcessIdentity) signal(sig syscall.Signal) error {
+ return unix.PidfdSendSignal(p.fd, unix.Signal(sig), nil, 0)
+}
+func (p *piLinuxProcessIdentity) close() { _ = unix.Close(p.fd) }
diff --git a/server/pkg/agent/pi_cleanup_other.go b/server/pkg/agent/pi_cleanup_other.go
new file mode 100644
index 0000000000..82bc622fbf
--- /dev/null
+++ b/server/pkg/agent/pi_cleanup_other.go
@@ -0,0 +1,27 @@
+//go:build !linux && !darwin
+
+package agent
+
+import (
+ "fmt"
+ "os/exec"
+ "syscall"
+)
+
+type piGroupProcessTracker struct{ cmd *exec.Cmd }
+
+func (*piGroupProcessTracker) unobservedTools() bool { return false }
+
+func newPiProcessTracker(cmd *exec.Cmd) piProcessTracker { return &piGroupProcessTracker{cmd: cmd} }
+func (*piGroupProcessTracker) snapshot(bool) error { return nil }
+func (*piGroupProcessTracker) close() {}
+func (p *piGroupProcessTracker) signal(sig syscall.Signal) error {
+ signalProcessGroup(p.cmd, sig)
+ return nil
+}
+func (p *piGroupProcessTracker) remaining() ([]int, error) {
+ if waitProcessGroupGone(p.cmd, 0) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("runtime process-tree cleanup could not be confirmed")
+}
diff --git a/server/pkg/agent/pi_cleanup_test.go b/server/pkg/agent/pi_cleanup_test.go
new file mode 100644
index 0000000000..280a34b190
--- /dev/null
+++ b/server/pkg/agent/pi_cleanup_test.go
@@ -0,0 +1,116 @@
+package agent
+
+import (
+ "errors"
+ "os/exec"
+ "syscall"
+ "testing"
+ "time"
+)
+
+type failedPiProcessTracker struct{ signalled, closed bool }
+
+func (*failedPiProcessTracker) unobservedTools() bool { return false }
+
+func (*failedPiProcessTracker) snapshot(bool) error {
+ return errors.New("cannot inspect process identity")
+}
+func (p *failedPiProcessTracker) signal(syscall.Signal) error { p.signalled = true; return nil }
+func (*failedPiProcessTracker) remaining() ([]int, error) { return nil, nil }
+func (p *failedPiProcessTracker) close() { p.closed = true }
+
+func TestPiCleanupInspectionFailureIsNotSuccess(t *testing.T) {
+ tracker := &failedPiProcessTracker{}
+ observed := make(chan struct{})
+ close(observed)
+ c := &piRunCleanup{tracker: tracker, done: make(chan struct{}), stop: make(chan struct{}), observed: observed}
+ pipesClosed := false
+ err := c.finish(&exec.Cmd{}, func() {}, func() {
+ if !tracker.signalled {
+ t.Error("output pipes released before cleanup finished")
+ }
+ pipesClosed = true
+ }, time.Millisecond)
+ if err == nil || !pipesClosed || !tracker.closed {
+ t.Fatalf("inspection failure was lost: err=%v pipesClosed=%v", err, pipesClosed)
+ }
+}
+
+type recoveringPiProcessTracker struct {
+ failedPiProcessTracker
+ failNext bool
+}
+
+func (p *recoveringPiProcessTracker) snapshot(bool) error {
+ if p.failNext {
+ p.failNext = false
+ return errors.New("temporary process inspection failure")
+ }
+ return nil
+}
+
+func TestPiCleanupObservationFailureCanRecover(t *testing.T) {
+ tracker := &recoveringPiProcessTracker{failNext: true}
+ observed := make(chan struct{})
+ close(observed)
+ c := &piRunCleanup{tracker: tracker, done: make(chan struct{}), stop: make(chan struct{}), observed: observed}
+ c.snapshot() // A failed observation is not proof that final cleanup failed.
+ if err := c.finish(&exec.Cmd{}, func() {}, func() {}, time.Millisecond); err != nil {
+ t.Fatalf("successful final verification retained a transient failure: %v", err)
+ }
+}
+
+func TestPiCleanupNormalCompletionDoesNotSignal(t *testing.T) {
+ // Even an unavailable process-inspection API must not change a successful
+ // run into cleanup_unconfirmed when no cancellation was requested.
+ tracker := &failedPiProcessTracker{}
+ observed := make(chan struct{})
+ close(observed)
+ c := &piRunCleanup{tracker: tracker, done: make(chan struct{}), stop: make(chan struct{}), observed: observed}
+ c.snapshot()
+ if err := c.complete(func() {}, func() {}); err != nil || tracker.signalled || !tracker.closed {
+ t.Fatalf("normal completion: err=%v signalled=%v closed=%v", err, tracker.signalled, tracker.closed)
+ }
+}
+
+type signalRacePiProcessTracker struct {
+ failedPiProcessTracker
+ checksUntilExit int
+ verificationErr error
+}
+
+func (*signalRacePiProcessTracker) snapshot(bool) error { return nil }
+func (*signalRacePiProcessTracker) signal(syscall.Signal) error { return syscall.EPERM }
+func (p *signalRacePiProcessTracker) remaining() ([]int, error) {
+ if p.verificationErr != nil {
+ return nil, p.verificationErr
+ }
+ if p.checksUntilExit > 0 {
+ p.checksUntilExit--
+ return []int{42}, nil
+ }
+ return nil, nil
+}
+
+func TestPiCleanupSignalRaceRequiresFinalVerification(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ checksUntilExit int
+ verificationErr error
+ }{
+ {name: "already exited"},
+ {name: "exec race recovers", checksUntilExit: 2},
+ {name: "cannot verify exit", verificationErr: syscall.EPERM},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tracker := &signalRacePiProcessTracker{checksUntilExit: tc.checksUntilExit, verificationErr: tc.verificationErr}
+ observed := make(chan struct{})
+ close(observed)
+ c := &piRunCleanup{tracker: tracker, done: make(chan struct{}), stop: make(chan struct{}), observed: observed}
+ err := c.finish(&exec.Cmd{}, func() {}, func() {}, 0)
+ if (err != nil) != (tc.verificationErr != nil) {
+ t.Fatalf("cleanup err=%v, verification err=%v", err, tc.verificationErr)
+ }
+ })
+ }
+}
diff --git a/server/pkg/agent/pi_cleanup_unix.go b/server/pkg/agent/pi_cleanup_unix.go
new file mode 100644
index 0000000000..9ea5a4d872
--- /dev/null
+++ b/server/pkg/agent/pi_cleanup_unix.go
@@ -0,0 +1,192 @@
+//go:build linux || darwin
+
+package agent
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "syscall"
+)
+
+type piProcessIdentity interface {
+ signal(syscall.Signal) error
+ close()
+}
+
+type piTrackedProcess struct {
+ info cursorUnixProcessInfo
+ id piProcessIdentity
+}
+
+type piUnixProcessTracker struct {
+ root int
+ known map[int]piTrackedProcess
+ observedDescendants bool
+ toolInFlight bool
+}
+
+func newPiProcessTracker(cmd *exec.Cmd) piProcessTracker {
+ return &piUnixProcessTracker{root: cmd.Process.Pid, known: make(map[int]piTrackedProcess)}
+}
+
+const piCanObserveRuntimeExit = true
+
+func piRuntimeExited(cmd *exec.Cmd) bool {
+ info, err := readCursorUnixProcessInfo(cmd.Process.Pid)
+ return piProcessMissing(cmd.Process.Pid, err) || (err == nil && info.zombie)
+}
+
+func (p *piUnixProcessTracker) unobservedTools() bool { return !p.observedDescendants }
+
+func (p *piUnixProcessTracker) snapshot(toolInFlight bool) error {
+ if toolInFlight != p.toolInFlight {
+ p.observedDescendants = false
+ p.toolInFlight = toolInFlight
+ }
+ all, err := listCursorUnixProcessInfos()
+ if err != nil {
+ return fmt.Errorf("inspect runtime descendants: %w", err)
+ }
+ current := make(map[int]cursorUnixProcessInfo, len(all))
+ owned := make(map[int]bool)
+ for _, info := range all {
+ if info.zombie {
+ continue
+ }
+ current[info.pid] = info
+ if previous, ok := p.known[info.pid]; ok && previous.info.start == info.start {
+ owned[info.pid] = true
+ }
+ }
+ // Release handles for exited incarnations during long runs, rather than
+ // retaining one descriptor for every command the agent ever executed.
+ for pid, previous := range p.known {
+ info, exists := current[pid]
+ if !exists {
+ // Enumeration can omit an inaccessible process. Keep its retained
+ // handle unless a direct identity query proves that it exited.
+ var readErr error
+ info, readErr = readCursorUnixProcessInfo(pid)
+ if readErr != nil && !piProcessMissing(pid, readErr) {
+ return fmt.Errorf("inspect retained process %d: %w", pid, readErr)
+ }
+ exists = readErr == nil && !info.zombie
+ if exists {
+ current[pid] = info
+ if info.start == previous.info.start {
+ owned[pid] = true
+ }
+ }
+ }
+ if !exists || info.start != previous.info.start {
+ previous.id.close()
+ delete(p.known, pid)
+ }
+ }
+ if len(p.known) == 0 {
+ owned[p.root] = true
+ }
+ // Resolve ancestry while it exists, retaining birth identities across
+ // reparenting. A reused PID never becomes an ancestry anchor.
+ for changed := true; changed; {
+ changed = false
+ for _, info := range current {
+ if !owned[info.pid] && owned[info.ppid] {
+ owned[info.pid] = true
+ changed = true
+ }
+ }
+ }
+ var captureErr error
+ for pid := range owned {
+ info, ok := current[pid]
+ if !ok {
+ continue
+ }
+ if prior, ok := p.known[pid]; ok {
+ if prior.info.start == info.start {
+ if toolInFlight && pid != p.root {
+ p.observedDescendants = true
+ }
+ continue
+ }
+ // Retain the original identity; never adopt the replacement.
+ continue
+ }
+ if !p.belongsToRun(info) {
+ continue
+ }
+ identity, err := capturePiProcessIdentity(info)
+ if err != nil {
+ if !errors.Is(err, syscall.ESRCH) && !errors.Is(err, os.ErrNotExist) {
+ captureErr = errors.Join(captureErr, fmt.Errorf("retain process %d: %w", pid, err))
+ }
+ continue
+ }
+ p.known[pid] = piTrackedProcess{info: info, id: identity}
+ if toolInFlight && pid != p.root {
+ p.observedDescendants = true
+ }
+ }
+ return captureErr
+}
+
+// Revalidate the live ancestry before retaining a new identity. Enumeration is
+// not atomic: a parent PID from that snapshot may already have been reused.
+func (p *piUnixProcessTracker) belongsToRun(info cursorUnixProcessInfo) bool {
+ seen := make(map[int]bool)
+ for info.pid > 1 && !seen[info.pid] {
+ if info.pid == p.root {
+ return true // The root is our own, still-unreaped exec.Cmd child.
+ }
+ seen[info.pid] = true
+ parent, err := readCursorUnixProcessInfo(info.ppid)
+ if err != nil || parent.zombie {
+ return false
+ }
+ child, err := readCursorUnixProcessInfo(info.pid)
+ if err != nil || child.start != info.start || child.ppid != parent.pid {
+ return false
+ }
+ if retained, ok := p.known[parent.pid]; ok && retained.info.start == parent.start {
+ return true
+ }
+ info = parent
+ }
+ return false
+}
+
+func (p *piUnixProcessTracker) signal(sig syscall.Signal) error {
+ var result error
+ for pid, proc := range p.known {
+ if err := proc.id.signal(sig); err != nil && !errors.Is(err, syscall.ESRCH) {
+ result = errors.Join(result, fmt.Errorf("signal owned process %d: %w", pid, err))
+ }
+ }
+ return result
+}
+
+func (p *piUnixProcessTracker) remaining() ([]int, error) {
+ var remaining []int
+ for pid, proc := range p.known {
+ current, err := readCursorUnixProcessInfo(pid)
+ if piProcessMissing(pid, err) {
+ continue
+ }
+ if err != nil {
+ return remaining, fmt.Errorf("inspect owned process %d: %w", pid, err)
+ }
+ if current.start == proc.info.start && !current.zombie {
+ remaining = append(remaining, pid)
+ }
+ }
+ return remaining, nil
+}
+
+func (p *piUnixProcessTracker) close() {
+ for _, proc := range p.known {
+ proc.id.close()
+ }
+}
diff --git a/server/pkg/agent/pi_cleanup_unix_test.go b/server/pkg/agent/pi_cleanup_unix_test.go
new file mode 100644
index 0000000000..fbde1e1451
--- /dev/null
+++ b/server/pkg/agent/pi_cleanup_unix_test.go
@@ -0,0 +1,115 @@
+//go:build linux || darwin
+
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestPiCleanupDetachedTool(t *testing.T) {
+ for _, provider := range []string{"pi", "omp"} {
+ for _, mode := range []string{"graceful", "ignore", "exit"} {
+ t.Run(provider+"/"+mode, func(t *testing.T) {
+ t.Parallel()
+ fake, dir, env := testutil.PiCleanupExecutable(t, mode)
+ backend, err := ResolveBackend(provider, Config{ExecutablePath: fake, Env: env, Logger: slog.Default()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ backend.(*piBackend).terminateGrace = 100 * time.Millisecond
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ if err := os.WriteFile(filepath.Join(dir, "session.jsonl"), nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ session, err := backend.Execute(ctx, "test", ExecOptions{Cwd: dir, ResumeSessionID: filepath.Join(dir, "session.jsonl")})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for msg := range session.Messages {
+ if msg.Type == MessageToolUse {
+ break
+ }
+ }
+ // The fixture has already published its PID/PGID before cancel.
+ data, err := os.ReadFile(filepath.Join(dir, "pids.json"))
+ var pids []int
+ if err != nil || json.Unmarshal(data, &pids) != nil || len(pids) != 2 {
+ t.Fatalf("fixture pids=%q err=%v", data, err)
+ }
+ started := time.Now()
+ if mode != "exit" {
+ cancel()
+ }
+ result := waitPiResult(t, session, 4*time.Second)
+ if result.Status == "cleanup_unconfirmed" {
+ t.Fatalf("cleanup failed: %s", result.Error)
+ }
+ if time.Since(started) > 3*time.Second {
+ t.Fatal("cleanup exceeded the bounded handoff")
+ }
+ for _, pid := range pids {
+ waitProcessGone(t, pid)
+ }
+ before, err := os.ReadFile(filepath.Join(dir, "receipt"))
+ if err != nil || len(before) == 0 {
+ t.Fatalf("missing writer receipt: %v", err)
+ }
+ time.Sleep(100 * time.Millisecond)
+ after, _ := os.ReadFile(filepath.Join(dir, "receipt"))
+ if len(before) != len(after) {
+ t.Fatalf("writes continued after Result: %d -> %d", len(before), len(after))
+ }
+ if mode == "graceful" {
+ if _, err := os.Stat(filepath.Join(dir, "term")); err != nil {
+ t.Fatal("Pi never received its graceful-cleanup signal")
+ }
+ }
+ })
+ }
+ }
+}
+
+func TestPiCleanupSuccessfulBackgroundServiceSurvives(t *testing.T) {
+ for _, provider := range []string{"pi", "omp"} {
+ t.Run(provider, func(t *testing.T) {
+ t.Parallel()
+ fake, dir, env := testutil.PiCleanupExecutable(t, "success")
+ backend, err := ResolveBackend(provider, Config{ExecutablePath: fake, Env: env, Logger: slog.Default()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ backend.(*piBackend).terminateGrace = 100 * time.Millisecond
+ sessionFile := filepath.Join(dir, "session.jsonl")
+ if err := os.WriteFile(sessionFile, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ session, err := backend.Execute(context.Background(), "start a background service", ExecOptions{Cwd: dir, ResumeSessionID: sessionFile})
+ if err != nil {
+ t.Fatal(err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ result := waitPiResult(t, session, 4*time.Second)
+ if result.Status != "completed" {
+ t.Fatalf("successful run = %s: %s", result.Status, result.Error)
+ }
+ before, _ := os.ReadFile(filepath.Join(dir, "receipt"))
+ time.Sleep(150 * time.Millisecond)
+ after, _ := os.ReadFile(filepath.Join(dir, "receipt"))
+ if len(after) <= len(before) {
+ t.Fatalf("successful background service stopped at Result: %d -> %d", len(before), len(after))
+ }
+ })
+ }
+}
diff --git a/server/pkg/agent/pi_turn_error_unix_test.go b/server/pkg/agent/pi_turn_error_unix_test.go
index 890f4148a2..bc67c9e278 100644
--- a/server/pkg/agent/pi_turn_error_unix_test.go
+++ b/server/pkg/agent/pi_turn_error_unix_test.go
@@ -94,6 +94,7 @@ func TestPiExecuteTurnErrorGraceClosesStdoutHeldByEscapedDescendant(t *testing.T
}
pi := backend.(*piBackend)
pi.turnErrorGrace = grace
+ pi.terminateGrace = grace
started := time.Now()
session, err := pi.Execute(context.Background(), "prompt-ignored", ExecOptions{
diff --git a/server/pkg/db/generated/supplement.sql.go b/server/pkg/db/generated/supplement.sql.go
index f37d30e01c..6c0a200529 100644
--- a/server/pkg/db/generated/supplement.sql.go
+++ b/server/pkg/db/generated/supplement.sql.go
@@ -728,14 +728,14 @@ WITH candidate AS MATERIALIZED (
SELECT t.id, t.issue_id, r.workspace_id, r.provider
FROM agent_task_queue t
JOIN agent_runtime r ON r.id = t.runtime_id
- WHERE t.id = $1
+ WHERE t.id = $2
AND t.status IN ('dispatched', 'waiting_local_directory')
FOR UPDATE OF t
), capability AS (
INSERT INTO task_supplement_capability (task_id, workspace_id, issue_id, capability)
SELECT id, workspace_id, issue_id, 'task-supplement-v1'
FROM candidate
- WHERE $2::boolean
+ WHERE $3::boolean
AND provider IN ('codex', 'claude', 'grok', 'cursor', 'kiro')
AND issue_id IS NOT NULL
ON CONFLICT DO NOTHING
@@ -745,7 +745,10 @@ UPDATE agent_task_queue t
SET status = 'running',
started_at = now(),
wait_reason = NULL,
- prepare_lease_expires_at = NULL
+ prepare_lease_expires_at = NULL,
+ result = CASE WHEN $1::boolean AND candidate.provider IN ('pi', 'omp')
+ THEN COALESCE(t.result, '{}'::jsonb) || '{"process_cleanup_capability":"pi-process-cleanup-v1"}'::jsonb
+ ELSE t.result END
FROM candidate
WHERE t.id = candidate.id
-- Reference the data-modifying CTE explicitly: capability persistence and
@@ -755,6 +758,7 @@ RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t
`
type StartAgentTaskWithSupplementParams struct {
+ EnableProcessCleanup bool `json:"enable_process_cleanup"`
TaskID pgtype.UUID `json:"task_id"`
EnableTaskSupplement bool `json:"enable_task_supplement"`
}
@@ -763,7 +767,7 @@ type StartAgentTaskWithSupplementParams struct {
// are one state transition. A missing row is the fail-closed value for old
// daemons, old servers, unsupported providers and application rollback.
func (q *Queries) StartAgentTaskWithSupplement(ctx context.Context, arg StartAgentTaskWithSupplementParams) (AgentTaskQueue, error) {
- row := q.db.QueryRow(ctx, startAgentTaskWithSupplement, arg.TaskID, arg.EnableTaskSupplement)
+ row := q.db.QueryRow(ctx, startAgentTaskWithSupplement, arg.EnableProcessCleanup, arg.TaskID, arg.EnableTaskSupplement)
var i AgentTaskQueue
err := row.Scan(
&i.ID,
diff --git a/server/pkg/db/generated/task_cleanup.sql.go b/server/pkg/db/generated/task_cleanup.sql.go
new file mode 100644
index 0000000000..bdb46d17c2
--- /dev/null
+++ b/server/pkg/db/generated/task_cleanup.sql.go
@@ -0,0 +1,187 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: task_cleanup.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const clearTaskProcessCleanupPending = `-- name: ClearTaskProcessCleanupPending :exec
+UPDATE agent_task_queue
+SET result = result - 'process_cleanup_pending'
+WHERE id = $1 AND status IN ('cancelled', 'failed')
+ AND result->>'process_cleanup_pending' = 'true'
+`
+
+func (q *Queries) ClearTaskProcessCleanupPending(ctx context.Context, id pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, clearTaskProcessCleanupPending, id)
+ return err
+}
+
+const failCancelledTaskProcessCleanup = `-- name: FailCancelledTaskProcessCleanup :one
+UPDATE agent_task_queue
+SET status = 'failed',
+ error = concat_ws('; ', NULLIF(error, ''), $1::text),
+ failure_reason = 'cleanup_unconfirmed',
+ completed_at = now(),
+ chat_finalize_deferred_at = NULL
+WHERE id = $2 AND status = 'cancelled'
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
+`
+
+type FailCancelledTaskProcessCleanupParams struct {
+ ErrorMessage string `json:"error_message"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// The daemon's cancellation acknowledgement can discover that local work did
+// NOT stop. Preserve the cancelled run's metadata but surface this as failure.
+// The status CAS makes replay harmless and leaves completed/failed rows alone.
+func (q *Queries) FailCancelledTaskProcessCleanup(ctx context.Context, arg FailCancelledTaskProcessCleanupParams) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, failCancelledTaskProcessCleanup, arg.ErrorMessage, arg.ID)
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.BranchName,
+ &i.DurableWorkDir,
+ &i.ChannelContextRevision,
+ &i.CommentThreadID,
+ &i.CancelledByType,
+ &i.CancelledByID,
+ &i.CancelledByName,
+ &i.IssueSnapshot,
+ &i.WorkflowStep,
+ )
+ return i, err
+}
+
+const markPiTaskProcessCleanupPending = `-- name: MarkPiTaskProcessCleanupPending :exec
+UPDATE agent_task_queue task
+SET result = COALESCE(task.result, '{}'::jsonb) || '{"process_cleanup_pending":true}'::jsonb
+WHERE task.id = $1 AND task.status = 'cancelled' AND task.started_at IS NOT NULL
+ AND task.result->>'process_cleanup_capability' = 'pi-process-cleanup-v1'
+ AND EXISTS (SELECT 1 FROM agent_runtime runtime WHERE runtime.id = task.runtime_id AND runtime.provider IN ('pi', 'omp'))
+`
+
+// Cancellation makes the task terminal before the daemon finishes stopping it.
+// Only a run that negotiated confirmation at start holds a fence until ack.
+func (q *Queries) MarkPiTaskProcessCleanupPending(ctx context.Context, id pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, markPiTaskProcessCleanupPending, id)
+ return err
+}
+
+const taskBlockedByProcessCleanup = `-- name: TaskBlockedByProcessCleanup :one
+SELECT EXISTS (
+ SELECT 1
+ FROM agent_task_queue candidate
+ JOIN LATERAL (
+ SELECT CASE WHEN unsafe.status = 'cancelled'
+ AND unsafe.result->>'process_cleanup_pending' = 'true'
+ THEN unsafe.completed_at + interval '30 seconds'
+ ELSE COALESCE(unsafe.completed_at, unsafe.created_at)
+ END AS completed_at
+ FROM agent_task_queue unsafe
+ WHERE unsafe.agent_id = candidate.agent_id
+ AND unsafe.runtime_id = candidate.runtime_id
+ AND (unsafe.failure_reason = 'cleanup_unconfirmed'
+ OR (unsafe.status = 'cancelled' AND unsafe.result->>'process_cleanup_pending' = 'true'
+ AND unsafe.completed_at <= now() - interval '30 seconds'))
+ ORDER BY unsafe.completed_at DESC, unsafe.id DESC
+ LIMIT 1
+ ) unsafe ON true
+ WHERE candidate.id = $1
+ AND candidate.status IN ('queued', 'dispatched', 'waiting_local_directory')
+ AND NOT EXISTS (
+ SELECT 1 FROM agent_task_queue manual
+ WHERE manual.agent_id = candidate.agent_id
+ AND manual.runtime_id = candidate.runtime_id
+ AND manual.rerun_of_task_id IS NOT NULL
+ AND manual.retry_of_task_id IS NULL
+ AND manual.created_at > unsafe.completed_at
+ AND (manual.id = candidate.id OR manual.status = 'completed')
+ )
+)
+`
+
+// A cleanup failure fences this agent on this runtime, including already queued
+// work and future scheduled runs. Only a NEW explicit manual rerun can cross
+// the fence; its successful completion allows later automated work again.
+// Existing failure and result fields are the durable safety markers.
+func (q *Queries) TaskBlockedByProcessCleanup(ctx context.Context, taskID pgtype.UUID) (bool, error) {
+ row := q.db.QueryRow(ctx, taskBlockedByProcessCleanup, taskID)
+ var exists bool
+ err := row.Scan(&exists)
+ return exists, err
+}
+
+const taskWaitingForProcessCleanup = `-- name: TaskWaitingForProcessCleanup :one
+SELECT EXISTS (
+ SELECT 1 FROM agent_task_queue candidate
+ JOIN agent_task_queue stopping ON stopping.agent_id = candidate.agent_id AND stopping.runtime_id = candidate.runtime_id
+ WHERE candidate.id = $1 AND candidate.status IN ('dispatched', 'waiting_local_directory')
+ AND stopping.status = 'cancelled' AND stopping.result->>'process_cleanup_pending' = 'true'
+ AND stopping.completed_at > now() - interval '30 seconds'
+)
+`
+
+func (q *Queries) TaskWaitingForProcessCleanup(ctx context.Context, id pgtype.UUID) (bool, error) {
+ row := q.db.QueryRow(ctx, taskWaitingForProcessCleanup, id)
+ var exists bool
+ err := row.Scan(&exists)
+ return exists, err
+}
diff --git a/server/pkg/db/queries/supplement.sql b/server/pkg/db/queries/supplement.sql
index a6315493bf..c9f4c5c3b4 100644
--- a/server/pkg/db/queries/supplement.sql
+++ b/server/pkg/db/queries/supplement.sql
@@ -23,7 +23,10 @@ UPDATE agent_task_queue t
SET status = 'running',
started_at = now(),
wait_reason = NULL,
- prepare_lease_expires_at = NULL
+ prepare_lease_expires_at = NULL,
+ result = CASE WHEN @enable_process_cleanup::boolean AND candidate.provider IN ('pi', 'omp')
+ THEN COALESCE(t.result, '{}'::jsonb) || '{"process_cleanup_capability":"pi-process-cleanup-v1"}'::jsonb
+ ELSE t.result END
FROM candidate
WHERE t.id = candidate.id
-- Reference the data-modifying CTE explicitly: capability persistence and
diff --git a/server/pkg/db/queries/task_cleanup.sql b/server/pkg/db/queries/task_cleanup.sql
new file mode 100644
index 0000000000..d3d01d68a0
--- /dev/null
+++ b/server/pkg/db/queries/task_cleanup.sql
@@ -0,0 +1,72 @@
+-- name: TaskBlockedByProcessCleanup :one
+-- A cleanup failure fences this agent on this runtime, including already queued
+-- work and future scheduled runs. Only a NEW explicit manual rerun can cross
+-- the fence; its successful completion allows later automated work again.
+-- Existing failure and result fields are the durable safety markers.
+SELECT EXISTS (
+ SELECT 1
+ FROM agent_task_queue candidate
+ JOIN LATERAL (
+ SELECT CASE WHEN unsafe.status = 'cancelled'
+ AND unsafe.result->>'process_cleanup_pending' = 'true'
+ THEN unsafe.completed_at + interval '30 seconds'
+ ELSE COALESCE(unsafe.completed_at, unsafe.created_at)
+ END AS completed_at
+ FROM agent_task_queue unsafe
+ WHERE unsafe.agent_id = candidate.agent_id
+ AND unsafe.runtime_id = candidate.runtime_id
+ AND (unsafe.failure_reason = 'cleanup_unconfirmed'
+ OR (unsafe.status = 'cancelled' AND unsafe.result->>'process_cleanup_pending' = 'true'
+ AND unsafe.completed_at <= now() - interval '30 seconds'))
+ ORDER BY unsafe.completed_at DESC, unsafe.id DESC
+ LIMIT 1
+ ) unsafe ON true
+ WHERE candidate.id = @task_id
+ AND candidate.status IN ('queued', 'dispatched', 'waiting_local_directory')
+ AND NOT EXISTS (
+ SELECT 1 FROM agent_task_queue manual
+ WHERE manual.agent_id = candidate.agent_id
+ AND manual.runtime_id = candidate.runtime_id
+ AND manual.rerun_of_task_id IS NOT NULL
+ AND manual.retry_of_task_id IS NULL
+ AND manual.created_at > unsafe.completed_at
+ AND (manual.id = candidate.id OR manual.status = 'completed')
+ )
+);
+
+-- name: FailCancelledTaskProcessCleanup :one
+-- The daemon's cancellation acknowledgement can discover that local work did
+-- NOT stop. Preserve the cancelled run's metadata but surface this as failure.
+-- The status CAS makes replay harmless and leaves completed/failed rows alone.
+UPDATE agent_task_queue
+SET status = 'failed',
+ error = concat_ws('; ', NULLIF(error, ''), @error_message::text),
+ failure_reason = 'cleanup_unconfirmed',
+ completed_at = now(),
+ chat_finalize_deferred_at = NULL
+WHERE id = @id AND status = 'cancelled'
+RETURNING *;
+
+-- name: MarkPiTaskProcessCleanupPending :exec
+-- Cancellation makes the task terminal before the daemon finishes stopping it.
+-- Only a run that negotiated confirmation at start holds a fence until ack.
+UPDATE agent_task_queue task
+SET result = COALESCE(task.result, '{}'::jsonb) || '{"process_cleanup_pending":true}'::jsonb
+WHERE task.id = @id AND task.status = 'cancelled' AND task.started_at IS NOT NULL
+ AND task.result->>'process_cleanup_capability' = 'pi-process-cleanup-v1'
+ AND EXISTS (SELECT 1 FROM agent_runtime runtime WHERE runtime.id = task.runtime_id AND runtime.provider IN ('pi', 'omp'));
+
+-- name: ClearTaskProcessCleanupPending :exec
+UPDATE agent_task_queue
+SET result = result - 'process_cleanup_pending'
+WHERE id = @id AND status IN ('cancelled', 'failed')
+ AND result->>'process_cleanup_pending' = 'true';
+
+-- name: TaskWaitingForProcessCleanup :one
+SELECT EXISTS (
+ SELECT 1 FROM agent_task_queue candidate
+ JOIN agent_task_queue stopping ON stopping.agent_id = candidate.agent_id AND stopping.runtime_id = candidate.runtime_id
+ WHERE candidate.id = @id AND candidate.status IN ('dispatched', 'waiting_local_directory')
+ AND stopping.status = 'cancelled' AND stopping.result->>'process_cleanup_pending' = 'true'
+ AND stopping.completed_at > now() - interval '30 seconds'
+);
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 07e8f624d0..00c09e0bd2 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -71,6 +71,10 @@ const (
// It is persisted when this exact task enters running; absence always means
// unsupported so mixed server/daemon versions fail closed.
DaemonCapabilityTaskSupplementV1 = "task-supplement-v1"
+ // DaemonCapabilityPiProcessCleanupV1 promises that this Pi/omp run joins
+ // descendant cleanup and explicitly confirms its cancellation outcome.
+ // Persist only at start; old daemons must retain their cancellation contract.
+ DaemonCapabilityPiProcessCleanupV1 = "pi-process-cleanup-v1"
// DaemonCapabilityWorkflowStatusRulesV1 advertises that the daemon's
// runtime brief drops its built-in in_progress / in_review rules for an
// issue whose claim carries a project workflow (MUL-8145). Only then may
diff --git a/server/pkg/taskfailure/failure.go b/server/pkg/taskfailure/failure.go
index 530f275b9f..09399eae46 100644
--- a/server/pkg/taskfailure/failure.go
+++ b/server/pkg/taskfailure/failure.go
@@ -93,6 +93,12 @@ const (
// agent timeout path.
ReasonTimeout Reason = "timeout"
+ // Process cleanup is a separate, non-retryable failure even when the
+ // provider succeeded or the user cancelled. Blocked successors do not
+ // create a new cleanup obligation of their own.
+ ReasonProcessCleanupUnconfirmed Reason = "cleanup_unconfirmed"
+ ReasonProcessCleanupBlocked Reason = "cleanup_blocked"
+
// ReasonIterationLimit: the agent reached its per-run iteration
// cap and emitted a fallback "I reached the iteration limit"
// message. Treated as platform-side because it is a Multica-imposed
@@ -288,6 +294,8 @@ var allReasons = []Reason{
ReasonRuntimeReconnectTimeout,
ReasonRuntimeRecovery,
ReasonTimeout,
+ ReasonProcessCleanupUnconfirmed,
+ ReasonProcessCleanupBlocked,
ReasonIterationLimit,
ReasonAgentBlocked,
ReasonAPIInvalidRequest,