From 53c2792cf54a576d1cd3f5ecfb219537c6704953 Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 30 May 2026 11:19:15 +0800 Subject: [PATCH] feat(workflow): use atomic updateMany CAS locking to prevent multi-replica polling race conditions --- src/workflow/local-executor.test.ts | 31 +++++++++++++++++++++++++++++ src/workflow/local-executor.ts | 30 ++++++++++++++++++++++++---- 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/src/workflow/local-executor.test.ts b/src/workflow/local-executor.test.ts index 9a59d26d..3c6458ef 100644 --- a/src/workflow/local-executor.test.ts +++ b/src/workflow/local-executor.test.ts @@ -122,6 +122,37 @@ describe('LocalExecutor Integration Tests', () => { await new Promise((resolve) => setTimeout(resolve, 50)) }) + it('should atomically claim tasks using CAS updateMany to prevent double-execution when tick() runs concurrently', async () => { + mocks.agentChat.mockResolvedValue(undefined) + + // Mock submit to prevent automatic execution by the Prisma Client Extension + const submitSpy = vi.spyOn(workflowService, 'submit').mockResolvedValue('dummy-id') + + // Create a single pending task (will NOT be run automatically because submit is mocked) + const task = await prisma.workflowTask.create({ + data: { + assetId: 'asset-concurrent-test', + type: WorkflowTaskType.chat, + status: WorkflowTaskStatus.pending, + }, + }) + + // We trigger two ticks concurrently to simulate overlapping polling cycles or multi-replica triggers. + // Both ticks will query the database at approximately the same time. + const tick1 = executor.tick() + const tick2 = executor.tick() + + const [promises1, promises2] = await Promise.all([tick1, tick2]) + await Promise.all([...promises1, ...promises2]) + + // Verify that the mock workflow is called EXACTLY ONCE for this task ID, + // proving that one tick successfully claimed the task and the other was atomically blocked. + expect(mocks.agentChat).toHaveBeenCalledTimes(1) + expect(mocks.agentChat).toHaveBeenCalledWith(expect.objectContaining({ id: task.id })) + + submitSpy.mockRestore() + }) + it('should query and retry stale tasks in tick() but ignore non-stale processing tasks', async () => { mocks.agentChat.mockResolvedValue(undefined) diff --git a/src/workflow/local-executor.ts b/src/workflow/local-executor.ts index f4ad6410..d6c4f264 100644 --- a/src/workflow/local-executor.ts +++ b/src/workflow/local-executor.ts @@ -73,14 +73,22 @@ export class LocalExecutor implements Executor { this.processingTasks.add(task.id) // 1. Immediately mark task as processing and set initial heartbeat in DB + // atomically, only if the task is still pending. try { - await prisma.workflowTask.update({ - where: { id: task.id }, + const affected = await prisma.workflowTask.updateMany({ + where: { + id: task.id, + status: WorkflowTaskStatus.pending, + }, data: { status: WorkflowTaskStatus.processing, heartbeat: new Date(), }, }) + if (affected.count === 0) { + this.processingTasks.delete(task.id) + return + } } catch (err) { console.error( `[LocalExecutor] Failed to mark task ${task.id} as processing in submit:`, @@ -159,14 +167,28 @@ export class LocalExecutor implements Executor { // 1. Immediately mark task as processing and set initial heartbeat in DB // to guarantee no other ticks/replicas can double-query it. + // We use updateMany to atomically claim it only if it is still pending or stale. try { - await prisma.workflowTask.update({ - where: { id: task.id }, + const affected = await prisma.workflowTask.updateMany({ + where: { + id: task.id, + OR: [ + { status: WorkflowTaskStatus.pending }, + { + status: WorkflowTaskStatus.processing, + heartbeat: { lt: staleTime }, + }, + ], + }, data: { status: WorkflowTaskStatus.processing, heartbeat: new Date(), }, }) + if (affected.count === 0) { + this.processingTasks.delete(task.id) + continue + } } catch (err) { console.error(`[LocalExecutor] Failed to mark task ${task.id} as processing:`, err) this.processingTasks.delete(task.id)