diff --git a/src/workflow/local-executor.test.ts b/src/workflow/local-executor.test.ts index 63c3a5bd..3c6458ef 100644 --- a/src/workflow/local-executor.test.ts +++ b/src/workflow/local-executor.test.ts @@ -72,6 +72,87 @@ describe('LocalExecutor Integration Tests', () => { await new Promise((resolve) => setTimeout(resolve, 50)) }) + it('should immediately lock task and start heartbeat updates in database even when queued in limiter', async () => { + let resolveFirstTranscode: (value: unknown) => void = () => {} + const firstTranscodePromise = new Promise((resolve) => { + resolveFirstTranscode = resolve + }) + mocks.transcodeMedia.mockImplementationOnce(() => firstTranscodePromise) + mocks.transcodeMedia.mockImplementationOnce(() => Promise.resolve()) + + // 1. Create task 1 (will run immediately and hold the transcode limiter slot) + const task1 = await prisma.workflowTask.create({ + data: { + assetId: 'asset-1', + type: WorkflowTaskType.transcode, + status: WorkflowTaskStatus.pending, + }, + }) + + // 2. Create task 2 (will be blocked and queued in memory by transcode limiter) + const task2 = await prisma.workflowTask.create({ + data: { + assetId: 'asset-2', + type: WorkflowTaskType.transcode, + status: WorkflowTaskStatus.pending, + }, + }) + + // Wait briefly for Prisma Client Extension's async submits to queue task2 + await new Promise((resolve) => setTimeout(resolve, 50)) + + // 3. Verify task 1 is running + expect(mocks.transcodeMedia).toHaveBeenCalledWith(expect.objectContaining({ id: task1.id })) + + // 4. Verify task 2 has NOT started executing yet + expect(mocks.transcodeMedia).not.toHaveBeenCalledWith( + expect.objectContaining({ id: task2.id }), + ) + + // 5. BUT verify task 2 is already locked in database and has heartbeat set! + const dbTask2 = await prisma.workflowTask.findUnique({ + where: { id: task2.id }, + }) + + expect(dbTask2?.status).toBe(WorkflowTaskStatus.processing) + expect(dbTask2?.heartbeat).toBeInstanceOf(Date) + + // Clean up + resolveFirstTranscode(undefined) + 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 20a76faa..d6c4f264 100644 --- a/src/workflow/local-executor.ts +++ b/src/workflow/local-executor.ts @@ -68,12 +68,61 @@ export class LocalExecutor implements Executor { // In tests, we trigger processing immediately using the appropriate limiter if (process.env.NODE_ENV === 'test') { - setTimeout(() => { + setTimeout(async () => { + if (this.processingTasks.has(task.id)) return + 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 { + 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:`, + err, + ) + this.processingTasks.delete(task.id) + return + } + + // 2. Start heartbeat updater immediately + const heartbeatInterval = setInterval(async () => { + try { + await prisma.workflowTask.update({ + where: { id: task.id }, + data: { heartbeat: new Date() }, + }) + } catch (err) { + console.error(`[LocalExecutor] Failed to update heartbeat for task ${task.id}:`, err) + } + }, 5000) + const limiter = task.type === WorkflowTaskType.transcode ? this.transcodeLimiter : this.generalLimiter limiter - .run(() => this.processTaskWrapper(task)) + .run(async () => { + try { + await this.processTaskWrapper(task) + } finally { + // 3. Clean up the heartbeat updater and processing set when the task finishes + clearInterval(heartbeatInterval) + this.processingTasks.delete(task.id) + } + }) .catch((err) => { console.error(`[LocalExecutor] Failed to process task ${task.id}:`, err) }) @@ -114,12 +163,64 @@ export class LocalExecutor implements Executor { for (const task of tasks) { if (this.processingTasks.has(task.id)) continue + this.processingTasks.add(task.id) + + // 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 { + 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) + continue + } + + // 2. Start heartbeat updater immediately so it updates heartbeat + // even while the task is queued waiting for limiter capacity. + const heartbeatInterval = setInterval(async () => { + try { + await prisma.workflowTask.update({ + where: { id: task.id }, + data: { heartbeat: new Date() }, + }) + } catch (err) { + console.error(`[LocalExecutor] Failed to update heartbeat for task ${task.id}:`, err) + } + }, 5000) const limiter = task.type === WorkflowTaskType.transcode ? this.transcodeLimiter : this.generalLimiter const promise = limiter - .run(() => this.processTaskWrapper(task)) + .run(async () => { + try { + await this.processTaskWrapper(task) + } finally { + // 3. Clean up the heartbeat updater and processing set when the task finishes + clearInterval(heartbeatInterval) + this.processingTasks.delete(task.id) + } + }) .catch((err) => { console.error(`[LocalExecutor] Failed to process task ${task.id}:`, err) }) @@ -132,36 +233,6 @@ export class LocalExecutor implements Executor { } private async processTaskWrapper(task: WorkflowTask) { - if (this.processingTasks.has(task.id)) return - this.processingTasks.add(task.id) - - // 1. Immediately mark task as processing and set initial heartbeat in DB - try { - await prisma.workflowTask.update({ - where: { id: task.id }, - data: { - status: WorkflowTaskStatus.processing, - heartbeat: new Date(), - }, - }) - } catch (err) { - console.error(`[LocalExecutor] Failed to mark task ${task.id} as processing:`, err) - this.processingTasks.delete(task.id) - return - } - - // 2. Start heartbeat updater every 5 seconds - const heartbeatInterval = setInterval(async () => { - try { - await prisma.workflowTask.update({ - where: { id: task.id }, - data: { heartbeat: new Date() }, - }) - } catch (err) { - console.error(`[LocalExecutor] Failed to update heartbeat for task ${task.id}:`, err) - } - }, 5000) - try { switch (task.type) { case WorkflowTaskType.ai_embedding: @@ -195,10 +266,6 @@ export class LocalExecutor implements Executor { } catch (updateErr) { console.error(`Failed to set task ${task.id} to failed:`, updateErr) } - } finally { - // 3. Clean up the heartbeat updater and processing set - clearInterval(heartbeatInterval) - this.processingTasks.delete(task.id) } } }