Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6324: Reduce chat resume query load (#7151)
Multica Eve76a90f602cce
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 7006854476..b8bdfc2ade 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -198,6 +198,8 @@ var concurrentIndexCleanups = map[string]string{"345_plugin_installation_workspace_key_index": "idx_plugin_installation_workspace_key","346_plugin_storage_scope_key_index": "idx_plugin_storage_scope_key","347_plugin_secret_installation_key_index": "idx_plugin_secret_installation_key",+ "349_agent_task_queue_chat_terminal_resume_index": "idx_agent_task_queue_chat_terminal_resume",+ "350_agent_task_queue_chat_retired_session_index": "idx_agent_task_queue_chat_retired_session",}// concurrentDownIndexCleanups covers every migration whose down directiondiff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 789c4dcfc4..9dfd0ac88c 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1854,6 +1854,10 @@ func (h *Handler) failClaimedTaskBeforeLaunch(return &claimBuildFailure{outcome: outcome, status: status, message: claimMessage}}+func chatSessionResumeFallbackNeeded(priorSessionID, priorWorkDir string) bool {+ return priorSessionID == "" || priorWorkDir == ""+}+// buildClaimedTaskResponse assembles the full daemon claim payload for a// single already-claimed task and computes the exact comment ids embedded in// it (deliveredCommentIDs). Shared by the per-runtime handler@@ -2522,21 +2526,6 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQuif cs.WorkDir.Valid {resp.PriorWorkDir = cs.WorkDir.String}- if prior, err := h.Queries.GetLastChatTaskSession(r.Context(), cs.ID); err == nil && prior.SessionID.Valid {- if resp.PriorSessionID == "" && prior.RuntimeID == task.RuntimeID {- resp.PriorSessionID = prior.SessionID.String- }- if prior.WorkDir.Valid && resp.PriorWorkDir == "" {- resp.PriorWorkDir = prior.WorkDir.String- }- }- // MUL-5305: if the most recent terminal task on this chat session- // withheld its Codex session (rollout missing), we resumed an older- // session (or none) above — disclose the continuity gap so the next- // turn tells the user the most recent turn's context is missing.- if missing, err := h.Queries.GetLatestChatTaskRolloutMissing(r.Context(), cs.ID); err == nil && missing {- resp.PriorSessionResumeUnavailable = true- }}// Resolve the user-message input batch for this run. A task-owned// task (chat_input_task_id set) reads exactly the user messages@@ -2577,6 +2566,49 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu}}+ // Input ownership is the claim's fail-closed boundary. Resume-history+ // reads belong after it: a task that cannot load its input is preserved+ // for redelivery and must not spend two more queries before returning.+ if !task.ForceFreshSession {+ // GetLastChatTaskSession currently has exactly two consumers: the+ // prior session and prior workdir fields. Keep this guard coupled to+ // both so adding a third consumer cannot silently skip its fallback.+ if chatSessionResumeFallbackNeeded(resp.PriorSessionID, resp.PriorWorkDir) {+ h.Metrics.RecordChatClaimSessionFallbackNeeded()+ started := time.Now()+ prior, err := h.Queries.GetLastChatTaskSession(r.Context(), cs.ID)+ h.Metrics.ObserveChatClaimLastSessionQuery(time.Since(started).Seconds())+ switch {+ case err == nil && prior.SessionID.Valid:+ h.Metrics.RecordChatClaimSessionFallbackHit()+ if resp.PriorSessionID == "" && prior.RuntimeID == task.RuntimeID {+ resp.PriorSessionID = prior.SessionID.String+ }+ if prior.WorkDir.Valid && resp.PriorWorkDir == "" {+ resp.PriorWorkDir = prior.WorkDir.String+ }+ case errors.Is(err, pgx.ErrNoRows):+ h.Metrics.RecordChatClaimSessionFallbackMiss()+ case err == nil:+ // Defensive only: the SQL excludes NULL session ids, but+ // preserve miss semantics if that contract ever changes.+ h.Metrics.RecordChatClaimSessionFallbackMiss()+ default:+ h.Metrics.RecordChatClaimSessionFallbackError()+ }+ }++ // MUL-5305: continuity-gap disclosure is independent of whether+ // either pointer field needed fallback, so this query stays+ // unconditional for non-force-fresh chat claims.+ started := time.Now()+ missing, err := h.Queries.GetLatestChatTaskRolloutMissing(r.Context(), cs.ID)+ h.Metrics.ObserveChatClaimRolloutMissingQuery(time.Since(started).Seconds())+ if err == nil && missing {+ resp.PriorSessionResumeUnavailable = true+ }+ }+parts := make([]string, 0, len(unanswered))for _, m := range unanswered {if strings.TrimSpace(m.Content) != "" {diff --git a/server/internal/handler/daemon_chat_resume_fallback_test.go b/server/internal/handler/daemon_chat_resume_fallback_test.gonew file mode 100644index 0000000000..0ff79adde3--- /dev/null+++ b/server/internal/handler/daemon_chat_resume_fallback_test.go@@ -0,0 +1,197 @@+package handler++import (+ "context"+ "errors"+ "net/http"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/prometheus/client_golang/prometheus"+)++type failChatInputQueryDB struct {+ delegate db.DBTX+}++func (f *failChatInputQueryDB) Exec(ctx context.Context, query string, args ...interface{}) (pgconn.CommandTag, error) {+ return f.delegate.Exec(ctx, query, args...)+}++func (f *failChatInputQueryDB) Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error) {+ if strings.Contains(query, "-- name: ListChatInputMessages") {+ return nil, errors.New("injected chat input load failure")+ }+ return f.delegate.Query(ctx, query, args...)+}++func (f *failChatInputQueryDB) QueryRow(ctx context.Context, query string, args ...interface{}) pgx.Row {+ return f.delegate.QueryRow(ctx, query, args...)+}++func TestChatSessionResumeFallbackNeeded(t *testing.T) {+ tests := []struct {+ name string+ priorSessionID string+ priorWorkDir string+ want bool+ }{+ {name: "both present", priorSessionID: "session", priorWorkDir: "/work", want: false},+ {name: "session missing", priorWorkDir: "/work", want: true},+ {name: "workdir missing", priorSessionID: "session", want: true},+ {name: "both missing", want: true},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := chatSessionResumeFallbackNeeded(tt.priorSessionID, tt.priorWorkDir); got != tt.want {+ t.Fatalf("chatSessionResumeFallbackNeeded(%q, %q) = %v, want %v", tt.priorSessionID, tt.priorWorkDir, got, tt.want)+ }+ })+ }+}++func TestClaimTaskChatCompletePointerSkipsSessionFallbackQuery(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)++ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "complete resume pointer",+ "session_id": "pointer-session",+ "work_dir": "/pointer-workdir",+ "runtime_id": runtimeID,+ })+ dbfx.Insert(t, "chat_message", testutil.Cols{+ "chat_session_id": chatSessionID,+ "role": "user",+ "content": "keep the direct pointer",+ })+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "priority": 1000,+ })++ claimMetrics := obsmetrics.NewBusinessMetrics()+ h := *testHandler+ h.Metrics = claimMetrics++ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/claim", nil,+ testWorkspaceID, daemonID)+ req = testutil.WithURLParams(req, "runtimeId", runtimeID)+ w := testutil.Call(t, h.ClaimTaskByRuntime, req).Want(http.StatusOK)+ var resp struct {+ Task *claimRuntimeGuardTask `json:"task"`+ }+ w.JSON(&resp)+ if resp.Task == nil {+ t.Fatal("expected a claimed task")+ }+ if resp.Task.PriorSessionID != "pointer-session" || resp.Task.PriorWorkDir != "/pointer-workdir" {+ t.Fatalf("claim pointer = (%q, %q), want direct chat-session pointer", resp.Task.PriorSessionID, resp.Task.PriorWorkDir)+ }++ registry := prometheus.NewRegistry()+ registry.MustRegister(claimMetrics.Collectors()...)+ families, err := registry.Gather()+ if err != nil {+ t.Fatalf("gather claim metrics: %v", err)+ }+ seenRolloutQuery := false+ for _, family := range families {+ switch family.GetName() {+ case "multica_chat_claim_session_fallback_needed_total":+ if len(family.Metric) != 1 || family.Metric[0].GetCounter().GetValue() != 0 {+ t.Fatalf("complete pointer unexpectedly needed session fallback: %v", family)+ }+ case "multica_chat_claim_session_fallback_result_total":+ t.Fatalf("complete pointer unexpectedly emitted a session fallback result: %v", family)+ case "multica_chat_claim_resume_query_duration_seconds":+ for _, metric := range family.Metric {+ for _, label := range metric.Label {+ if label.GetName() != "query" {+ continue+ }+ switch label.GetValue() {+ case "rollout_missing":+ seenRolloutQuery = true+ case "last_session":+ t.Fatal("complete pointer unexpectedly ran GetLastChatTaskSession")+ }+ }+ }+ }+ }+ if !seenRolloutQuery {+ t.Fatal("independent rollout-missing query was not observed")+ }+}++func TestClaimTaskChatInputLoadFailureSkipsResumeQueries(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "input failure skips resume history",+ "runtime_id": runtimeID,+ })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "priority": 1000,+ })+ dbfx.Exec(t, `UPDATE agent_task_queue SET chat_input_task_id = id WHERE id = $1`, taskID)+ dbfx.Insert(t, "chat_message", testutil.Cols{+ "chat_session_id": chatSessionID,+ "role": "user",+ "content": "input query should fail before resume history",+ "task_id": taskID,+ })++ claimMetrics := obsmetrics.NewBusinessMetrics()+ h := *testHandler+ h.Metrics = claimMetrics+ h.Queries = db.New(&failChatInputQueryDB{delegate: testPool})++ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/claim", nil,+ testWorkspaceID, daemonID)+ req = testutil.WithURLParams(req, "runtimeId", runtimeID)+ testutil.Call(t, h.ClaimTaskByRuntime, req).Want(http.StatusInternalServerError)++ var status string+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status)+ if status != "dispatched" {+ t.Fatalf("task status after input load failure = %q, want dispatched for redelivery", status)+ }++ registry := prometheus.NewRegistry()+ registry.MustRegister(claimMetrics.Collectors()...)+ families, err := registry.Gather()+ if err != nil {+ t.Fatalf("gather claim metrics: %v", err)+ }+ for _, family := range families {+ switch family.GetName() {+ case "multica_chat_claim_session_fallback_needed_total":+ if len(family.Metric) != 1 || family.Metric[0].GetCounter().GetValue() != 0 {+ t.Fatalf("input load failure unexpectedly needed session fallback: %v", family)+ }+ case "multica_chat_claim_session_fallback_result_total":+ t.Fatalf("input load failure unexpectedly emitted a session fallback result: %v", family)+ case "multica_chat_claim_resume_query_duration_seconds":+ t.Fatalf("input load failure unexpectedly ran a resume-history query: %v", family)+ }+ }+}diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.goindex 1ee16e9590..6b622a4a33 100644--- a/server/internal/metrics/business.go+++ b/server/internal/metrics/business.go@@ -9,6 +9,8 @@ import (var taskDurationBuckets = []float64{1, 2.5, 5, 10, 30, 60, 120, 300, 600, 1200, 3600, 7200}+var chatClaimResumeQueryDurationBuckets = []float64{0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5}+type activeTaskLabels struct {source stringruntimeMode string@@ -33,6 +35,9 @@ type BusinessMetrics struct {taskQueuedExpired *prometheus.CounterVectaskLeaseExpired *prometheus.CounterVec+ chatClaimSessionFallbackNeeded prometheus.Counter+ chatClaimSessionFallbackResult *prometheus.CounterVec+ chatClaimResumeQueryDuration *prometheus.HistogramVecruntimeGCDeleted prometheus.CounterruntimeGCFailed prometheus.CounterruntimeGCBlocked prometheus.Gauge@@ -149,6 +154,25 @@ func NewBusinessMetrics() *BusinessMetrics {Name: "lease_expired_total",Help: "Total dispatched or running task leases expired by the scheduler.",}, metricLabels("multica_task_lease_expired_total")),+ chatClaimSessionFallbackNeeded: prometheus.NewCounter(prometheus.CounterOpts{+ Namespace: "multica",+ Subsystem: "chat_claim",+ Name: "session_fallback_needed_total",+ Help: "Total chat claims whose session pointer lacked a provider session or workdir.",+ }),+ chatClaimSessionFallbackResult: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica",+ Subsystem: "chat_claim",+ Name: "session_fallback_result_total",+ Help: "Total chat-claim session fallback query results (hit, miss, or error).",+ }, metricLabels("multica_chat_claim_session_fallback_result_total")),+ chatClaimResumeQueryDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{+ Namespace: "multica",+ Subsystem: "chat_claim",+ Name: "resume_query_duration_seconds",+ Help: "Duration of chat-claim resume-history queries by fixed query name.",+ Buckets: chatClaimResumeQueryDurationBuckets,+ }, metricLabels("multica_chat_claim_resume_query_duration_seconds")),runtimeGCDeleted: prometheus.NewCounter(prometheus.CounterOpts{Namespace: "multica",Subsystem: "runtime_gc",@@ -198,6 +222,9 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {m.llmRequests,m.taskQueuedExpired,m.taskLeaseExpired,+ m.chatClaimSessionFallbackNeeded,+ m.chatClaimSessionFallbackResult,+ m.chatClaimResumeQueryDuration,m.runtimeGCDeleted,m.runtimeGCFailed,m.runtimeGCBlocked,@@ -310,6 +337,49 @@ func (m *BusinessMetrics) RecordTaskLeaseExpired(source string) {m.taskLeaseExpired.WithLabelValues(NormalizeTaskSource(source)).Inc()}+// RecordChatClaimSessionFallbackNeeded counts a claim whose chat-session+// pointer lacked either the provider session or the workdir.+func (m *BusinessMetrics) RecordChatClaimSessionFallbackNeeded() {+ if m == nil {+ return+ }+ m.chatClaimSessionFallbackNeeded.Inc()+}++func (m *BusinessMetrics) RecordChatClaimSessionFallbackHit() {+ m.recordChatClaimSessionFallbackResult("hit")+}++func (m *BusinessMetrics) RecordChatClaimSessionFallbackMiss() {+ m.recordChatClaimSessionFallbackResult("miss")+}++func (m *BusinessMetrics) RecordChatClaimSessionFallbackError() {+ m.recordChatClaimSessionFallbackResult("error")+}++func (m *BusinessMetrics) recordChatClaimSessionFallbackResult(result string) {+ if m == nil {+ return+ }+ m.chatClaimSessionFallbackResult.WithLabelValues(result).Inc()+}++func (m *BusinessMetrics) observeChatClaimResumeQuery(query string, seconds float64) {+ if m == nil || seconds < 0 {+ return+ }+ m.chatClaimResumeQueryDuration.WithLabelValues(query).Observe(seconds)+}++func (m *BusinessMetrics) ObserveChatClaimLastSessionQuery(seconds float64) {+ m.observeChatClaimResumeQuery("last_session", seconds)+}++func (m *BusinessMetrics) ObserveChatClaimRolloutMissingQuery(seconds float64) {+ m.observeChatClaimResumeQuery("rollout_missing", seconds)+}+// costUSDTicks is the provider's own price for this usage in 1e-10 USD, or 0// when it reported none. When present it wins over the rate table: the table// cannot express request-level rules such as xAI's 2x surcharge above a 200Kdiff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.goindex a65b5ac08a..978ae47f70 100644--- a/server/internal/metrics/business_test.go+++ b/server/internal/metrics/business_test.go@@ -66,6 +66,29 @@ func TestBusinessMetricsFailureReasonUsesCanonicalClassifier(t *testing.T) {}}+func TestBusinessMetricsChatClaimResumeObservations(t *testing.T) {+ m := NewBusinessMetrics()++ m.RecordChatClaimSessionFallbackNeeded()+ m.RecordChatClaimSessionFallbackHit()+ m.RecordChatClaimSessionFallbackMiss()+ m.RecordChatClaimSessionFallbackError()+ m.ObserveChatClaimLastSessionQuery(0.01)+ m.ObserveChatClaimRolloutMissingQuery(0.02)++ if got := testutil.ToFloat64(m.chatClaimSessionFallbackNeeded); got != 1 {+ t.Errorf("chat claim fallback needed = %v, want 1", got)+ }+ for _, result := range []string{"hit", "miss", "error"} {+ if got := testutil.ToFloat64(m.chatClaimSessionFallbackResult.WithLabelValues(result)); got != 1 {+ t.Errorf("chat claim fallback %s = %v, want 1", result, got)+ }+ }+ if got := testutil.CollectAndCount(m.chatClaimResumeQueryDuration); got != 2 {+ t.Fatalf("chat claim resume query series = %d, want 2", got)+ }+}+func TestBusinessMetricsLLMPricingAndUnpricedTokens(t *testing.T) {m := NewBusinessMetrics()@@ -108,6 +131,10 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {m.RecordTaskFailed("issue", "local", taskfailure.ReasonTimeout.String())m.RecordTaskQueuedExpired("issue", "local")m.RecordTaskLeaseExpired("issue")+ m.RecordChatClaimSessionFallbackNeeded()+ m.RecordChatClaimSessionFallbackHit()+ m.ObserveChatClaimLastSessionQuery(0.01)+ m.ObserveChatClaimRolloutMissingQuery(0.01)m.RecordLLMUsage("issue", "local", "codex", "gpt-5.4", 1, 1, 1, 1, 0)m.RecordLLMUsage("issue", "local", "custom-provider", "custom-model", 1, 0, 0, 0, 0)diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex caca63badb..8f3911e02e 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -30,27 +30,31 @@ const (labelEventKind = "event_kind"labelAction = "action"labelResult = "result"+ labelQuery = "query"labelOp = "op"labelGate = "gate")var businessMetricLabels = map[string][]string{- "multica_agent_task_enqueued_total": {labelSource, labelRuntimeMode},- "multica_agent_task_dispatched_total": {labelSource, labelRuntimeMode},- "multica_agent_task_started_total": {labelSource, labelRuntimeMode, labelProvider},- "multica_agent_task_terminal_total": {labelSource, labelRuntimeMode, labelTerminalStatus},- "multica_agent_task_failed_total": {labelSource, labelRuntimeMode, labelFailureReason},- "multica_agent_task_queue_wait_seconds": {labelSource, labelRuntimeMode},- "multica_agent_task_run_seconds": {labelSource, labelRuntimeMode, labelTerminalStatus},- "multica_agent_task_total_seconds": {labelSource, labelRuntimeMode, labelTerminalStatus},- "multica_agent_task_in_progress": {labelSource, labelRuntimeMode},- "multica_agent_task_iteration_count": {labelSource, labelTerminalStatus},- "multica_llm_tokens_total": {labelProvider, labelModel, labelTokenType, labelRuntimeMode, labelSource},- "multica_llm_cost_usd_total": {labelProvider, labelModel, labelTokenType, labelRuntimeMode, labelSource},- "multica_llm_unpriced_tokens_total": {labelProvider, labelModelAlias, labelTokenType},- "multica_llm_request_total": {labelProvider, labelModel, labelRuntimeMode},- "multica_task_queued_expired_total": {labelSource, labelRuntimeMode},- "multica_task_lease_expired_total": {labelSource},+ "multica_agent_task_enqueued_total": {labelSource, labelRuntimeMode},+ "multica_agent_task_dispatched_total": {labelSource, labelRuntimeMode},+ "multica_agent_task_started_total": {labelSource, labelRuntimeMode, labelProvider},+ "multica_agent_task_terminal_total": {labelSource, labelRuntimeMode, labelTerminalStatus},+ "multica_agent_task_failed_total": {labelSource, labelRuntimeMode, labelFailureReason},+ "multica_agent_task_queue_wait_seconds": {labelSource, labelRuntimeMode},+ "multica_agent_task_run_seconds": {labelSource, labelRuntimeMode, labelTerminalStatus},+ "multica_agent_task_total_seconds": {labelSource, labelRuntimeMode, labelTerminalStatus},+ "multica_agent_task_in_progress": {labelSource, labelRuntimeMode},+ "multica_agent_task_iteration_count": {labelSource, labelTerminalStatus},+ "multica_llm_tokens_total": {labelProvider, labelModel, labelTokenType, labelRuntimeMode, labelSource},+ "multica_llm_cost_usd_total": {labelProvider, labelModel, labelTokenType, labelRuntimeMode, labelSource},+ "multica_llm_unpriced_tokens_total": {labelProvider, labelModelAlias, labelTokenType},+ "multica_llm_request_total": {labelProvider, labelModel, labelRuntimeMode},+ "multica_task_queued_expired_total": {labelSource, labelRuntimeMode},+ "multica_task_lease_expired_total": {labelSource},+ "multica_chat_claim_session_fallback_needed_total": {},+ "multica_chat_claim_session_fallback_result_total": {labelResult},+ "multica_chat_claim_resume_query_duration_seconds": {labelQuery},// PR3 funnel / community / commercial."multica_signup_total": {labelSignupSource},diff --git a/server/migrations/234_agent_task_queue_retired_session_id.up.sql b/server/migrations/234_agent_task_queue_retired_session_id.up.sqlindex ae211f63d6..ada242c200 100644--- a/server/migrations/234_agent_task_queue_retired_session_id.up.sql+++ b/server/migrations/234_agent_task_queue_retired_session_id.up.sql@@ -10,7 +10,8 @@---- Nullable and write-once per row: set only when a run abandons a session it-- was told to resume. NULL — the overwhelming majority of rows — means nothing--- was retired. No index: every reader already scopes by (agent_id, issue_id)--- or chat_session_id, both of which are indexed, and the retired set within a--- scope is tiny.+-- was retired. No index was added in this migration: every reader at the time+-- scoped by (agent_id, issue_id) or chat_session_id, and the retired set within+-- a scope was tiny. Migrations 349/350 later added terminal-resume and retired-+-- session indexes after production history made that assumption too costly.ALTER TABLE agent_task_queue ADD COLUMN IF NOT EXISTS retired_session_id TEXT;diff --git a/server/migrations/349_agent_task_queue_chat_terminal_resume_index.down.sql b/server/migrations/349_agent_task_queue_chat_terminal_resume_index.down.sqlnew file mode 100644index 0000000000..38ae5102c4--- /dev/null+++ b/server/migrations/349_agent_task_queue_chat_terminal_resume_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_chat_terminal_resume;diff --git a/server/migrations/349_agent_task_queue_chat_terminal_resume_index.up.sql b/server/migrations/349_agent_task_queue_chat_terminal_resume_index.up.sqlnew file mode 100644index 0000000000..564d722418--- /dev/null+++ b/server/migrations/349_agent_task_queue_chat_terminal_resume_index.up.sql@@ -0,0 +1,13 @@+-- Bounds both chat resume-history queries to one chat instead of scanning the+-- global terminal-task population. Keep all three terminal states: the+-- completed/failed rollout-missing query implies this wider predicate, while+-- GetLastChatTaskSession also needs cancelled rows. chat_session_id IS NOT NULL+-- excludes issue tasks from this hot write-table index.+--+-- Do NOT add session_id IS NOT NULL. The resume_overflow_at CTE must read+-- codex_resume_oversized failures whose NULL session_id marks the cutoff; a+-- narrower predicate would silently send that CTE back to a full-table scan.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_chat_terminal_resume+ON agent_task_queue (chat_session_id, session_id, completed_at DESC)+WHERE chat_session_id IS NOT NULL+ AND status IN ('completed', 'failed', 'cancelled');diff --git a/server/migrations/350_agent_task_queue_chat_retired_session_index.down.sql b/server/migrations/350_agent_task_queue_chat_retired_session_index.down.sqlnew file mode 100644index 0000000000..758f05a597--- /dev/null+++ b/server/migrations/350_agent_task_queue_chat_retired_session_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_chat_retired_session;diff --git a/server/migrations/350_agent_task_queue_chat_retired_session_index.up.sql b/server/migrations/350_agent_task_queue_chat_retired_session_index.up.sqlnew file mode 100644index 0000000000..21278ffd78--- /dev/null+++ b/server/migrations/350_agent_task_queue_chat_retired_session_index.up.sql@@ -0,0 +1,8 @@+-- Retired sessions need their own sparse index: the database has no CHECK+-- constraint proving retired_session_id is present only on terminal rows, so+-- folding this into migration 349's terminal predicate could resurrect a+-- retired session by silently omitting a valid non-terminal marker.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_chat_retired_session+ON agent_task_queue (chat_session_id, retired_session_id)+WHERE chat_session_id IS NOT NULL+ AND retired_session_id IS NOT NULL;diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 5703e8d0be..bf89d26f61 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -921,6 +921,11 @@ type GetLastChatTaskSessionRow struct {// state. Keep this list in sync with resumeUnsafeFailureReason and// GetLastTaskSession.//+// The plan depends on idx_agent_task_queue_chat_terminal_resume for the+// terminal/cutoff scans and idx_agent_task_queue_chat_retired_session for the+// retired set. Keep their partial predicates broad enough for every CTE here,+// especially the NULL-session resume_overflow_at rows.+//// 'cancelled' is resumable and its absence was GH #6340: the user stops a turn// the agent had already started answering, and the next message starts from// nothing. A cancelled row only carries a session_id because the daemon pinneddiff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex d9a5e62a37..17e0c42430 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -991,6 +991,11 @@ RETURNING *;-- state. Keep this list in sync with resumeUnsafeFailureReason and-- GetLastTaskSession.--+-- The plan depends on idx_agent_task_queue_chat_terminal_resume for the+-- terminal/cutoff scans and idx_agent_task_queue_chat_retired_session for the+-- retired set. Keep their partial predicates broad enough for every CTE here,+-- especially the NULL-session resume_overflow_at rows.+---- 'cancelled' is resumable and its absence was GH #6340: the user stops a turn-- the agent had already started answering, and the next message starts from-- nothing. A cancelled row only carries a session_id because the daemon pinned