Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8188: fail fast on Kiro panic and stop resuming undrivable sessions (#9458)
Multica Eve79d801f45c1f
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 3095522259..35a6e32958 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -555,6 +555,10 @@ type TaskCancelAck struct {// swallow it entirely.ErrorMessage stringFailureReason string+ // RetiredSessionID: a resumed session this run produced no output on+ // before the cancel landed, or one a fresh-session retry abandoned. The+ // server retires it so later triggers start fresh (MUL-8188).+ RetiredSessionID string}// AckTaskCancelled tells the server this daemon observed the task's@@ -581,6 +585,9 @@ func (c *Client) AckTaskCancelled(ctx context.Context, taskID string, ack TaskCaif ack.FailureReason != "" {body["failure_reason"] = ack.FailureReason}+ if ack.RetiredSessionID != "" {+ body["retired_session_id"] = ack.RetiredSessionID+ }return c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/cancel-ack", taskID), body, nil, defaultTerminalRetrySchedule)}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 8c7f9afc3e..a4333da199 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -5819,7 +5819,10 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {// run errors stay discarded: on a cancelled run they are expected// noise (context canceled, killed process), and persisting them would// stamp a bogus reason on every ordinary mid-run cancel.- ack := TaskCancelAck{BranchName: result.BranchName, DurableWorkDir: result.DurableWorkDir}+ // 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 *worktreePreservedErrorif errors.As(err, &preserved) {ack.ErrorMessage = preserved.Error()@@ -5874,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}); ackErr != nil {+ if ackErr := d.client.AckTaskCancelled(ctx, task.ID, TaskCancelAck{BranchName: result.BranchName, DurableWorkDir: result.DurableWorkDir, RetiredSessionID: result.RetiredSessionID}); ackErr != nil {taskLog.Warn("cancel ack failed; server sweeper will finalize", "error", ackErr)}return@@ -8789,6 +8792,8 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// keep ascending seq values for the same task.var msgSeq atomic.Int32d.reportThinkingLevelWarning(ctx, task.ID, selection.ThinkingLevelWarning, &msgSeq, taskLog)+ outputObserver := &taskOutputObserver{}+ ctx = withTaskOutputObserver(ctx, outputObserver)result, tools, err := d.executeAndDrain(ctx, backend, prompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)if err != nil {return TaskResult{}, err@@ -8875,6 +8880,21 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i}phaseRecorder.Mark(taskPhaseTurnCompleted)+ // MUL-8188: a resumed run that was cancelled after minutes of total+ // silence resumed a session the runtime cannot drive. Retire it so the+ // next trigger starts fresh instead of re-entering the same hang; the+ // cancel-ack (or the fail callback on daemon shutdown) carries it.+ if retiredSessionID == "" {+ silent, wasSilent := outputObserver.silentFor()+ if shouldRetireSilentResume(result.Status, task.PriorSessionID, silent, wasSilent) {+ taskLog.Warn("resumed session produced no output before cancellation; retiring it so the next run starts fresh",+ "session_id", task.PriorSessionID,+ "silent_for", silent.Round(time.Second).String(),+ )+ retiredSessionID = task.PriorSessionID+ }+ }+elapsed := time.Since(taskStart).Round(time.Second)taskLog.Info("agent finished","status", result.Status,@@ -9401,6 +9421,8 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, prod.runningTasks.Add(1)defer d.runningTasks.Add(-1)phaseRecorder.Mark(taskPhaseRuntimeStarted)+ outputObserver := taskOutputObserverFromContext(ctx)+ outputObserver.begin()taskLog.Debug("backend started, draining messages")// Only negotiated sessions may claim additions. Stop and join delivery@@ -9620,6 +9642,7 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro}if isTaskOutputReceived(msg) {phaseRecorder.Mark(taskPhaseFirstOutputReceived)+ outputObserver.markOutput()}if isTaskToolUse(msg) {phaseRecorder.Mark(taskPhaseFirstToolUse)diff --git a/server/internal/daemon/task_output_observer.go b/server/internal/daemon/task_output_observer.gonew file mode 100644index 0000000000..5e015bea1d--- /dev/null+++ b/server/internal/daemon/task_output_observer.go@@ -0,0 +1,129 @@+package daemon++import (+ "context"+ "sync"+ "time"++ "github.com/multica-ai/multica/server/pkg/awakeclock"+)++// silentResumeRetireThreshold is how long a RESUMED run must have gone without+// a single agent message before a cancellation retires its session.+//+// A healthy resumed turn produces its first thinking/text/tool event within+// seconds; minutes of total silence after a resume means the runtime loaded+// the transcript and then could not drive it — the MUL-8188 shape, where Kiro+// panicked in its agent loop and left session/prompt unanswered. Users cancel+// such runs by hand, and before this the cancelled row kept the session+// resumable, so every later trigger re-entered the same hang.+//+// The threshold keeps an ordinary early cancel ("wrong issue", "let me edit+// the prompt") from discarding a healthy conversation: those land well before+// it. The cost of a false positive is bounded — the next run starts a fresh+// session in the same workdir — while a false negative is an issue that hangs+// on every trigger.+const silentResumeRetireThreshold = 5 * time.Minute++// taskOutputObserver records, for the most recent backend execution of a task,+// when it started and whether it produced any agent output. Unlike+// taskPhaseRecorder (diagnostic-only by contract) it exists to drive the+// silent-resume retirement decision.+//+// Silence is measured on awakeclock, not wall time: a laptop that suspends+// right after a resume and is woken and cancelled later must not have its slept+// time counted as the session failing to answer — on Windows Go's monotonic+// clock keeps counting through sleep, which would permanently retire a healthy+// conversation. Same reasoning as the idle watchdog (MUL-7851 / #9201).+type taskOutputObserver struct {+ // clock returns awake-time readings; nil means awakeclock.Now. Tests+ // inject a fake to simulate host suspend.+ clock func() time.Duration++ mu sync.Mutex+ started time.Duration+ begun bool+ observed bool+}++func (o *taskOutputObserver) now() time.Duration {+ if o.clock != nil {+ return o.clock()+ }+ return awakeclock.Now()+}++// begin marks the start of a backend execution. Each execution (including a+// fresh-session retry) resets the observation so the decision always concerns+// the run whose result is being classified.+func (o *taskOutputObserver) begin() {+ if o == nil {+ return+ }+ now := o.now()+ o.mu.Lock()+ o.started = now+ o.begun = true+ o.observed = false+ o.mu.Unlock()+}++func (o *taskOutputObserver) markOutput() {+ if o == nil {+ return+ }+ o.mu.Lock()+ o.observed = true+ o.mu.Unlock()+}++// silentFor reports how much AWAKE time the current execution has run+// without output. ok is false when the execution never started or did+// produce output.+func (o *taskOutputObserver) silentFor() (time.Duration, bool) {+ if o == nil {+ return 0, false+ }+ now := o.now()+ o.mu.Lock()+ defer o.mu.Unlock()+ if !o.begun || o.observed {+ return 0, false+ }+ silent := now - o.started+ if silent < 0 {+ silent = 0+ }+ return silent, true+}++type taskOutputObserverContextKey struct{}++func withTaskOutputObserver(ctx context.Context, o *taskOutputObserver) context.Context {+ return context.WithValue(ctx, taskOutputObserverContextKey{}, o)+}++func taskOutputObserverFromContext(ctx context.Context) *taskOutputObserver {+ o, _ := ctx.Value(taskOutputObserverContextKey{}).(*taskOutputObserver)+ return o+}++// shouldRetireSilentResume reports whether a run's resumed session should be+// retired because the run was cancelled after resuming it and never produced+// any output for at least silentResumeRetireThreshold.+//+// Only cancellation statuses qualify: a failed run already carries an error+// the resume guards classify, and a timeout/idle_watchdog has its own+// failure_reason. priorSessionID == "" means the run started cold, so there+// is no resumed session to blame.+func shouldRetireSilentResume(status, priorSessionID string, silent time.Duration, wasSilent bool) bool {+ if priorSessionID == "" || !wasSilent {+ return false+ }+ switch status {+ case "cancelled", "aborted":+ default:+ return false+ }+ return silent >= silentResumeRetireThreshold+}diff --git a/server/internal/daemon/task_output_observer_test.go b/server/internal/daemon/task_output_observer_test.gonew file mode 100644index 0000000000..faa6b9a10c--- /dev/null+++ b/server/internal/daemon/task_output_observer_test.go@@ -0,0 +1,210 @@+package daemon++import (+ "context"+ "encoding/json"+ "io"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"+)++func TestShouldRetireSilentResume(t *testing.T) {+ t.Parallel()++ long := silentResumeRetireThreshold + time.Second+ short := silentResumeRetireThreshold - time.Second+ cases := []struct {+ name string+ status string+ prior string+ silent time.Duration+ wasSilent bool+ want bool+ }{+ // MUL-8188: resumed, cancelled by hand after minutes of nothing.+ {"cancelled silent resume", "cancelled", "ses_broken", long, true, true},+ {"aborted silent resume", "aborted", "ses_broken", long, true, true},+ // An ordinary early cancel keeps the conversation.+ {"early cancel", "cancelled", "ses_ok", short, true, false},+ // Any output proves the session loads and runs.+ {"cancel after output", "cancelled", "ses_ok", long, false, false},+ // A cold run has no resumed session to blame.+ {"cold run", "cancelled", "", long, true, false},+ // Failures/timeouts are classified by their own guards.+ {"failed", "failed", "ses_x", long, true, false},+ {"timeout", "timeout", "ses_x", long, true, false},+ {"idle watchdog", "idle_watchdog", "ses_x", long, true, false},+ {"completed", "completed", "ses_x", long, true, false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ if got := shouldRetireSilentResume(tc.status, tc.prior, tc.silent, tc.wasSilent); got != tc.want {+ t.Fatalf("shouldRetireSilentResume(%q, %q, %s, %v) = %v, want %v", tc.status, tc.prior, tc.silent, tc.wasSilent, got, tc.want)+ }+ })+ }+}++// fakeAwakeClock is an awake-time source the test advances by hand. A host+// suspend is simply wall time passing while this clock stands still.+type fakeAwakeClock struct {+ mu sync.Mutex+ now time.Duration+}++func (c *fakeAwakeClock) read() time.Duration {+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.now+}++func (c *fakeAwakeClock) advance(d time.Duration) {+ c.mu.Lock()+ c.now += d+ c.mu.Unlock()+}++func TestTaskOutputObserver(t *testing.T) {+ t.Parallel()++ var nilObs *taskOutputObserver+ nilObs.begin()+ nilObs.markOutput()+ if _, ok := nilObs.silentFor(); ok {+ t.Fatal("nil observer must report not-silent")+ }++ clock := &fakeAwakeClock{now: time.Hour}+ o := &taskOutputObserver{clock: clock.read}+ if _, ok := o.silentFor(); ok {+ t.Fatal("never-started observer must report not-silent")+ }+ o.begin()+ clock.advance(7 * time.Minute)+ if d, ok := o.silentFor(); !ok || d != 7*time.Minute {+ t.Fatalf("silentFor = %s, %v; want 7m, true", d, ok)+ }+ o.markOutput()+ clock.advance(time.Minute)+ if _, ok := o.silentFor(); ok {+ t.Fatal("observer with output must report not-silent")+ }+ // A new execution (fresh-session retry) resets the observation.+ o.begin()+ clock.advance(time.Minute)+ if _, ok := o.silentFor(); !ok {+ t.Fatal("begin must reset the output flag")+ }++ ctx := withTaskOutputObserver(context.Background(), o)+ if taskOutputObserverFromContext(ctx) != o {+ t.Fatal("observer not recoverable from context")+ }+ if taskOutputObserverFromContext(context.Background()) != nil {+ t.Fatal("empty context must yield a nil observer")+ }+}++// TestTaskOutputObserverIgnoresHostSleep is the suspend regression the review+// asked for: a resume starts, the host sleeps for an hour (wall time passes,+// awake time does not), the user wakes it and cancels within a minute. That+// run was silent for one awake minute, not 61, and must not retire a healthy+// session. Mirrors the idle-watchdog fix (MUL-7851 / #9201).+func TestTaskOutputObserverIgnoresHostSleep(t *testing.T) {+ t.Parallel()++ clock := &fakeAwakeClock{}+ o := &taskOutputObserver{clock: clock.read}+ o.begin()+ clock.advance(30 * time.Second)+ // Host suspended for an hour here: wall time passes, awakeclock does not+ // move, so there is nothing to advance. The user cancels 30s after waking.+ clock.advance(30 * time.Second)++ silent, wasSilent := o.silentFor()+ if !wasSilent || silent != time.Minute {+ t.Fatalf("silentFor = %s, %v; want 1m of awake silence", silent, wasSilent)+ }+ if shouldRetireSilentResume("cancelled", "ses_ok", silent, wasSilent) {+ t.Fatal("a run cancelled one awake minute after resuming must not retire its session, however long the host slept")+ }+}++func TestTaskOutputObserverDefaultsToAwakeClock(t *testing.T) {+ t.Parallel()++ o := &taskOutputObserver{}+ o.begin()+ if d, ok := o.silentFor(); !ok || d < 0 || d > time.Minute {+ t.Fatalf("silentFor on the real awake clock = %s, %v; want a small non-negative duration", d, ok)+ }+}++// TestHandleTask_CancelAckCarriesRetiredSession pins the delivery half of+// MUL-8188: the session runTask retired must reach the server on the+// poll-cancelled path, the only terminal channel a cancelled task has.+func TestHandleTask_CancelAckCarriesRetiredSession(t *testing.T) {+ t.Parallel()++ var mu sync.Mutex+ var ackBody map[string]any+ var statusCalls int+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case strings.HasSuffix(r.URL.Path, "/cancel-ack"):+ body, _ := io.ReadAll(r.Body)+ mu.Lock()+ _ = json.Unmarshal(body, &ackBody)+ mu.Unlock()+ w.WriteHeader(http.StatusOK)+ case strings.HasSuffix(r.URL.Path, "/status"):+ mu.Lock()+ statusCalls+++ first := statusCalls == 1+ mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ if first {+ _, _ = w.Write([]byte(`{"status":"cancelled"}`))+ } else {+ _, _ = w.Write([]byte(`{"status":"running"}`))+ }+ default:+ w.WriteHeader(http.StatusOK)+ }+ }))+ t.Cleanup(srv.Close)++ d := &Daemon{+ client: NewClient(srv.URL),+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ workspaces: make(map[string]*workspaceState),+ runtimeIndex: map[string]Runtime{"rt-1": {ID: "rt-1", Provider: "kiro"}},+ cancelPollInterval: 10 * time.Millisecond,+ }+ d.runner = taskRunnerFunc(func(runCtx context.Context, _ Task, _ string, _ int, _ *slog.Logger) (TaskResult, error) {+ <-runCtx.Done()+ return TaskResult{Status: "aborted", RetiredSessionID: "ses_broken"}, nil+ })++ d.handleTask(context.Background(), Task{+ ID: "task-retire-ack",+ RuntimeID: "rt-1",+ IssueID: "issue-retire-ack",+ Agent: &AgentData{Name: "test-agent"},+ }, 0)++ mu.Lock()+ defer mu.Unlock()+ if ackBody == nil {+ t.Fatal("cancel-ack was never posted")+ }+ if got := ackBody["retired_session_id"]; got != "ses_broken" {+ t.Fatalf("cancel-ack retired_session_id = %v, want ses_broken (body=%v)", got, ackBody)+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 10c2319ff4..5f6d2685b2 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -2730,6 +2730,25 @@ func chatSessionResumeFallbackNeeded(priorSessionID, priorWorkDir string) bool {return priorSessionID == "" || priorWorkDir == ""}+// rerunSessionRetired reports whether a later run already retired the session+// a manual retry would resume. The rerun path reads its exact source task, so+// it bypasses the retired_sessions exclusion GetLastTaskSession applies; this+// is that exclusion for the exact-source path (MUL-8188). A lookup error fails+// closed — starting fresh in the reused workdir costs conversation context,+// resuming an undrivable session costs the whole run.+func (h *Handler) rerunSessionRetired(ctx context.Context, agentID pgtype.UUID, sessionID string) bool {+ retired, err := h.Queries.IsTaskSessionRetired(ctx, db.IsTaskSessionRetiredParams{+ AgentID: agentID,+ SessionID: sessionID,+ })+ if err != nil {+ slog.Warn("daemon claim: retired-session lookup failed; starting the rerun fresh",+ "agent_id", uuidToString(agentID), "error", err)+ return true+ }+ return retired+}+func rerunSourceMatchesTaskScope(task, source db.AgentTaskQueue) bool {if task.AgentID != source.AgentID {return false@@ -3373,8 +3392,15 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQuif src.WorkDir.Valid {resp.PriorWorkDir = src.WorkDir.String}+ sourceSessionRetired := src.SessionID.Valid &&+ h.rerunSessionRetired(r.Context(), task.AgentID, src.SessionID.String)+ if sourceSessionRetired {+ // The source's own conversation is gone for good; tell the+ // agent rather than letting it assume continuity.+ resp.PriorSessionResumeUnavailable = true+ }if !service.ResumeUnsafeFailure(src.FailureReason.String, src.Error.String) &&- src.SessionID.Valid && src.RuntimeID == task.RuntimeID {+ src.SessionID.Valid && src.RuntimeID == task.RuntimeID && !sourceSessionRetired {resp.PriorSessionID = src.SessionID.String// The deltas date from the run we actually resume, which on// this path is the operator-chosen source — routinely NOT@@ -5699,6 +5725,11 @@ type TaskCancelAckRequest struct {// preserved worktree is the only pointer left to the agent's work.ErrorMessage string `json:"error_message,omitempty"`FailureReason string `json:"failure_reason,omitempty"`+ // RetiredSessionID: the session this run resumed and then produced no+ // output on before it was cancelled — a session the runtime cannot drive+ // (MUL-8188). Recorded so later triggers start fresh instead of resuming+ // into the same hang. Older daemons never send it.+ RetiredSessionID string `json:"retired_session_id,omitempty"`}func (h *Handler) AckTaskCancelled(w http.ResponseWriter, r *http.Request) {@@ -5719,6 +5750,7 @@ func (h *Handler) AckTaskCancelled(w http.ResponseWriter, r *http.Request) {req.FailureReason = util.SanitizeTextForPostgres(req.FailureReason)req.BranchName = util.SanitizeTextForPostgres(req.BranchName)req.DurableWorkDir = util.SanitizeTextForPostgres(req.DurableWorkDir)+ req.RetiredSessionID = util.SanitizeTextForPostgres(req.RetiredSessionID)// Terminal deliveries first, failing LOUD on persistence errors: these// fields are the only pointer to a cancelled task's work, and the daemon@@ -5771,6 +5803,17 @@ func (h *Handler) AckTaskCancelled(w http.ResponseWriter, r *http.Request) {}delivered = true}+ if retired := strings.TrimSpace(req.RetiredSessionID); retired != "" {+ // Fail loud like the deliveries above: the daemon retries the ack,+ // and a dropped write leaves the undrivable session resumable.+ // Not a client-visible field, so no rebroadcast is needed.+ if err := h.TaskService.RetireCancelledTaskSession(r.Context(), task.ID, retired); err != nil {+ slog.Error("cancel ack: retire session failed",+ "task_id", taskID, "error", err)+ writeError(w, http.StatusInternalServerError, "failed to retire session")+ return+ }+ }if delivered {// The task:cancelled broadcast fired at cancel time, before this ack —// clients may already hold a refetched row without the branch/errordiff --git a/server/internal/handler/daemon_cancel_retire_test.go b/server/internal/handler/daemon_cancel_retire_test.gonew file mode 100644index 0000000000..69d39653e2--- /dev/null+++ b/server/internal/handler/daemon_cancel_retire_test.go@@ -0,0 +1,281 @@+package handler++import (+ "context"+ "errors"+ "net/http"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// mul8188Agent returns the seeded workspace agent and its runtime.+func mul8188Agent(t *testing.T) (agentID, runtimeID string) {+ t.Helper()+ dbfx.QueryRow(t, `+ SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1+ `, testWorkspaceID).Scan(&agentID, &runtimeID)+ return agentID, runtimeID+}++func ackCancelled(t *testing.T, taskID string, body map[string]any) {+ t.Helper()+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/cancel-ack", body)+ req = testutil.WithURLParams(req, "taskId", taskID)+ testutil.Call(t, testHandler.AckTaskCancelled, req).Want(http.StatusOK)+}++func lastIssueSession(t *testing.T, agentID, issueID string) (string, bool) {+ t.Helper()+ got, err := testHandler.Queries.GetLastTaskSession(context.Background(), db.GetLastTaskSessionParams{+ AgentID: parseUUID(agentID),+ IssueID: parseUUID(issueID),+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return "", false+ }+ if err != nil {+ t.Fatalf("GetLastTaskSession: %v", err)+ }+ return got.SessionID.String, true+}++func retiredSessionOf(t *testing.T, taskID string) string {+ t.Helper()+ var retired string+ dbfx.QueryRow(t, `+ SELECT COALESCE(retired_session_id, '') FROM agent_task_queue WHERE id = $1+ `, taskID).Scan(&retired)+ return retired+}++// TestCancelAck_RetiresSilentResumedSession is the server half of MUL-8188's+// "keeps resuming the broken session" loop: an earlier provider 5xx (resume+// safe) and then a hand-cancelled run, both naming the same session. Every row+// was a valid resume source, so each trigger resumed it again.+func TestCancelAck_RetiresSilentResumedSession(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ agentID, runtimeID := mul8188Agent(t)+ issueID := dbfx.Issue(t, "mul-8188 retire on cancel-ack")++ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "failed",+ "session_id": "ses_broken",+ "failure_reason": "agent_error.provider_server_error",+ "error": "kiro session/prompt failed: session/prompt: Internal error (code=-32603, data=dispatch failure)",+ "started_at": testutil.Raw("now() - interval '10 minutes'"),+ "completed_at": testutil.Raw("now() - interval '9 minutes'"),+ })+ cancelled := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "cancelled",+ "session_id": "ses_broken",+ "started_at": testutil.Raw("now() - interval '8 minutes'"),+ "completed_at": testutil.Raw("now() - interval '1 minute'"),+ })++ if got, ok := lastIssueSession(t, agentID, issueID); !ok || got != "ses_broken" {+ t.Fatalf("precondition: resume pointer = %q (%v), want ses_broken", got, ok)+ }++ ackCancelled(t, cancelled, map[string]any{"retired_session_id": "ses_broken"})++ if got := retiredSessionOf(t, cancelled); got != "ses_broken" {+ t.Fatalf("retired_session_id = %q, want ses_broken", got)+ }+ if got, ok := lastIssueSession(t, agentID, issueID); ok && got == "ses_broken" {+ t.Fatal("the undrivable session is still offered as the resume pointer")+ }++ // Replay is idempotent and never overwrites.+ ackCancelled(t, cancelled, map[string]any{"retired_session_id": "ses_other"})+ if got := retiredSessionOf(t, cancelled); got != "ses_broken" {+ t.Fatalf("replay overwrote retired_session_id: %q", got)+ }+}++// TestCancelAck_RetiredSessionIgnoredOnNonCancelledRow: the status CAS keeps a+// stale ack from retiring the session of a completed run.+func TestCancelAck_RetiredSessionIgnoredOnNonCancelledRow(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ agentID, runtimeID := mul8188Agent(t)+ issueID := dbfx.Issue(t, "mul-8188 cas on completed row")+ completed := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "completed",+ "session_id": "ses_healthy",+ "started_at": testutil.Raw("now()"),+ "completed_at": testutil.Raw("now()"),+ })++ ackCancelled(t, completed, map[string]any{"retired_session_id": "ses_healthy"})++ if got := retiredSessionOf(t, completed); got != "" {+ t.Fatalf("retired_session_id = %q on a completed row, want empty", got)+ }+ if got, ok := lastIssueSession(t, agentID, issueID); !ok || got != "ses_healthy" {+ t.Fatalf("resume pointer = %q (%v), want ses_healthy to stay resumable", got, ok)+ }+}++// TestCancelAck_RetiredSessionClearsChatPointer: a chat turn resumes from+// chat_session.session_id first, so the pointer must be cleared too — but+// only while it still names the retired session.+func TestCancelAck_RetiredSessionClearsChatPointer(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ agentID, runtimeID := mul8188Agent(t)+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "session_id": "ses_broken",+ "runtime_id": runtimeID,+ })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "status": "cancelled",+ "session_id": "ses_broken",+ "started_at": testutil.Raw("now()"),+ "completed_at": testutil.Raw("now()"),+ })++ ackCancelled(t, taskID, map[string]any{"retired_session_id": "ses_broken"})++ var pointer *string+ dbfx.QueryRow(t, `SELECT session_id FROM chat_session WHERE id = $1`, chatSessionID).Scan(&pointer)+ if pointer != nil && *pointer == "ses_broken" {+ t.Fatal("chat resume pointer still names the retired session")+ }+}++// TestGetLastTaskSession_ExcludesInvalidConversationHistory pins the+// server-side text guard for rows an older daemon classified as resume-safe:+// Kiro's "invalid conversation history" panic must never be resumed again.+func TestGetLastTaskSession_ExcludesInvalidConversationHistory(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ agentID, runtimeID := mul8188Agent(t)+ issueID := dbfx.Issue(t, "mul-8188 invalid history text guard")+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "failed",+ "session_id": "ses_broken",+ "failure_reason": "agent_error.unknown",+ "error": `kiro runtime panicked: The application panicked (crashed). | Message: first agent loop request should never fail: AgentLoopResponse(Custom("invalid conversation history received"))`,+ "started_at": testutil.Raw("now()"),+ "completed_at": testutil.Raw("now()"),+ })++ if got, ok := lastIssueSession(t, agentID, issueID); ok && got == "ses_broken" {+ t.Fatal("a session Kiro reported as invalid history is still offered as the resume pointer")+ }+}++// TestClaimRerun_DoesNotReviveRetiredSession is the review's P1 regression+// (adapted from the reviewer's attachment). A manual retry resumes from its+// exact source task instead of GetLastTaskSession, so it used to bypass the+// retired set: retrying the original provider-5xx failure handed back the+// very session a later cancelled run had retired. The workdir must still be+// reused, and the agent told that continuity is unavailable.+func TestClaimRerun_DoesNotReviveRetiredSession(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)+ issueID := dbfx.Issue(t, "mul-8188 rerun retired session")+ sourceID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "failed",+ "session_id": "ses_broken",+ "failure_reason": "agent_error.provider_server_error",+ "error": "dispatch failure",+ "work_dir": "/tmp/mul8188-existing-workdir",+ "started_at": testutil.Raw("now() - interval '10 minutes'"),+ "completed_at": testutil.Raw("now() - interval '9 minutes'"),+ })+ cancelledID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "cancelled",+ "started_at": testutil.Raw("now() - interval '8 minutes'"),+ "completed_at": testutil.Raw("now() - interval '1 minute'"),+ })+ ackCancelled(t, cancelledID, map[string]any{"retired_session_id": "ses_broken"})+ if got, ok := lastIssueSession(t, agentID, issueID); ok && got == "ses_broken" {+ t.Fatal("precondition: retirement did not take effect")+ }++ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "rerun_of_task_id": sourceID,+ "force_fresh_session": true,+ })+ var response struct {+ Task *AgentTaskResponse `json:"task"`+ }+ claimForRuntimeExpecting(t, testHandler, runtimeID, daemonID, http.StatusOK).JSON(&response)+ if response.Task == nil {+ t.Fatal("no task claimed")+ }+ if response.Task.PriorSessionID != "" {+ t.Fatalf("manual retry revived retired session: PriorSessionID=%q", response.Task.PriorSessionID)+ }+ if response.Task.PriorWorkDir != "/tmp/mul8188-existing-workdir" {+ t.Fatalf("PriorWorkDir = %q, want the source workdir reused", response.Task.PriorWorkDir)+ }+ if !response.Task.PriorSessionResumeUnavailable {+ t.Fatal("PriorSessionResumeUnavailable = false; the agent must be told continuity is gone")+ }+}++// TestClaimRerun_ResumesHealthySourceSession is the control: with nothing+// retired, a manual retry of a resume-safe failure still resumes its session.+func TestClaimRerun_ResumesHealthySourceSession(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)+ issueID := dbfx.Issue(t, "mul-8188 rerun healthy session")+ sourceID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "failed",+ "session_id": "ses_healthy",+ "failure_reason": "agent_error.provider_server_error",+ "error": "dispatch failure",+ "started_at": testutil.Raw("now() - interval '10 minutes'"),+ "completed_at": testutil.Raw("now() - interval '9 minutes'"),+ })+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "rerun_of_task_id": sourceID,+ "force_fresh_session": true,+ })+ var response struct {+ Task *AgentTaskResponse `json:"task"`+ }+ claimForRuntimeExpecting(t, testHandler, runtimeID, daemonID, http.StatusOK).JSON(&response)+ if response.Task == nil {+ t.Fatal("no task claimed")+ }+ if response.Task.PriorSessionID != "ses_healthy" {+ t.Fatalf("PriorSessionID = %q, want ses_healthy", response.Task.PriorSessionID)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 3b5cbb2ce6..eac7293876 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -3377,6 +3377,53 @@ func (s *TaskService) RebroadcastCancelledTask(ctx context.Context, taskID pgtyps.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, task)}+// RetireCancelledTaskSession records, on a CANCELLED task, a session the daemon+// judged undrivable: the run resumed it and produced no output at all before+// it was cancelled (MUL-8188). It is the cancel-ack's counterpart of the+// retired_session_id the complete/fail callbacks carry, and it has the same+// two effects: the (agent, issue) resume lookups stop selecting the session,+// and a chat pointer still naming it is cleared so the next turn starts fresh.+//+// The status CAS in SetAgentTaskRetiredSessionIDIfCancelled makes a late or+// replayed ack against a completed/failed row a no-op; the chat pointer is+// only touched when that write applied, so a stale ack can never clear a+// healthy pointer.+func (s *TaskService) RetireCancelledTaskSession(ctx context.Context, taskID pgtype.UUID, sessionID string) error {+ if sessionID == "" {+ return nil+ }+ return s.runInTx(ctx, func(qtx *db.Queries) error {+ if err := lockChatSessionForTaskWrite(ctx, qtx, taskID); err != nil {+ return err+ }+ rows, err := qtx.SetAgentTaskRetiredSessionIDIfCancelled(ctx, db.SetAgentTaskRetiredSessionIDIfCancelledParams{+ ID: taskID,+ RetiredSessionID: pgtype.Text{String: sessionID, Valid: true},+ })+ if err != nil {+ return fmt.Errorf("record retired session on cancelled task: %w", err)+ }+ if rows == 0 {+ return nil+ }+ t, err := qtx.GetAgentTask(ctx, taskID)+ if err != nil {+ return fmt.Errorf("load cancelled task: %w", err)+ }+ if !t.ChatSessionID.Valid {+ return nil+ }+ if err := qtx.ClearChatSessionSessionIfMatches(ctx, db.ClearChatSessionSessionIfMatchesParams{+ ID: t.ChatSessionID,+ SessionID: pgtype.Text{String: sessionID, Valid: true},+ RuntimeID: t.RuntimeID,+ }); err != nil {+ return fmt.Errorf("clear retired chat session resume pointer: %w", err)+ }+ return nil+ })+}+func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID pgtype.UUID) bool {var (task db.AgentTaskQueuediff --git a/server/pkg/agent/acp_panic.go b/server/pkg/agent/acp_panic.gonew file mode 100644index 0000000000..f78d17b48d--- /dev/null+++ b/server/pkg/agent/acp_panic.go@@ -0,0 +1,112 @@+package agent++import (+ "regexp"+ "strings"+ "sync"+)++// acpRuntimePanicDetector watches an ACP runtime's stderr for a panic report+// and signals it the moment the header line arrives.+//+// Why it has to be live rather than a post-mortem scan: a Rust ACP runtime+// (Kiro) can panic inside its agent loop while the ACP server task keeps+// running. The process stays alive, stdout stays open, and the in-flight+// session/prompt never gets a response or an error. Every existing stderr+// check (promoteACPResultOnProviderError) only runs after the process exits,+// so it never sees this panic, and the task sits in "waiting for reply" until+// the 2h idle watchdog or a manual cancel (MUL-8188). Observed verbatim:+//+// The application panicked (crashed).+// Message: first agent loop request should never fail: AgentLoopResponse(Custom("invalid conversation history received"))+// Location: crates/agent/src/agent/mod.rs:3744+//+// Only line-anchored panic headers count, so an ordinary log line that merely+// mentions the word "panicked" does not end a healthy run.+type acpRuntimePanicDetector struct {+ mu sync.Mutex+ remains []byte+ fired bool+ lines []string // header + up to acpPanicDetailLines following lines+ detected chan struct{}+}++// acpPanicDetailLines bounds how many lines after the header are kept for the+// error text: enough for color-eyre's Message/Location pair or Rust's default+// "panicked at <loc>:\n<msg>" shape, without swallowing a whole backtrace.+const acpPanicDetailLines = 3++// acpPanicDetailMaxLen caps the surfaced panic text so a pathological message+// cannot bloat the task error column.+const acpPanicDetailMaxLen = 600++var (+ // color-eyre / human-panic header (Kiro installs color-eyre) and the Rust+ // default hook header ("thread 'main' panicked at src/x.rs:1:2:").+ acpPanicHeaderRe = regexp.MustCompile(`^(The application panicked\b|thread '[^']*' panicked at\b)`)+ ansiEscapeRe = regexp.MustCompile(`\x1b\[[0-9;]*[A-Za-z]`)+)++func newACPRuntimePanicDetector() *acpRuntimePanicDetector {+ return &acpRuntimePanicDetector{detected: make(chan struct{})}+}++// Write implements io.Writer so the detector can sit behind the stderr+// io.MultiWriter next to the log forwarder and the provider-error sniffer.+func (d *acpRuntimePanicDetector) Write(p []byte) (int, error) {+ d.mu.Lock()+ defer d.mu.Unlock()++ data := append(d.remains, p...)+ nl := strings.LastIndexByte(string(data), '\n')+ if nl < 0 {+ d.remains = append(d.remains[:0], data...)+ return len(p), nil+ }+ complete := string(data[:nl])+ d.remains = append(d.remains[:0], data[nl+1:]...)++ for _, raw := range strings.Split(complete, "\n") {+ line := strings.TrimSpace(ansiEscapeRe.ReplaceAllString(strings.TrimSuffix(raw, "\r"), ""))+ if line == "" {+ continue+ }+ if !d.fired {+ if acpPanicHeaderRe.MatchString(line) {+ d.fired = true+ d.lines = append(d.lines, line)+ close(d.detected)+ }+ continue+ }+ if len(d.lines) <= acpPanicDetailLines {+ d.lines = append(d.lines, line)+ }+ }+ return len(p), nil+}++// Detected is closed when the first panic header is seen.+func (d *acpRuntimePanicDetector) Detected() <-chan struct{} {+ return d.detected+}++// Fired reports whether a panic header has been seen.+func (d *acpRuntimePanicDetector) Fired() bool {+ d.mu.Lock()+ defer d.mu.Unlock()+ return d.fired+}++// Detail returns the captured panic header and the lines that followed it,+// joined into a single line. Read it after the stderr copier has drained so+// the Message/Location lines that trail the header are included.+func (d *acpRuntimePanicDetector) Detail() string {+ d.mu.Lock()+ defer d.mu.Unlock()+ detail := strings.Join(d.lines, " | ")+ if len(detail) > acpPanicDetailMaxLen {+ detail = strings.ToValidUTF8(detail[:acpPanicDetailMaxLen], "") + "…"+ }+ return detail+}diff --git a/server/pkg/agent/kiro.go b/server/pkg/agent/kiro.goindex 1520858f4c..ec2acea338 100644--- a/server/pkg/agent/kiro.go+++ b/server/pkg/agent/kiro.go@@ -165,7 +165,10 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptioreturn nil, fmt.Errorf("start kiro: %w", err)}- stderrSink := io.MultiWriter(newLogWriter(b.cfg.Logger, "[kiro:stderr] "), providerErr)+ // Live panic watch: Kiro can panic inside its agent loop while the ACP+ // process stays up, so session/prompt would never answer (MUL-8188).+ runtimePanic := newACPRuntimePanicDetector()+ stderrSink := io.MultiWriter(newLogWriter(b.cfg.Logger, "[kiro:stderr] "), providerErr, runtimePanic)stderrDone := make(chan struct{})go func() {defer close(stderrDone)@@ -182,6 +185,10 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio// for Result.Output while retaining the full text for error detection.var deliverable acpDeliverableTrackervar streamingCurrentTurn atomic.Bool+ // turnProducedMessage records whether the current prompt emitted any agent+ // message before a runtime panic; a resumed session that panics before its+ // first message is one the runtime cannot drive (MUL-8188).+ var turnProducedMessage atomic.Bool// Completion-preservation state for the -32603 close-handshake guard.//// Kiro raises `session/prompt -32603 "failed to generate a response"`@@ -258,6 +265,7 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio}}deliverable.observe(msg)+ turnProducedMessage.Store(true)trySend(msgCh, msg)},onPromptDone: func(result hermesPromptResult) {@@ -305,6 +313,8 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio// resume. Only that is curable by starting a fresh session, so// handshake/network failures below must leave it false.var resumeRejected bool+ // Set when the live panic detector aborted session/prompt.+ var runtimePanicked booleffectiveModel := strings.TrimSpace(opts.Model)initResult, err := c.request(runCtx, "initialize", map[string]any{@@ -445,10 +455,23 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio// shape can drive the turn.// TODO: drop one field once Kiro lands on a single canonical payload.streamingCurrentTurn.Store(true)+ // promptCtx lets a live runtime panic abort the in-flight prompt.+ // Without it a Kiro that panicked in its agent loop but kept the ACP+ // process alive leaves session/prompt waiting until the task timeout+ // or the idle watchdog (MUL-8188).+ promptCtx, promptCancel := context.WithCancel(runCtx)+ go func() {+ select {+ case <-runtimePanic.Detected():+ b.cfg.Logger.Warn("kiro runtime panicked mid-turn; aborting the prompt", "pid", cmd.Process.Pid, "session_id", sessionID)+ promptCancel()+ case <-promptCtx.Done():+ }+ }()// Steering opens only once the prompt is on the wire and closes as// soon as it answers, so a supplement can never target setup or a// finished turn.- _, err = c.requestAndNotifySent(runCtx, "session/prompt", map[string]any{+ _, err = c.requestAndNotifySent(promptCtx, "session/prompt", map[string]any{"sessionId": sessionID,"content": promptBlocks,"prompt": promptBlocks,@@ -457,8 +480,17 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptiosupplements.active.Store(true)}})+ promptCancel()supplements.stop()- if err != nil {+ if err != nil && runtimePanic.Fired() && runCtx.Err() == nil {+ // Checked before the ctx classifiers: promptCtx was cancelled by+ // the panic, not by the task. The panic may also have taken the+ // process down ("kiro process exited"); either way the panic is+ // the real cause. Error text and resume classification are+ // settled after stderr drains (see below).+ finalStatus = "failed"+ runtimePanicked = true+ } else if err != nil {if runCtx.Err() == context.DeadlineExceeded {finalStatus = "timeout"finalError = fmt.Sprintf("kiro timed out after %s", timeout)@@ -539,6 +571,26 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio// provider-error sniffer; see hermes.go for the failure mode.<-stderrDone+ // A runtime panic during the prompt is the real failure, whichever+ // path noticed it first: the live detector aborting the prompt, or+ // the process dying and closing stdout before stderr was read. The+ // Message/Location lines trail the header, so the text is only+ // complete now that stderr has drained.+ if runtimePanic.Fired() && (runtimePanicked || finalStatus == "failed") {+ finalStatus = "failed"+ finalError = "kiro runtime panicked: " + runtimePanic.Detail()+ if opts.ResumeSessionID != "" && !turnProducedMessage.Load() {+ // The resumed session loaded but the runtime crashed before+ // the turn produced anything: this session cannot be driven,+ // so let the daemon retry once from a fresh session and+ // retire it. A panic after the turn made progress is not+ // evidence against the session, so it stays resumable.+ b.cfg.Logger.Warn("resumed kiro session panicked before its first message; signaling resume rejection so the daemon retries with a fresh session",+ "session_id", sessionID,+ )+ resumeRejected = true+ }+ }finalOutput, providerErrorOutput := deliverable.result()// Promote completed→failed when stderr or the agent textdiff --git a/server/pkg/agent/kiro_panic_test.go b/server/pkg/agent/kiro_panic_test.gonew file mode 100644index 0000000000..f4c6f58f95--- /dev/null+++ b/server/pkg/agent/kiro_panic_test.go@@ -0,0 +1,226 @@+package agent++import (+ "context"+ "log/slog"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/pkg/taskfailure"+)++// fakeKiroACPPanicScript reproduces MUL-8188: session/load succeeds, then the+// first session/prompt makes Kiro's agent loop panic. The panic is written to+// stderr and — the part that used to wedge tasks for hours — the process keeps+// running without ever answering the prompt, unless KIRO_PANIC_EXIT is set.+// KIRO_CHUNK_BEFORE_PANIC emits one agent message before panicking.+func fakeKiroACPPanicScript() string {+ return `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_fresh"}}\n' "$id"+ ;;+ *'"method":"session/load"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ if [ -n "$KIRO_CHUNK_BEFORE_PANIC" ]; then+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_broken","update":{"type":"AgentMessageChunk","content":{"type":"text","text":"working on it"}}}}\n'+ sleep 0.3+ fi+ printf '\033[31mThe application panicked (crashed).\033[0m\n' >&2+ printf 'Message: first agent loop request should never fail: AgentLoopResponse(Custom("invalid conversation history received"))\n' >&2+ printf 'Location: crates/agent/src/agent/mod.rs:3744\n' >&2+ if [ -n "$KIRO_PANIC_EXIT" ]; then+ exit 101+ fi+ ;;+ esac+done+`+}++func runKiroPanicScript(t *testing.T, env map[string]string, opts ExecOptions) (Result, time.Duration) {+ t.Helper()+ fakePath := filepath.Join(t.TempDir(), "kiro-cli")+ writeTestExecutable(t, fakePath, []byte(fakeKiroACPPanicScript()))++ backend, err := New("kiro", Config{ExecutablePath: fakePath, Logger: slog.Default(), Env: env})+ if err != nil {+ t.Fatalf("new kiro backend: %v", err)+ }+ // A long task timeout: the run must end because of the panic, not+ // because a deadline happened to expire.+ opts.Timeout = 60 * time.Second+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ defer cancel()++ start := time.Now()+ session, err := backend.Execute(ctx, "prompt", opts)+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ select {+ case result, ok := <-session.Result:+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ return result, time.Since(start)+ case <-time.After(20 * time.Second):+ t.Fatal("kiro run did not finish after the runtime panicked (stuck waiting for session/prompt)")+ return Result{}, 0+ }+}++// TestKiroResumedPanicFailsFastAndRejectsResume is the MUL-8188 regression:+// a resumed session whose history Kiro cannot replay panics on the first+// prompt while the process stays alive. The run must fail within seconds,+// surface the panic, and signal ResumeRejected so the daemon retries once on a+// fresh session and retires the broken one.+func TestKiroResumedPanicFailsFastAndRejectsResume(t *testing.T) {+ t.Parallel()++ result, elapsed := runKiroPanicScript(t, nil, ExecOptions{ResumeSessionID: "ses_broken"})++ if result.Status != "failed" {+ t.Fatalf("status = %q, want failed (error=%q)", result.Status, result.Error)+ }+ if elapsed > 10*time.Second {+ t.Fatalf("run took %s; a live panic must end it promptly", elapsed)+ }+ if !result.ResumeRejected {+ t.Fatalf("ResumeRejected = false, want true for a resumed session that panicked before its first message (error=%q)", result.Error)+ }+ for _, want := range []string{"kiro runtime panicked", "The application panicked", "invalid conversation history received", "Location: crates/agent/src/agent/mod.rs:3744"} {+ if !strings.Contains(result.Error, want) {+ t.Errorf("error %q does not contain %q", result.Error, want)+ }+ }+ if strings.Contains(result.Error, "\x1b[") {+ t.Errorf("error still carries ANSI escapes: %q", result.Error)+ }+ // The resume guards (daemon fresh-session retry, poisoned classifier,+ // GetLastTaskSession text guard) all key off this predicate.+ if !taskfailure.UnresumableHistory(result.Error) {+ t.Errorf("UnresumableHistory(%q) = false, want true", result.Error)+ }+}++// TestKiroPanicThenExitIsStillClassifiedAsPanic covers the other shape: the+// panic takes the process down, so stdout closes ("kiro process exited")+// possibly before stderr is read. The panic must still be the reported cause.+func TestKiroPanicThenExitIsStillClassifiedAsPanic(t *testing.T) {+ t.Parallel()++ result, _ := runKiroPanicScript(t, map[string]string{"KIRO_PANIC_EXIT": "1"}, ExecOptions{ResumeSessionID: "ses_broken"})++ if result.Status != "failed" {+ t.Fatalf("status = %q, want failed (error=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "invalid conversation history received") {+ t.Fatalf("error %q does not surface the panic message", result.Error)+ }+ if !result.ResumeRejected {+ t.Fatalf("ResumeRejected = false, want true (error=%q)", result.Error)+ }+}++// TestKiroFreshSessionPanicDoesNotRejectResume: a cold session cannot be+// "resume rejected". It must still fail fast instead of hanging.+func TestKiroFreshSessionPanicDoesNotRejectResume(t *testing.T) {+ t.Parallel()++ result, elapsed := runKiroPanicScript(t, nil, ExecOptions{})++ if result.Status != "failed" {+ t.Fatalf("status = %q, want failed (error=%q)", result.Status, result.Error)+ }+ if elapsed > 10*time.Second {+ t.Fatalf("run took %s; a live panic must end it promptly", elapsed)+ }+ if result.ResumeRejected {+ t.Fatal("ResumeRejected = true on a fresh session, want false")+ }+ if !strings.Contains(result.Error, "kiro runtime panicked") {+ t.Fatalf("error %q does not surface the panic", result.Error)+ }+}++// TestKiroResumedPanicAfterProgressKeepsSession: a resumed turn that produced+// output before panicking proved the session loads and runs, so the panic is+// not evidence against it and ResumeRejected stays false.+func TestKiroResumedPanicAfterProgressKeepsSession(t *testing.T) {+ t.Parallel()++ result, _ := runKiroPanicScript(t, map[string]string{"KIRO_CHUNK_BEFORE_PANIC": "1"}, ExecOptions{ResumeSessionID: "ses_broken"})++ if result.Status != "failed" {+ t.Fatalf("status = %q, want failed (error=%q)", result.Status, result.Error)+ }+ if result.ResumeRejected {+ t.Fatalf("ResumeRejected = true after the turn made progress, want false (error=%q)", result.Error)+ }+}++func TestACPRuntimePanicDetector(t *testing.T) {+ t.Parallel()++ t.Run("color-eyre header split across writes", func(t *testing.T) {+ d := newACPRuntimePanicDetector()+ _, _ = d.Write([]byte("INFO starting\n\x1b[31mThe application pan"))+ if d.Fired() {+ t.Fatal("fired on a partial line")+ }+ _, _ = d.Write([]byte("icked (crashed).\x1b[0m\nMessage: boom\nLocation: x.rs:1\n"))+ select {+ case <-d.Detected():+ default:+ t.Fatal("Detected() not closed after the header")+ }+ if got, want := d.Detail(), "The application panicked (crashed). | Message: boom | Location: x.rs:1"; got != want {+ t.Fatalf("Detail() = %q, want %q", got, want)+ }+ })++ t.Run("rust default hook", func(t *testing.T) {+ d := newACPRuntimePanicDetector()+ _, _ = d.Write([]byte("thread 'tokio-runtime-worker' panicked at crates/agent/src/lib.rs:10:5:\nindex out of bounds\n"))+ if !d.Fired() {+ t.Fatal("did not fire on the Rust default panic header")+ }+ if !strings.Contains(d.Detail(), "index out of bounds") {+ t.Fatalf("Detail() = %q, want the panic message", d.Detail())+ }+ })++ t.Run("mid-line mention is not a panic", func(t *testing.T) {+ d := newACPRuntimePanicDetector()+ _, _ = d.Write([]byte("WARN tool output: the application panicked earlier, retrying\nDEBUG thread 'x' panicked at nothing\n"))+ if d.Fired() {+ t.Fatal("fired on a log line that only mentions a panic")+ }+ })++ t.Run("detail is bounded", func(t *testing.T) {+ d := newACPRuntimePanicDetector()+ _, _ = d.Write([]byte("The application panicked (crashed).\nMessage: " + strings.Repeat("x", 2000) + "\na\nb\nc\nd\n"))+ detail := d.Detail()+ if len(detail) > acpPanicDetailMaxLen+len("…") {+ t.Fatalf("Detail() length %d exceeds the cap", len(detail))+ }+ if strings.Contains(detail, "| d") {+ t.Fatalf("Detail() kept more than %d trailing lines: %q", acpPanicDetailLines, detail)+ }+ })+}diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 99414e592b..e896dacf7f 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -4353,6 +4353,10 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)AND NOT (COALESCE(error, '') ILIKE '%could not resolve authentication method%')AND NOT (COALESCE(error, '') ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'AND COALESCE(error, '') ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')+ -- MUL-8188: a runtime that names its own transcript invalid (Kiro panics+ -- with "invalid conversation history received" on every prompt) replays+ -- the same failure on every resume. Mirrors taskfailure.UnresumableHistory.+ AND NOT (COALESCE(error, '') ILIKE '%invalid conversation history%')))-- MUL-5722: a resume that overflowed the reader names no session, so it can@@ -4934,6 +4938,33 @@ func (q *Queries) HasTaskForIssue(ctx context.Context, issueID pgtype.UUID) (booreturn exists, err}+const isTaskSessionRetired = `-- name: IsTaskSessionRetired :one+SELECT EXISTS (+ SELECT 1 FROM agent_task_queue r+ WHERE r.agent_id = $1+ AND r.retired_session_id = $2::text+) AS retired+`++type IsTaskSessionRetiredParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ SessionID string `json:"session_id"`+}++// Whether any run of this agent explicitly retired session_id. The+// manual-retry claim path resumes from its exact source task instead of+// GetLastTaskSession / the chat pointer, so it must consult the retired set+// itself; without this a retry of an older, resume-safe failed run revives a+// session a later run already proved undrivable (MUL-8188). Session ids are+// opaque runtime-issued ids, so (agent, session) identifies the transcript+// whether the runs were issue or chat tasks.+func (q *Queries) IsTaskSessionRetired(ctx context.Context, arg IsTaskSessionRetiredParams) (bool, error) {+ row := q.db.QueryRow(ctx, isTaskSessionRetired, arg.AgentID, arg.SessionID)+ var retired bool+ err := row.Scan(&retired)+ return retired, err+}+const linkTaskToIssue = `-- name: LinkTaskToIssue :execUPDATE agent_task_queueSET issue_id = $2@@ -8448,6 +8479,32 @@ func (q *Queries) SetAgentTaskErrorIfEmpty(ctx context.Context, arg SetAgentTaskreturn err}+const setAgentTaskRetiredSessionIDIfCancelled = `-- name: SetAgentTaskRetiredSessionIDIfCancelled :execrows+UPDATE agent_task_queue+SET retired_session_id = COALESCE(retired_session_id, $1)+WHERE id = $2 AND status = 'cancelled'+`++type SetAgentTaskRetiredSessionIDIfCancelledParams struct {+ RetiredSessionID pgtype.Text `json:"retired_session_id"`+ ID pgtype.UUID `json:"id"`+}++// Cancel-ack companion to CompleteAgentTask/FailAgentTask's retired_session_id+// (MUL-8188). A resumed run that produced no output at all before it was+// cancelled is the signature of a session the runtime cannot drive (Kiro+// loaded the transcript, then hung on the first prompt). Without this the+// cancelled row kept the session resumable and every later trigger re-entered+// the same hang. Same status CAS and never-overwrite rule as the other+// cancel-ack writes; the row count tells the caller whether it applied.+func (q *Queries) SetAgentTaskRetiredSessionIDIfCancelled(ctx context.Context, arg SetAgentTaskRetiredSessionIDIfCancelledParams) (int64, error) {+ result, err := q.db.Exec(ctx, setAgentTaskRetiredSessionIDIfCancelled, arg.RetiredSessionID, arg.ID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const setDeferredChannelIssueTaskRuntimeOverlay = `-- name: SetDeferredChannelIssueTaskRuntimeOverlay :execrowsUPDATE agent_task_queueSET runtime_mcp_overlay = $1,diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex e1d467afc1..677544aa13 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -1009,6 +1009,10 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)AND NOT (COALESCE(error, '') ILIKE '%could not resolve authentication method%')AND NOT (COALESCE(error, '') ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'AND COALESCE(error, '') ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')+ -- MUL-8188: a runtime that names its own transcript invalid (Kiro panics+ -- with "invalid conversation history received" on every prompt) replays+ -- the same failure on every resume. Mirrors taskfailure.UnresumableHistory.+ AND NOT (COALESCE(error, '') ILIKE '%invalid conversation history%')))-- MUL-5722, mirroring GetLastTaskSession: an overflowed resume records nodiff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 4647b4245b..cb6ba79406 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -1096,6 +1096,10 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)AND NOT (COALESCE(error, '') ILIKE '%could not resolve authentication method%')AND NOT (COALESCE(error, '') ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'AND COALESCE(error, '') ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')+ -- MUL-8188: a runtime that names its own transcript invalid (Kiro panics+ -- with "invalid conversation history received" on every prompt) replays+ -- the same failure on every resume. Mirrors taskfailure.UnresumableHistory.+ AND NOT (COALESCE(error, '') ILIKE '%invalid conversation history%')))-- MUL-5722: a resume that overflowed the reader names no session, so it can@@ -1507,6 +1511,32 @@ UPDATE agent_task_queueSET durable_work_dir = COALESCE(durable_work_dir, sqlc.arg('durable_work_dir'))WHERE id = sqlc.arg('id') AND status = 'cancelled';+-- name: IsTaskSessionRetired :one+-- Whether any run of this agent explicitly retired session_id. The+-- manual-retry claim path resumes from its exact source task instead of+-- GetLastTaskSession / the chat pointer, so it must consult the retired set+-- itself; without this a retry of an older, resume-safe failed run revives a+-- session a later run already proved undrivable (MUL-8188). Session ids are+-- opaque runtime-issued ids, so (agent, session) identifies the transcript+-- whether the runs were issue or chat tasks.+SELECT EXISTS (+ SELECT 1 FROM agent_task_queue r+ WHERE r.agent_id = sqlc.arg('agent_id')+ AND r.retired_session_id = sqlc.arg('session_id')::text+) AS retired;++-- name: SetAgentTaskRetiredSessionIDIfCancelled :execrows+-- Cancel-ack companion to CompleteAgentTask/FailAgentTask's retired_session_id+-- (MUL-8188). A resumed run that produced no output at all before it was+-- cancelled is the signature of a session the runtime cannot drive (Kiro+-- loaded the transcript, then hung on the first prompt). Without this the+-- cancelled row kept the session resumable and every later trigger re-entered+-- the same hang. Same status CAS and never-overwrite rule as the other+-- cancel-ack writes; the row count tells the caller whether it applied.+UPDATE agent_task_queue+SET retired_session_id = COALESCE(retired_session_id, sqlc.arg('retired_session_id'))+WHERE id = sqlc.arg('id') AND status = 'cancelled';+-- name: SetAgentTaskErrorIfEmpty :exec-- Companion to SetAgentTaskBranchName for the cancel-ack path. A cancelled-- worktree task whose Finalize ABORTED has no branch to deliver — the errordiff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex 9687de4fc3..cb58d6148a 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -1292,6 +1292,10 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)AND NOT (COALESCE(error, '') ILIKE '%could not resolve authentication method%')AND NOT (COALESCE(error, '') ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'AND COALESCE(error, '') ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')+ -- MUL-8188: a runtime that names its own transcript invalid (Kiro panics+ -- with "invalid conversation history received" on every prompt) replays+ -- the same failure on every resume. Mirrors taskfailure.UnresumableHistory.+ AND NOT (COALESCE(error, '') ILIKE '%invalid conversation history%')))-- MUL-5722, mirroring GetLastTaskSession: an overflowed resume records nodiff --git a/server/pkg/taskfailure/resume.go b/server/pkg/taskfailure/resume.goindex 59d7a82487..e85e9e926d 100644--- a/server/pkg/taskfailure/resume.go+++ b/server/pkg/taskfailure/resume.go@@ -39,9 +39,26 @@ func UnresumableHistory(errText string) bool {if errText == "" {return false}+ if invalidHistoryRe.MatchString(errText) {+ return true+ }return emptyContentRe.MatchString(errText) && historyMessageLocatorRe.MatchString(errText)}+// invalidHistoryRe matches a runtime stating outright that the conversation+// history it loaded is invalid. Kiro writes a transcript ending in a cancelled+// ToolResults with no assistant reply when a provider failure interrupts a+// tool call, then panics on every later prompt with+//+// first agent loop request should never fail: AgentLoopResponse(Custom("invalid conversation history received"))+//+// (MUL-8188). Unlike the empty-message shape this needs no second signal: the+// phrase itself names the transcript as the defect.+//+// Keep in sync with the GetLastTaskSession / GetLastChatTaskSession resume+// queries (pkg/db/queries), which apply the same text guard server-side.+var invalidHistoryRe = regexp.MustCompile(`(?i)invalid conversation history`)+// AuthMethodUnresolved reports whether an agent error is the provider// SDK refusing to resolve its own credentials — no api_key, no auth_token, and// no explicitly-omitted auth header. On a RESUMED session this isdiff --git a/server/pkg/taskfailure/resume_test.go b/server/pkg/taskfailure/resume_test.goindex 112e6f394b..7fe1dc492c 100644--- a/server/pkg/taskfailure/resume_test.go+++ b/server/pkg/taskfailure/resume_test.go@@ -60,6 +60,24 @@ func TestUnresumableHistory(t *testing.T) {errMsg: "The final assistant message must not be empty.",want: true,},+ {+ // MUL-8188, verbatim from the Kiro panic the backend surfaces.+ name: "kiro invalid conversation history panic",+ errMsg: `kiro runtime panicked: The application panicked (crashed). | Message: first agent loop request should never fail: AgentLoopResponse(Custom("invalid conversation history received")) | Location: crates/agent/src/agent/mod.rs:3744`,+ want: true,+ },+ {+ name: "invalid conversation history bare",+ errMsg: "Invalid Conversation History received",+ want: true,+ },+ {+ // A Kiro panic that says nothing about the transcript must not+ // discard the session on its own.+ name: "kiro panic unrelated to history",+ errMsg: "kiro runtime panicked: The application panicked (crashed). | Message: index out of bounds",+ want: false,+ },// --- Negatives: emptiness complaints that are NOT about history. ---{