Skip to content

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

Go

fix(sweeper): gate running-task wall clock on runtime liveness (MUL-4107) (#4978)

Multica Evea69d969fb182
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index 87b4b17c47..f08c8db09c 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -37,11 +37,19 @@ const (
// means something went wrong (e.g. StartTask API call failed silently).
dispatchTimeoutSeconds = 300.0
// runningTimeoutSeconds fails tasks stuck in 'running' beyond this. It is a
- // coarse server-side backstop keyed on started_at (it does NOT look at task
- // activity) — mainly for runs whose daemon died without reporting. The
- // daemon itself decides stuck-vs-long-running by activity (idle/tool
- // watchdog), so this only needs to sit generously above any realistic single
- // run rather than track a per-run wall-clock cap (MUL-3064).
+ // coarse server-side backstop keyed on started_at, AND-gated by daemon
+ // liveness (agent_runtime.last_seen_at freshness within
+ // staleThresholdSeconds): a running task whose runtime is still
+ // heartbeating is NEVER killed by this wall clock, even after the timeout
+ // elapses. This is what lets healthy multi-hour research / training runs
+ // survive on self-hosted deployments (MUL-4107) — the daemon itself
+ // decides stuck-vs-long-running via its inactivity watchdogs (idle/tool),
+ // so the server-side wall clock is only a defensive backstop for the
+ // pathological case where a runtime row somehow retains status='online'
+ // with a stale DB heartbeat for longer than this timeout. The primary
+ // "daemon died" path is `sweepStaleRuntimes` in the same tick (Redis
+ // liveness + DB stale + FailTasksForOfflineRuntimes), which typically
+ // reclaims orphaned tasks within ~180s.
runningTimeoutSeconds = 9000.0
// queuedTTLSeconds expires tasks that have been sitting in 'queued'
// for longer than this without ever being claimed. This is the cleanup
@@ -239,14 +247,25 @@ func gcRuntimes(ctx context.Context, queries *db.Queries, bus *events.Bus) {
}
// sweepStaleTasks fails tasks stuck in dispatched/running for too long,
-// even when the runtime is still online. This handles cases where:
-// - The agent process hangs and the daemon is still heartbeating
-// - The daemon failed to report task completion/failure
-// - A server restart left tasks in a non-terminal state
+// even when the runtime is still online at the row level. Each branch pairs
+// the wall clock with a task-appropriate liveness signal so healthy long
+// runs are preserved:
+// - dispatched: excludes rows with an active prepare_lease (renewed by
+// the daemon between claim and StartTask).
+// - running: excludes rows whose runtime is 'online' with a fresh
+// last_seen_at (renewed by the daemon heartbeat ~every 15s).
+//
+// The daemon-dead case is primarily handled upstream by sweepStaleRuntimes
+// in the same tick; this function is a defensive backstop for the residual
+// edge where a runtime row lingers online-with-stale-heartbeat past the
+// wall clock (MUL-4107).
func sweepStaleTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, bus *events.Bus) {
failedTasks, err := queries.FailStaleTasks(ctx, db.FailStaleTasksParams{
DispatchTimeoutSecs: dispatchTimeoutSeconds,
RunningTimeoutSecs: runningTimeoutSeconds,
+ // Reuse the runtime stale window so the running-task backstop
+ // exactly matches what sweepStaleRuntimes considers "not alive".
+ RuntimeStaleSecs: staleThresholdSeconds,
})
if err != nil {
slog.Warn("task sweeper: failed to clean up stale tasks", "error", err)
diff --git a/server/cmd/server/runtime_sweeper_test.go b/server/cmd/server/runtime_sweeper_test.go
index 45d8cfa2a7..050bd33e96 100644
--- a/server/cmd/server/runtime_sweeper_test.go
+++ b/server/cmd/server/runtime_sweeper_test.go
@@ -5,6 +5,7 @@ import (
"strings"
"sync"
"testing"
+ "time"
"github.com/multica-ai/multica/server/internal/events"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -78,6 +79,30 @@ func cleanupSweeperFixture(t *testing.T, issueID, agentID string) {
testPool.Exec(ctx, `UPDATE agent SET status = 'idle' WHERE id = $1`, agentID)
}
+// ageOutAgentRuntime marks the agent's runtime as stale — old last_seen_at —
+// so the runtime-liveness gate on the running-task sweep predicate
+// (agent_runtime.last_seen_at within staleThresholdSeconds) does NOT protect
+// the test task from being killed by the wall clock. Register a cleanup that
+// restores last_seen_at so subsequent tests re-using this runtime see it as
+// fresh. Callers pass a `staleAgo` well beyond staleThresholdSeconds so tests
+// are insensitive to that constant's precise value.
+func ageOutAgentRuntime(t *testing.T, agentID string, staleAgo time.Duration) {
+ t.Helper()
+ ctx := context.Background()
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_runtime SET last_seen_at = now() - make_interval(secs => $1)
+ WHERE id = (SELECT runtime_id FROM agent WHERE id = $2)
+ `, staleAgo.Seconds(), agentID); err != nil {
+ t.Fatalf("failed to age out agent runtime: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `
+ UPDATE agent_runtime SET last_seen_at = now()
+ WHERE id = (SELECT runtime_id FROM agent WHERE id = $1)
+ `, agentID)
+ })
+}
+
func TestRefreshAgentStatusFromTasks(t *testing.T) {
if testPool == nil {
t.Skip("no database connection")
@@ -132,6 +157,10 @@ func TestSweepStaleTasksBroadcastsWithWorkspaceID(t *testing.T) {
issueID, agentID, taskID := setupSweeperTestFixture(t, "running")
t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })
+ // The running-task sweep now requires the task's runtime to be NOT
+ // heartbeating (MUL-4107). Age the runtime out so this test still
+ // exercises the sweeper wall clock rather than being silently skipped.
+ ageOutAgentRuntime(t, agentID, 10*time.Minute)
queries := db.New(testPool)
bus := events.New()
@@ -149,6 +178,7 @@ func TestSweepStaleTasksBroadcastsWithWorkspaceID(t *testing.T) {
failedTasks, err := queries.FailStaleTasks(context.Background(), db.FailStaleTasksParams{
DispatchTimeoutSecs: 300.0,
RunningTimeoutSecs: 1.0, // 1 second — our task is 3 hours old
+ RuntimeStaleSecs: staleThresholdSeconds,
})
if err != nil {
t.Fatalf("FailStaleTasks query failed: %v", err)
@@ -213,6 +243,8 @@ func TestSweepStaleTasksReconcileAgentStatus(t *testing.T) {
issueID, agentID, _ := setupSweeperTestFixture(t, "running")
t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })
+ // Runtime must be stale for the running-task wall clock to fire (MUL-4107).
+ ageOutAgentRuntime(t, agentID, 10*time.Minute)
queries := db.New(testPool)
bus := events.New()
@@ -230,6 +262,7 @@ func TestSweepStaleTasksReconcileAgentStatus(t *testing.T) {
failedTasks, err := queries.FailStaleTasks(context.Background(), db.FailStaleTasksParams{
DispatchTimeoutSecs: 300.0,
RunningTimeoutSecs: 1.0,
+ RuntimeStaleSecs: staleThresholdSeconds,
})
if err != nil {
t.Fatalf("FailStaleTasks failed: %v", err)
@@ -291,6 +324,9 @@ func TestSweepDispatchedStaleTask(t *testing.T) {
failedTasks, err := queries.FailStaleTasks(context.Background(), db.FailStaleTasksParams{
DispatchTimeoutSecs: 1.0,
RunningTimeoutSecs: 9000.0,
+ // RuntimeStaleSecs only affects the running branch — irrelevant for
+ // this dispatched-timeout test, but wired for API consistency.
+ RuntimeStaleSecs: staleThresholdSeconds,
})
if err != nil {
t.Fatalf("FailStaleTasks failed: %v", err)
@@ -343,6 +379,98 @@ func TestSweepDispatchedStaleTask(t *testing.T) {
}
}
+// TestSweepRunningTaskSkippedWhenRuntimeFresh is the MUL-4107 regression test:
+// a running task whose wall-clock deadline has already passed MUST NOT be
+// killed by the sweeper as long as its owning runtime is 'online' and its
+// last_seen_at is within the runtime stale window. This preserves healthy
+// multi-hour research / training runs — the primary motivation for the
+// liveness-keyed sweep predicate.
+func TestSweepRunningTaskSkippedWhenRuntimeFresh(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+
+ issueID, agentID, taskID := setupSweeperTestFixture(t, "running")
+ t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })
+
+ // Runtime heartbeat is fresh (integration fixture inserts last_seen_at=now()).
+ // Task started_at is 3h ago; RunningTimeoutSecs=1s would kill on wall clock
+ // alone — but the runtime is proving liveness, so the sweeper must skip it.
+ queries := db.New(testPool)
+ failedTasks, err := queries.FailStaleTasks(context.Background(), db.FailStaleTasksParams{
+ DispatchTimeoutSecs: 300.0,
+ RunningTimeoutSecs: 1.0,
+ RuntimeStaleSecs: staleThresholdSeconds,
+ })
+ if err != nil {
+ t.Fatalf("FailStaleTasks failed: %v", err)
+ }
+
+ for _, ft := range failedTasks {
+ if ft.ID.Bytes == parseUUIDBytes(taskID) {
+ t.Fatalf("healthy long-running task on live daemon must NOT be swept — that was the MUL-4107 bug")
+ }
+ }
+
+ var status string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT status FROM agent_task_queue WHERE id = $1`, taskID,
+ ).Scan(&status); err != nil {
+ t.Fatalf("failed to query task status: %v", err)
+ }
+ if status != "running" {
+ t.Fatalf("expected task to stay 'running', got %q", status)
+ }
+}
+
+// TestSweepRunningTaskKilledWhenRuntimeStale is the companion coverage: with
+// the same wall-clock deadline elapsed, a running task IS killed when its
+// runtime's DB heartbeat is stale (simulates the "runtime lingers online
+// with a stale heartbeat past the wall clock" pathological case that the
+// wall-clock branch is the defensive backstop for). Note that in production
+// the daemon-dead case is normally reclaimed sooner by sweepStaleRuntimes;
+// this test asserts the residual backstop still fires when it needs to.
+func TestSweepRunningTaskKilledWhenRuntimeStale(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+
+ issueID, agentID, taskID := setupSweeperTestFixture(t, "running")
+ t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })
+ ageOutAgentRuntime(t, agentID, 10*time.Minute)
+
+ queries := db.New(testPool)
+ failedTasks, err := queries.FailStaleTasks(context.Background(), db.FailStaleTasksParams{
+ DispatchTimeoutSecs: 300.0,
+ RunningTimeoutSecs: 1.0,
+ RuntimeStaleSecs: staleThresholdSeconds,
+ })
+ if err != nil {
+ t.Fatalf("FailStaleTasks failed: %v", err)
+ }
+
+ found := false
+ for _, ft := range failedTasks {
+ if ft.ID.Bytes == parseUUIDBytes(taskID) {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("expected wall clock to fire when runtime heartbeat is stale, but task %s was not swept", taskID)
+ }
+
+ var status string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT status FROM agent_task_queue WHERE id = $1`, taskID,
+ ).Scan(&status); err != nil {
+ t.Fatalf("failed to query task status: %v", err)
+ }
+ if status != "failed" {
+ t.Fatalf("expected task status 'failed', got %q", status)
+ }
+}
+
// TestSweepResetsInProgressIssueToTodo verifies the core fix: when the sweeper
// force-fails a stale task whose issue is still in_progress (because the daemon
// crashed mid-run), the issue is reset back to todo so the daemon can re-queue it.
@@ -399,10 +527,14 @@ func TestSweepResetsInProgressIssueToTodo(t *testing.T) {
queries := db.New(testPool)
bus := events.New()
+ // Runtime must be stale for the running-task wall clock to fire (MUL-4107).
+ ageOutAgentRuntime(t, agentID, 10*time.Minute)
+
// Fail the stale task (running timeout of 1 second — our task is 3 hours old).
failedTasks, err := queries.FailStaleTasks(ctx, db.FailStaleTasksParams{
DispatchTimeoutSecs: 300.0,
RunningTimeoutSecs: 1.0,
+ RuntimeStaleSecs: staleThresholdSeconds,
})
if err != nil {
t.Fatalf("FailStaleTasks failed: %v", err)
@@ -484,9 +616,13 @@ func TestSweepDoesNotResetIssueAlreadyInReview(t *testing.T) {
queries := db.New(testPool)
bus := events.New()
+ // Runtime must be stale for the running-task wall clock to fire (MUL-4107).
+ ageOutAgentRuntime(t, agentID, 10*time.Minute)
+
failedTasks, err := queries.FailStaleTasks(ctx, db.FailStaleTasksParams{
DispatchTimeoutSecs: 300.0,
RunningTimeoutSecs: 1.0,
+ RuntimeStaleSecs: staleThresholdSeconds,
})
if err != nil {
t.Fatalf("FailStaleTasks failed: %v", err)
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index c84f9c7828..4b6f4c8356 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -1746,28 +1746,64 @@ WHERE (
AND dispatched_at < now() - make_interval(secs => $1::double precision)
AND (prepare_lease_expires_at IS NULL OR prepare_lease_expires_at < now())
)
- OR (status = 'running' AND started_at < now() - make_interval(secs => $2::double precision))
+ OR (
+ status = 'running'
+ AND started_at < now() - make_interval(secs => $2::double precision)
+ AND NOT EXISTS (
+ SELECT 1 FROM agent_runtime r
+ WHERE r.id = agent_task_queue.runtime_id
+ AND r.status = 'online'
+ AND r.last_seen_at >= now() - make_interval(secs => $3::double precision)
+ )
+ )
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
`
type FailStaleTasksParams struct {
DispatchTimeoutSecs float64 `json:"dispatch_timeout_secs"`
RunningTimeoutSecs float64 `json:"running_timeout_secs"`
+ RuntimeStaleSecs float64 `json:"runtime_stale_secs"`
}
// Fails tasks stuck in dispatched/running beyond the given thresholds.
-// Handles cases where the daemon is alive but the task is orphaned
-// (e.g. agent process hung, daemon failed to report completion).
-// Dispatched tasks with an active prepare lease are excluded because the
-// daemon is still proving liveness while resolving/cache/preparing startup
-// inputs before StartTask.
+//
+// Each branch pairs a wall-clock deadline with a task-appropriate liveness
+// signal, so the sweeper only kills tasks whose owning daemon is no longer
+// proving it is alive:
+//
+// - Dispatched: `prepare_lease_expires_at` is refreshed every 15s by the
+// daemon between claim and StartTask (see startTaskPrepareLeaseExtender).
+// A live lease excludes the row.
+//
+// - Running: no per-task lease is renewed once StartTask fires, so we key
+// off the daemon-wide heartbeat instead — `agent_runtime.last_seen_at`,
+// which the daemon bumps every ~15s while it is up. A running task whose
+// runtime is `online` AND whose `last_seen_at` is within
+// @runtime_stale_secs is treated as alive and is NOT killed by this
+// wall-clock backstop, even after `started_at` exceeds the running
+// timeout. This is what lets healthy multi-hour research / training runs
+// survive on self-hosted deployments (MUL-4107): the daemon side is
+// bounded only by inactivity watchdogs (idle / per-tool), so the
+// server-side wall clock must not shadow that with a coarser cap.
+//
+// The daemon-dead case is the primary responsibility of `sweepStaleRuntimes`
+// (which mixes DB `last_seen_at` with the Redis LivenessStore and calls
+// `FailTasksForOfflineRuntimes` in the same tick). The wall-clock branch
+// here is a defensive backstop for pathological cases where a runtime row
+// somehow retains status='online' with a stale DB heartbeat for longer than
+// the wall clock allows.
+//
+// runtime_id IS NULL: a running row with no runtime is by definition not
+// proving liveness, so the wall clock is allowed to fire — same shape as
+// the legacy pure-wall-clock behavior for that (rare / historical) case.
+//
// waiting_local_directory rows are intentionally excluded: the daemon owns
// the wait (with its own ctx-driven timeout) and a legitimate queue ahead
// of this task can exceed the dispatch / running timeouts without being
// "stuck". If the daemon dies, RecoverOrphanedTasksForRuntime reclaims
// those rows at restart.
func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams) ([]AgentTaskQueue, error) {
- rows, err := q.db.Query(ctx, failStaleTasks, arg.DispatchTimeoutSecs, arg.RunningTimeoutSecs)
+ rows, err := q.db.Query(ctx, failStaleTasks, arg.DispatchTimeoutSecs, arg.RunningTimeoutSecs, arg.RuntimeStaleSecs)
if err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 07c998ba1f..c6a62a31bf 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -568,11 +568,37 @@ RETURNING *;
-- name: FailStaleTasks :many
-- Fails tasks stuck in dispatched/running beyond the given thresholds.
--- Handles cases where the daemon is alive but the task is orphaned
--- (e.g. agent process hung, daemon failed to report completion).
--- Dispatched tasks with an active prepare lease are excluded because the
--- daemon is still proving liveness while resolving/cache/preparing startup
--- inputs before StartTask.
+--
+-- Each branch pairs a wall-clock deadline with a task-appropriate liveness
+-- signal, so the sweeper only kills tasks whose owning daemon is no longer
+-- proving it is alive:
+--
+-- * Dispatched: `prepare_lease_expires_at` is refreshed every 15s by the
+-- daemon between claim and StartTask (see startTaskPrepareLeaseExtender).
+-- A live lease excludes the row.
+--
+-- * Running: no per-task lease is renewed once StartTask fires, so we key
+-- off the daemon-wide heartbeat instead — `agent_runtime.last_seen_at`,
+-- which the daemon bumps every ~15s while it is up. A running task whose
+-- runtime is `online` AND whose `last_seen_at` is within
+-- @runtime_stale_secs is treated as alive and is NOT killed by this
+-- wall-clock backstop, even after `started_at` exceeds the running
+-- timeout. This is what lets healthy multi-hour research / training runs
+-- survive on self-hosted deployments (MUL-4107): the daemon side is
+-- bounded only by inactivity watchdogs (idle / per-tool), so the
+-- server-side wall clock must not shadow that with a coarser cap.
+--
+-- The daemon-dead case is the primary responsibility of `sweepStaleRuntimes`
+-- (which mixes DB `last_seen_at` with the Redis LivenessStore and calls
+-- `FailTasksForOfflineRuntimes` in the same tick). The wall-clock branch
+-- here is a defensive backstop for pathological cases where a runtime row
+-- somehow retains status='online' with a stale DB heartbeat for longer than
+-- the wall clock allows.
+--
+-- runtime_id IS NULL: a running row with no runtime is by definition not
+-- proving liveness, so the wall clock is allowed to fire — same shape as
+-- the legacy pure-wall-clock behavior for that (rare / historical) case.
+--
-- waiting_local_directory rows are intentionally excluded: the daemon owns
-- the wait (with its own ctx-driven timeout) and a legitimate queue ahead
-- of this task can exceed the dispatch / running timeouts without being
@@ -587,7 +613,16 @@ WHERE (
AND dispatched_at < now() - make_interval(secs => @dispatch_timeout_secs::double precision)
AND (prepare_lease_expires_at IS NULL OR prepare_lease_expires_at < now())
)
- OR (status = 'running' AND started_at < now() - make_interval(secs => @running_timeout_secs::double precision))
+ OR (
+ status = 'running'
+ AND started_at < now() - make_interval(secs => @running_timeout_secs::double precision)
+ AND NOT EXISTS (
+ SELECT 1 FROM agent_runtime r
+ WHERE r.id = agent_task_queue.runtime_id
+ AND r.status = 'online'
+ AND r.last_seen_at >= now() - make_interval(secs => @runtime_stale_secs::double precision)
+ )
+ )
RETURNING *;
-- name: ExpireStaleQueuedTasks :many