Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8270: fix(db): keep lease claims within query limits (#9563)
mrlonely16a067f30ab2
diff --git a/server/internal/service/object_cleanup_claim_test.go b/server/internal/service/object_cleanup_claim_test.gonew file mode 100644index 0000000000..6262116af2--- /dev/null+++ b/server/internal/service/object_cleanup_claim_test.go@@ -0,0 +1,98 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+)++func TestObjectCleanupClaimsOneRowWithStaleStatistics(t *testing.T) {+ cases := []struct {+ table string+ seed string+ states []string+ claim func(context.Context, *db.Queries, pgtype.UUID) (string, error)+ }{+ {+ table: "channel_media_pending_object",+ seed: `INSERT INTO channel_media_pending_object+ (storage_key, workspace_id, chat_message_id, storage_url, state, created_at, next_attempt_at)+ SELECT 'key-' || n, gen_random_uuid(), gen_random_uuid(), 'https://objects.test/' || n,+ $3, now() - interval '2 hours', now() - interval '2 hours' + n * interval '1 second'+ FROM generate_series($1::int, $2::int) n`,+ states: []string{"pending", "deleting", "tombstoned"},+ claim: func(ctx context.Context, queries *db.Queries, lease pgtype.UUID) (string, error) {+ row, err := queries.ClaimNextChannelMediaPendingObjectForReconcile(ctx, db.ClaimNextChannelMediaPendingObjectForReconcileParams{+ LeaseToken: lease, Lease: pgInterval(channelMediaReconcileLease),+ SettleDelay: pgInterval(ChannelMediaReconcileSettleDelay),+ })+ return row.StorageKey, err+ },+ },+ {+ table: "issue_source_context_object_intent",+ seed: `INSERT INTO issue_source_context_object_intent+ (storage_key, workspace_id, source_context_id, attachment_id, object_url, state, created_at, next_attempt_at)+ SELECT 'key-' || n, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'https://objects.test/' || n,+ $3, now() - interval '2 hours', now() - interval '2 hours' + n * interval '1 second'+ FROM generate_series($1::int, $2::int) n`,+ states: []string{"pending", "deleting"},+ claim: func(ctx context.Context, queries *db.Queries, lease pgtype.UUID) (string, error) {+ row, err := queries.ClaimSourceContextObjectIntentForCleanup(ctx, lease)+ return row.StorageKey, err+ },+ },+ }+ for _, testCase := range cases {+ for _, state := range testCase.states {+ t.Run(testCase.table+"/"+state, func(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ tx, err := sharedTestPool(t).Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(context.Background())+ // Copy the real schema so statistics and claims stay local to this test.+ table := pgx.Identifier{testCase.table}.Sanitize()+ if _, err := tx.Exec(ctx, "CREATE TEMP TABLE "+table+" (LIKE public."+table+" INCLUDING ALL) ON COMMIT DROP"); err != nil {+ t.Fatal(err)+ }+ if _, err := tx.Exec(ctx, testCase.seed, 1, 1, state); err != nil {+ t.Fatal(err)+ }+ // Add due rows after ANALYZE without forcing a particular query plan.+ if _, err := tx.Exec(ctx, "ANALYZE "+table); err != nil {+ t.Fatal(err)+ }+ if _, err := tx.Exec(ctx, testCase.seed, 2, 3, state); err != nil {+ t.Fatal(err)+ }+ queries := db.New(tx)+ for index := 1; index <= 3; index++ {+ key, err := testCase.claim(ctx, queries, dbid.NewV7())+ if err != nil || key != fmt.Sprintf("key-%d", index) {+ t.Fatalf("claim %d returned %q, err=%v", index, key, err)+ }+ var claimed int+ if err := tx.QueryRow(ctx, "SELECT count(*) FROM "+table+" WHERE lease_token IS NOT NULL").Scan(&claimed); err != nil {+ t.Fatal(err)+ }+ if claimed != index {+ t.Fatalf("after %d claims, %d rows hold leases; want %d", index, claimed, index)+ }+ }+ if _, err := testCase.claim(ctx, queries, dbid.NewV7()); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("claim while all leases are active: %v, want no rows", err)+ }+ })+ }+ }+}diff --git a/server/internal/service/runtime_health_gate_test.go b/server/internal/service/runtime_health_gate_test.goindex c0c598ebc0..25d05c5c1d 100644--- a/server/internal/service/runtime_health_gate_test.go+++ b/server/internal/service/runtime_health_gate_test.go@@ -3,7 +3,9 @@ package serviceimport ("context""errors"+ "fmt""testing"+ "time""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"@@ -11,6 +13,86 @@ import (db "github.com/multica-ai/multica/server/pkg/db/generated")+func TestStaleDispatchRecoveryHonorsBatchLimitWithStaleStatistics(t *testing.T) {+ for _, limit := range []int32{0, 1, 2, 10} {+ t.Run(fmt.Sprintf("limit_%d", limit), func(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ tx, err := sharedTestPool(t).Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(context.Background())+ // Copy the real schemas so statistics and claims stay local to this test.+ for _, name := range []string{"agent", "agent_runtime", "agent_task_queue"} {+ table := pgx.Identifier{name}.Sanitize()+ if _, err := tx.Exec(ctx, "CREATE TEMP TABLE "+table+" (LIKE public."+table+" INCLUDING ALL) ON COMMIT DROP"); err != nil {+ t.Fatal(err)+ }+ }+ var runtimeID, agentID pgtype.UUID+ if err := tx.QueryRow(ctx, `+ INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, status, visibility, last_seen_at)+ VALUES (gen_random_uuid(), 'batch reclaim', 'local', 'multica_daemon', 'online', 'public', now())+ RETURNING id+ `).Scan(&runtimeID); err != nil {+ t.Fatal(err)+ }+ if err := tx.QueryRow(ctx, `+ INSERT INTO agent (workspace_id, name, runtime_mode, runtime_id)+ SELECT workspace_id, 'batch reclaim', 'local', id FROM agent_runtime WHERE id = $1+ RETURNING id+ `, runtimeID).Scan(&agentID); err != nil {+ t.Fatal(err)+ }+ const seed = `INSERT INTO agent_task_queue (agent_id, runtime_id, status, dispatched_at, priority)+ SELECT $1, $2, 'dispatched', now() - interval '10 minutes', 6 - n+ FROM generate_series($3::int, $4::int) n`+ if _, err := tx.Exec(ctx, seed, agentID, runtimeID, 1, 1); err != nil {+ t.Fatal(err)+ }+ if _, err := tx.Exec(ctx, "ANALYZE agent; ANALYZE agent_runtime; ANALYZE agent_task_queue"); err != nil {+ t.Fatal(err)+ }+ if _, err := tx.Exec(ctx, seed, agentID, runtimeID, 2, 5); err != nil {+ t.Fatal(err)+ }+ queries := db.New(tx)+ params := db.ReclaimStaleDispatchedTasksForRuntimesParams{+ RuntimeIds: []pgtype.UUID{runtimeID}, PrepareLeaseSecs: 60,+ ClaimRecoverySecs: 30, RuntimeStaleSecs: RuntimeClaimFreshnessSeconds, MaxTasks: limit,+ }+ claimed := 0+ for {+ batch, err := queries.ReclaimStaleDispatchedTasksForRuntimes(ctx, params)+ if err != nil {+ t.Fatal(err)+ }+ want := min(int(limit), 5-claimed)+ if len(batch) != want {+ t.Fatalf("reclaimed %d tasks, want %d (limit %d, already claimed %d)", len(batch), want, limit, claimed)+ }+ for _, task := range batch {+ if task.Priority > int32(5-claimed) || task.Priority <= int32(5-claimed-want) {+ t.Fatalf("reclaimed priority %d outside the next %d highest-priority tasks", task.Priority, want)+ }+ }+ claimed += len(batch)+ var renewed int+ if err := tx.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE prepare_lease_expires_at > now()`).Scan(&renewed); err != nil {+ t.Fatal(err)+ }+ if renewed != claimed {+ t.Fatalf("renewed %d task leases after returning %d tasks", renewed, claimed)+ }+ if want == 0 {+ break+ }+ }+ })+ }+}+// TestRuntimeHealthGatesClaimsAndStaleDispatchRecovery directly covers every// SQL release path that can hand work to a daemon. Offline, stale, or wrong// runtimes must leave the row untouched; a fresh scoped runtime may claim ordiff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex b8ca298594..f455618cf1 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -7896,10 +7896,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg}const reclaimStaleDispatchedTasksForRuntimes = `-- name: ReclaimStaleDispatchedTasksForRuntimes :many-UPDATE agent_task_queue-SET dispatched_at = now(),- prepare_lease_expires_at = now() + make_interval(secs => $1::double precision)-WHERE id IN (+WITH candidates AS MATERIALIZED (SELECT atq.id FROM agent_task_queue atqWHERE atq.runtime_id = ANY($2::uuid[])AND atq.status = 'dispatched'@@ -7934,6 +7931,10 @@ WHERE id IN (LIMIT $5::intFOR UPDATE SKIP LOCKED)+UPDATE agent_task_queue+SET dispatched_at = now(),+ prepare_lease_expires_at = now() + make_interval(secs => $1::double precision)+WHERE id IN (SELECT id FROM candidates)RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step`@@ -7952,6 +7953,8 @@ type ReclaimStaleDispatchedTasksForRuntimesParams struct {// query (dispatched, never started, past the recovery window, expired/absent// prepare lease) and the same dispatched_at refresh; only the runtime filter// (= ANY) and the LIMIT (max_tasks instead of 1) differ.+// MATERIALIZED pins the candidate set so nested-loop rescans cannot exceed+// max_tasks.func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, arg ReclaimStaleDispatchedTasksForRuntimesParams) ([]AgentTaskQueue, error) {rows, err := q.db.Query(ctx, reclaimStaleDispatchedTasksForRuntimes,arg.PrepareLeaseSecs,diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.goindex 10b473751d..f33620b7d5 100644--- a/server/pkg/db/generated/channel.sql.go+++ b/server/pkg/db/generated/channel.sql.go@@ -336,12 +336,7 @@ func (q *Queries) ClaimChannelMediaPendingObjectsForBind(ctx context.Context, ar}const claimNextChannelMediaPendingObjectForReconcile = `-- name: ClaimNextChannelMediaPendingObjectForReconcile :one-UPDATE channel_media_pending_object AS obj-SET state = CASE WHEN obj.state = 'tombstoned' THEN 'tombstoned' ELSE 'deleting' END,- lease_token = $1,- lease_expires_at = now() + $2::interval,- attempt = obj.attempt + 1-FROM (+WITH due AS MATERIALIZED (SELECT cand.storage_key FROM channel_media_pending_object AS candWHERE cand.next_attempt_at <= now()AND (@@ -352,7 +347,13 @@ FROM (ORDER BY cand.next_attempt_atLIMIT 1FOR UPDATE SKIP LOCKED-) AS due+)+UPDATE channel_media_pending_object AS obj+SET state = CASE WHEN obj.state = 'tombstoned' THEN 'tombstoned' ELSE 'deleting' END,+ lease_token = $1,+ lease_expires_at = now() + $2::interval,+ attempt = obj.attempt + 1+FROM dueWHERE obj.storage_key = due.storage_keyRETURNING obj.storage_key, obj.workspace_id, obj.chat_message_id, obj.storage_url, obj.installation_id, obj.state, obj.lease_token, obj.lease_expires_at, obj.attempt, obj.next_attempt_at, obj.last_error, obj.tombstone_pass, obj.created_at`@@ -369,6 +370,8 @@ type ClaimNextChannelMediaPendingObjectForReconcileParams struct {// while earlier rows ran, and could expire and be reclaimed before its own// DELETE was ever tried, inflating attempt/backoff for work that never// happened. One row per claim means attempt counts attempts.+// MATERIALIZED pins the bounded candidate set so a nested-loop rescan cannot+// move the LIMIT window to another row after an update.//// Due means (a) 'pending' rows older than the settle delay — an operational// buffer only; correctness comes from the state flip, after which a bind candiff --git a/server/pkg/db/generated/source_context.sql.go b/server/pkg/db/generated/source_context.sql.goindex 5b601d2537..f100167108 100644--- a/server/pkg/db/generated/source_context.sql.go+++ b/server/pkg/db/generated/source_context.sql.go@@ -78,11 +78,7 @@ func (q *Queries) AttachIssueSourceContext(ctx context.Context, arg AttachIssueS}const claimSourceContextObjectIntentForCleanup = `-- name: ClaimSourceContextObjectIntentForCleanup :one-UPDATE issue_source_context_object_intent AS intent-SET state = 'deleting',- lease_token = $1,- lease_expires_at = now() + interval '2 minutes'-FROM (+WITH due AS MATERIALIZED (SELECT candidate.storage_keyFROM issue_source_context_object_intent candidateWHERE candidate.next_attempt_at <= now()@@ -93,11 +89,18 @@ FROM (ORDER BY candidate.next_attempt_at, candidate.storage_keyLIMIT 1FOR UPDATE SKIP LOCKED-) due+)+UPDATE issue_source_context_object_intent AS intent+SET state = 'deleting',+ lease_token = $1,+ lease_expires_at = now() + interval '2 minutes'+FROM dueWHERE intent.storage_key = due.storage_keyRETURNING intent.storage_key, intent.workspace_id, intent.source_context_id, intent.attachment_id, intent.object_url, intent.state, intent.lease_token, intent.lease_expires_at, intent.next_attempt_at, intent.last_error, intent.created_at`+// MATERIALIZED pins the single candidate so nested-loop rescans cannot lease+// extra objects.func (q *Queries) ClaimSourceContextObjectIntentForCleanup(ctx context.Context, leaseToken pgtype.UUID) (IssueSourceContextObjectIntent, error) {row := q.db.QueryRow(ctx, claimSourceContextObjectIntentForCleanup, leaseToken)var i IssueSourceContextObjectIntentdiff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 3949165f69..23c798fe73 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -902,10 +902,9 @@ RETURNING *;-- query (dispatched, never started, past the recovery window, expired/absent-- prepare lease) and the same dispatched_at refresh; only the runtime filter-- (= ANY) and the LIMIT (max_tasks instead of 1) differ.-UPDATE agent_task_queue-SET dispatched_at = now(),- prepare_lease_expires_at = now() + make_interval(secs => @prepare_lease_secs::double precision)-WHERE id IN (+-- MATERIALIZED pins the candidate set so nested-loop rescans cannot exceed+-- max_tasks.+WITH candidates AS MATERIALIZED (SELECT atq.id FROM agent_task_queue atqWHERE atq.runtime_id = ANY(@runtime_ids::uuid[])AND atq.status = 'dispatched'@@ -940,6 +939,10 @@ WHERE id IN (LIMIT @max_tasks::intFOR UPDATE SKIP LOCKED)+UPDATE agent_task_queue+SET dispatched_at = now(),+ prepare_lease_expires_at = now() + make_interval(secs => @prepare_lease_secs::double precision)+WHERE id IN (SELECT id FROM candidates)RETURNING *;-- name: ExtendAgentTaskPrepareLease :onediff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sqlindex f8be647f92..e7a7f46596 100644--- a/server/pkg/db/queries/channel.sql+++ b/server/pkg/db/queries/channel.sql@@ -1303,6 +1303,8 @@ RETURNING storage_key;-- while earlier rows ran, and could expire and be reclaimed before its own-- DELETE was ever tried, inflating attempt/backoff for work that never-- happened. One row per claim means attempt counts attempts.+-- MATERIALIZED pins the bounded candidate set so a nested-loop rescan cannot+-- move the LIMIT window to another row after an update.---- Due means (a) 'pending' rows older than the settle delay — an operational-- buffer only; correctness comes from the state flip, after which a bind can@@ -1313,12 +1315,7 @@ RETURNING storage_key;-- FOR UPDATE SKIP LOCKED keeps replicas off each other's row; the-- object-storage DELETE happens outside any transaction, gated by the lease-- token. No row (ErrNoRows) means nothing is due — the sweep is done.-UPDATE channel_media_pending_object AS obj-SET state = CASE WHEN obj.state = 'tombstoned' THEN 'tombstoned' ELSE 'deleting' END,- lease_token = @lease_token,- lease_expires_at = now() + @lease::interval,- attempt = obj.attempt + 1-FROM (+WITH due AS MATERIALIZED (SELECT cand.storage_key FROM channel_media_pending_object AS candWHERE cand.next_attempt_at <= now()AND (@@ -1329,7 +1326,13 @@ FROM (ORDER BY cand.next_attempt_atLIMIT 1FOR UPDATE SKIP LOCKED-) AS due+)+UPDATE channel_media_pending_object AS obj+SET state = CASE WHEN obj.state = 'tombstoned' THEN 'tombstoned' ELSE 'deleting' END,+ lease_token = @lease_token,+ lease_expires_at = now() + @lease::interval,+ attempt = obj.attempt + 1+FROM dueWHERE obj.storage_key = due.storage_keyRETURNING obj.*;diff --git a/server/pkg/db/queries/source_context.sql b/server/pkg/db/queries/source_context.sqlindex e63abafc88..065159e2d1 100644--- a/server/pkg/db/queries/source_context.sql+++ b/server/pkg/db/queries/source_context.sql@@ -130,11 +130,9 @@ WHERE workspace_id = sqlc.arg(workspace_id)RETURNING storage_key;-- name: ClaimSourceContextObjectIntentForCleanup :one-UPDATE issue_source_context_object_intent AS intent-SET state = 'deleting',- lease_token = sqlc.arg(lease_token),- lease_expires_at = now() + interval '2 minutes'-FROM (+-- MATERIALIZED pins the single candidate so nested-loop rescans cannot lease+-- extra objects.+WITH due AS MATERIALIZED (SELECT candidate.storage_keyFROM issue_source_context_object_intent candidateWHERE candidate.next_attempt_at <= now()@@ -145,7 +143,12 @@ FROM (ORDER BY candidate.next_attempt_at, candidate.storage_keyLIMIT 1FOR UPDATE SKIP LOCKED-) due+)+UPDATE issue_source_context_object_intent AS intent+SET state = 'deleting',+ lease_token = sqlc.arg(lease_token),+ lease_expires_at = now() + interval '2 minutes'+FROM dueWHERE intent.storage_key = due.storage_keyRETURNING intent.*;