Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(task): settle a run once when its completion is redelivered (#22637)

Arvin Xue3073a9aaf22
diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.ts
index 21c19225734..eb956664ada 100644
--- a/apps/server/src/modules/Redis/keys.ts
+++ b/apps/server/src/modules/Redis/keys.ts
@@ -159,6 +159,12 @@ export const RedisKeys = {
* Full key: agentRun:run_slots:v1:{userId}
*/
runSlots: (userId: string): string => `run_slots:v1:${userId}`,
+ /**
+ * Whether one operation's `onComplete` delivery is settling or has settled
+ * its Task run, so a redelivery is not applied a second time.
+ * Full key: agentRun:task_run_delivery:v1:{operationId}
+ */
+ taskRunDelivery: (operationId: string): string => `task_run_delivery:v1:${operationId}`,
},
/**
* Steer queue scope β€” see {@link RedisKeyNamespace.AGENT_STEER}.
diff --git a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts
index 91772289f24..7c5bb262e3e 100644
--- a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts
+++ b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts
@@ -2,11 +2,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { onTopicComplete } from './onTopicComplete';
-const { getServerDB, isRunAlreadySettled, lifecycleOnTopicComplete } = vi.hoisted(() => ({
- getServerDB: vi.fn(),
- isRunAlreadySettled: vi.fn(),
- lifecycleOnTopicComplete: vi.fn(),
-}));
+const { claim, getServerDB, isRunAlreadySettled, lifecycleOnTopicComplete, markSettled, release } =
+ vi.hoisted(() => ({
+ claim: vi.fn(),
+ getServerDB: vi.fn(),
+ isRunAlreadySettled: vi.fn(),
+ lifecycleOnTopicComplete: vi.fn(),
+ markSettled: vi.fn(),
+ release: vi.fn(),
+ }));
vi.mock('@/database/server', () => ({ getServerDB }));
vi.mock('@/server/services/taskLifecycle', () => ({
@@ -15,6 +19,9 @@ vi.mock('@/server/services/taskLifecycle', () => ({
}),
}));
vi.mock('@/server/services/taskLifecycle/reconcile', () => ({ isRunAlreadySettled }));
+vi.mock('@/server/services/redis', () => ({
+ redisService: { taskRunDelivery: { claim, markSettled, release } },
+}));
const makeContext = (body: Record<string, unknown>) => {
const json = vi.fn(function (payload, status = 200) {
@@ -46,6 +53,9 @@ describe('onTopicComplete webhook', () => {
getServerDB.mockReset().mockResolvedValue({ select: () => chain });
isRunAlreadySettled.mockReset().mockResolvedValue(false);
lifecycleOnTopicComplete.mockReset().mockResolvedValue(undefined);
+ claim.mockReset().mockResolvedValue('claimed');
+ markSettled.mockReset().mockResolvedValue(undefined);
+ release.mockReset().mockResolvedValue(undefined);
});
it('drives the lifecycle for a run nobody has settled yet', async () => {
@@ -80,4 +90,67 @@ describe('onTopicComplete webhook', () => {
expect(lifecycleOnTopicComplete).not.toHaveBeenCalled();
expect(json).toHaveBeenCalledWith({ skipped: 'already-settled', success: true });
});
+
+ describe('a successful run delivered more than once', () => {
+ const donePayload = { ...failedRunPayload, errorMessage: undefined, reason: 'done' };
+
+ it('settles the run on the first delivery and remembers it', async () => {
+ const { context, json } = makeContext(donePayload);
+
+ await onTopicComplete(context);
+
+ expect(lifecycleOnTopicComplete).toHaveBeenCalledTimes(1);
+ expect(markSettled).toHaveBeenCalledWith('op-1');
+ expect(json).toHaveBeenCalledWith({ success: true });
+ });
+
+ it('acks a redelivery of a settled run without driving the lifecycle again', async () => {
+ claim.mockResolvedValue('settled');
+ const { context, json } = makeContext(donePayload);
+
+ await onTopicComplete(context);
+
+ expect(lifecycleOnTopicComplete).not.toHaveBeenCalled();
+ expect(json).toHaveBeenCalledWith({ skipped: 'already-settled', success: true });
+ });
+
+ it('asks QStash to come back while the first delivery is still settling', async () => {
+ claim.mockResolvedValue('in-progress');
+ const { context, json } = makeContext(donePayload);
+
+ await onTopicComplete(context);
+
+ expect(lifecycleOnTopicComplete).not.toHaveBeenCalled();
+ expect(json).toHaveBeenCalledWith({ skipped: 'in-progress' }, 409);
+ });
+
+ it('gives the claim back when the settle fails so the retry can finish it', async () => {
+ lifecycleOnTopicComplete.mockRejectedValue(new Error('db down'));
+ const { context, json } = makeContext(donePayload);
+
+ await onTopicComplete(context);
+
+ expect(release).toHaveBeenCalledWith('op-1');
+ expect(markSettled).not.toHaveBeenCalled();
+ expect(json).toHaveBeenCalledWith({ error: 'db down' }, 500);
+ });
+
+ it('still settles the run when Redis cannot arbitrate', async () => {
+ claim.mockResolvedValue('unavailable');
+ const { context } = makeContext(donePayload);
+
+ await onTopicComplete(context);
+
+ expect(lifecycleOnTopicComplete).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not claim failed runs, which the settled check already fences', async () => {
+ const { context } = makeContext(failedRunPayload);
+
+ await onTopicComplete(context);
+
+ expect(claim).not.toHaveBeenCalled();
+ expect(lifecycleOnTopicComplete).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts
index a3b708b118b..808e5e8406d 100644
--- a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts
+++ b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts
@@ -5,6 +5,7 @@ import type { Context } from 'hono';
import { tasks } from '@/database/schemas';
import { getServerDB } from '@/database/server';
+import { redisService } from '@/server/services/redis';
import { TaskLifecycleService } from '@/server/services/taskLifecycle';
import { isRunAlreadySettled } from '@/server/services/taskLifecycle/reconcile';
@@ -83,19 +84,47 @@ export async function onTopicComplete(c: Context) {
return c.json({ skipped: 'already-settled', success: true });
}
+ // Settling a successful run (handoff + brief LLM calls) outlasts the QStash
+ // delivery timeout, so the same run is redelivered while it is still being
+ // settled β€” and the lifecycle is not idempotent: each pass emits another
+ // brief. Failed runs are fenced above. A delivery that finds the settle in
+ // progress answers non-2xx: if the holder dies, a later retry takes over
+ // once its lease lapses. Without Redis, settle anyway: a duplicate brief
+ // beats a run that never reaches its Task.
+ const claim =
+ (reason || 'done') === 'done'
+ ? await redisService.taskRunDelivery.claim(operationId)
+ : undefined;
+
+ if (claim === 'settled') {
+ log('Skipped: run %s of task %s was already settled', operationId, taskId);
+ return c.json({ skipped: 'already-settled', success: true });
+ }
+ if (claim === 'in-progress') {
+ log('Deferred: run %s of task %s is still settling', operationId, taskId);
+ return c.json({ skipped: 'in-progress' }, 409);
+ }
+
const taskLifecycle = new TaskLifecycleService(db, userId, wsId);
- await taskLifecycle.onTopicComplete({
- errorCode: errorType,
- errorMessage,
- lastAssistantContent,
- operationId,
- reason: reason || 'done',
- runTrigger,
- taskId,
- taskIdentifier: taskRow?.identifier ?? taskIdentifier ?? taskId,
- topicId,
- });
+ try {
+ await taskLifecycle.onTopicComplete({
+ errorCode: errorType,
+ errorMessage,
+ lastAssistantContent,
+ operationId,
+ reason: reason || 'done',
+ runTrigger,
+ taskId,
+ taskIdentifier: taskRow?.identifier ?? taskIdentifier ?? taskId,
+ topicId,
+ });
+ } catch (error) {
+ if (claim === 'claimed') await redisService.taskRunDelivery.release(operationId);
+ throw error;
+ }
+
+ if (claim === 'claimed') await redisService.taskRunDelivery.markSettled(operationId);
return c.json({ success: true });
} catch (error) {
diff --git a/apps/server/src/services/redis/README.md b/apps/server/src/services/redis/README.md
index ac2e51dc5fa..9ae78d22de5 100644
--- a/apps/server/src/services/redis/README.md
+++ b/apps/server/src/services/redis/README.md
@@ -18,6 +18,9 @@ callers do not choose a provider, prefix, key, SET options or claim lifetime.
distinct topics one nightly review may cover. Its keys live in the `agent-signal` namespace
next to the Agent Signal runtime stores. Each count returns `undefined` without Redis; the
Agent Signal caller decides whether that fails open or closed.
+- `taskRunDelivery`: one settle per operation for a Task run's `onComplete` redeliveries β€” a
+ ten minute lease while settling, a three day marker once settled. `unavailable` without Redis;
+ the webhook then settles anyway.
- `agentIdentity`: replay claims on agent-account provider webhooks, one per provider event
id, in the `agent-identity` namespace. `releaseWebhookEvent` gives a claim back when the
delivery failed after it was claimed. Without Redis the claim falls back to a process-local one.
diff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.ts
index 60c90202d97..fee90317152 100644
--- a/apps/server/src/services/redis/index.ts
+++ b/apps/server/src/services/redis/index.ts
@@ -7,6 +7,7 @@ import { linear } from './linear';
import { pageCollab } from './pageCollab';
import { skillTools } from './skillTools';
import { steerQueue } from './steerQueue';
+import { taskRunDelivery } from './taskRunDelivery';
import { threadStartFence } from './threadStartFence';
import { workspaceRescan } from './workspaceRescan';
@@ -21,6 +22,7 @@ export const redisService = {
pageCollab,
skillTools,
steerQueue,
+ taskRunDelivery,
threadStartFence,
workspaceRescan,
};
diff --git a/apps/server/src/services/redis/taskRunDelivery.test.ts b/apps/server/src/services/redis/taskRunDelivery.test.ts
new file mode 100644
index 00000000000..c7a25f51f06
--- /dev/null
+++ b/apps/server/src/services/redis/taskRunDelivery.test.ts
@@ -0,0 +1,65 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { taskRunDelivery } from './taskRunDelivery';
+
+const { client, getRedisServiceClient } = vi.hoisted(() => {
+ const client = { del: vi.fn(), get: vi.fn(), set: vi.fn() };
+ return { client, getRedisServiceClient: vi.fn() };
+});
+vi.mock('./client', () => ({ getRedisServiceClient }));
+
+describe('taskRunDelivery', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ getRedisServiceClient.mockResolvedValue(client);
+ });
+
+ it('claims the first delivery of an operation under a lease', async () => {
+ client.set.mockResolvedValue('OK');
+
+ await expect(taskRunDelivery.claim('op-1')).resolves.toBe('claimed');
+ expect(client.set).toHaveBeenCalledWith('task_run_delivery:v1:op-1', 'settling', {
+ nx: true,
+ px: 10 * 60 * 1000,
+ });
+ });
+
+ it('reports a redelivery while the first one still holds the lease', async () => {
+ client.set.mockResolvedValue(null);
+ client.get.mockResolvedValue('settling');
+
+ await expect(taskRunDelivery.claim('op-1')).resolves.toBe('in-progress');
+ });
+
+ it('reports a redelivery of a settled operation', async () => {
+ client.set.mockResolvedValue(null);
+ client.get.mockResolvedValue('settled');
+
+ await expect(taskRunDelivery.claim('op-1')).resolves.toBe('settled');
+ });
+
+ it('cannot arbitrate without Redis or when a command fails', async () => {
+ getRedisServiceClient.mockResolvedValueOnce(null);
+ await expect(taskRunDelivery.claim('op-1')).resolves.toBe('unavailable');
+
+ client.set.mockRejectedValue(new Error('timeout'));
+ await expect(taskRunDelivery.claim('op-1')).resolves.toBe('unavailable');
+ });
+
+ it('remembers a settled operation past the retry window', async () => {
+ client.set.mockResolvedValue('OK');
+
+ await taskRunDelivery.markSettled('op-1');
+
+ expect(client.set).toHaveBeenCalledWith('task_run_delivery:v1:op-1', 'settled', {
+ px: 3 * 24 * 60 * 60 * 1000,
+ });
+ });
+
+ it('releases a failed claim and swallows Redis errors', async () => {
+ client.del.mockRejectedValue(new Error('timeout'));
+
+ await expect(taskRunDelivery.release('op-1')).resolves.toBeUndefined();
+ expect(client.del).toHaveBeenCalledWith('task_run_delivery:v1:op-1');
+ });
+});
diff --git a/apps/server/src/services/redis/taskRunDelivery.ts b/apps/server/src/services/redis/taskRunDelivery.ts
new file mode 100644
index 00000000000..2f5c08dbd33
--- /dev/null
+++ b/apps/server/src/services/redis/taskRunDelivery.ts
@@ -0,0 +1,63 @@
+import { RedisKeys } from '@/server/modules/Redis';
+
+import { getRedisServiceClient } from './client';
+
+const getClient = () => getRedisServiceClient('agentRun');
+
+// Comfortably longer than one settle (minutes of LLM work), and shorter than
+// QStash's last retry (~30 min), so a delivery that crashed mid-settle is taken
+// over by that retry instead of being lost.
+const LEASE_TTL_MS = 10 * 60 * 1000;
+// Outlives the whole QStash retry schedule.
+const SETTLED_TTL_MS = 3 * 24 * 60 * 60 * 1000;
+
+const SETTLING = 'settling';
+const SETTLED = 'settled';
+
+export type TaskRunDeliveryClaim = 'claimed' | 'in-progress' | 'settled' | 'unavailable';
+
+/**
+ * At-most-once settling of a run's `onComplete` delivery, per operation.
+ *
+ * QStash redelivers on timeout, and settling a run takes longer than the
+ * delivery timeout, so one finished run can reach the Task several times.
+ */
+export const taskRunDelivery = {
+ /**
+ * @returns `claimed` when this delivery owns the settle, `in-progress` while
+ * another one holds it, `settled` once it finished, `unavailable` when Redis
+ * cannot arbitrate
+ */
+ async claim(operationId: string): Promise<TaskRunDeliveryClaim> {
+ const redis = await getClient();
+ if (!redis) return 'unavailable';
+
+ const key = RedisKeys.agentRun.taskRunDelivery(operationId);
+ try {
+ if ((await redis.set(key, SETTLING, { nx: true, px: LEASE_TTL_MS })) === 'OK') {
+ return 'claimed';
+ }
+ return (await redis.get(key)) === SETTLED ? 'settled' : 'in-progress';
+ } catch {
+ return 'unavailable';
+ }
+ },
+
+ /** Best effort: without the marker a late retry waits out the lease and settles again. */
+ async markSettled(operationId: string): Promise<void> {
+ const redis = await getClient();
+ if (!redis) return;
+
+ await redis
+ .set(RedisKeys.agentRun.taskRunDelivery(operationId), SETTLED, { px: SETTLED_TTL_MS })
+ .catch(() => undefined);
+ },
+
+ /** Best effort: a claim that cannot be released lapses with its lease. */
+ async release(operationId: string): Promise<void> {
+ const redis = await getClient();
+ if (!redis) return;
+
+ await redis.del(RedisKeys.agentRun.taskRunDelivery(operationId)).catch(() => undefined);
+ },
+};