diff --git a/src/workflow/local-executor.test.ts b/src/workflow/local-executor.test.ts new file mode 100644 index 00000000..cdbe2d2b --- /dev/null +++ b/src/workflow/local-executor.test.ts @@ -0,0 +1,199 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest' +import { prisma } from '@/db' +import { setupTestDbHooks } from '@/db-test-hooks' +import { workflowService } from './workflow' +import { LocalExecutor } from './local-executor' +import { WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client' + +// Mock the individual workflows +const mocks = { + agentEmbeddingMedia: vi.fn(), + queryEmbeddingForSearch: vi.fn(), + agentAutofillMedia: vi.fn(), + agentChat: vi.fn(), + transcodeMedia: vi.fn(), +} + +vi.mock('./workflows/agent-embedding', () => ({ + agentEmbeddingMedia: (task: unknown) => mocks.agentEmbeddingMedia(task), +})) +vi.mock('./workflows/query-embedding-for-search', () => ({ + queryEmbeddingForSearch: (task: unknown) => mocks.queryEmbeddingForSearch(task), +})) +vi.mock('./workflows/agent-autofill', () => ({ + agentAutofillMedia: (task: unknown) => mocks.agentAutofillMedia(task), +})) +vi.mock('./workflows/agent-chat', () => ({ + agentChat: (task: unknown) => mocks.agentChat(task), +})) +vi.mock('@/transcode/workflows/transcode', () => ({ + transcodeMedia: (task: unknown) => mocks.transcodeMedia(task), +})) + +describe('LocalExecutor Integration Tests', () => { + setupTestDbHooks() + + let executor: LocalExecutor + + beforeEach(() => { + // Get the global executor instance which processes tasks submitted via the Prisma Client Extension + executor = (workflowService as unknown as { executor: LocalExecutor }).executor + vi.clearAllMocks() + }) + + describe('Heartbeat & Task Status transition', () => { + it('should immediately transition task to processing and set initial heartbeat', async () => { + let resolveChat: (value: unknown) => void = () => {} + const chatPromise = new Promise((resolve) => { + resolveChat = resolve + }) + mocks.agentChat.mockImplementationOnce(() => chatPromise) + + const task = await prisma.workflowTask.create({ + data: { + assetId: 'test-asset', + type: WorkflowTaskType.chat, + status: WorkflowTaskStatus.pending, + }, + }) + + // Wait briefly for the Prisma Client Extension's async submit (setTimeout 0) to execute and transition task + await new Promise((resolve) => setTimeout(resolve, 50)) + + const intermediateTask = await prisma.workflowTask.findUnique({ + where: { id: task.id }, + }) + + expect(intermediateTask?.status).toBe(WorkflowTaskStatus.processing) + expect(intermediateTask?.heartbeat).toBeInstanceOf(Date) + + // Clean up + resolveChat(undefined) + await new Promise((resolve) => setTimeout(resolve, 50)) + }) + + it('should query and retry stale tasks in tick() but ignore non-stale processing tasks', async () => { + mocks.agentChat.mockResolvedValue(undefined) + + // 1. Create a stale task (processing, heartbeat 40 seconds ago) + const staleTask = await prisma.workflowTask.create({ + data: { + assetId: 'asset-stale', + type: WorkflowTaskType.chat, + status: WorkflowTaskStatus.processing, + heartbeat: new Date(Date.now() - 40 * 1000), + }, + }) + + // 2. Create a non-stale task (processing, heartbeat 5 seconds ago) + const activeTask = await prisma.workflowTask.create({ + data: { + assetId: 'asset-active', + type: WorkflowTaskType.chat, + status: WorkflowTaskStatus.processing, + heartbeat: new Date(Date.now() - 5 * 1000), + }, + }) + + // Trigger tick manually on the executor and await the returned task promises + const promises = await executor.tick() + await Promise.all(promises) + + // The stale task should be picked up and processed (mocks.agentChat called for staleTask) + expect(mocks.agentChat).toHaveBeenCalledWith(expect.objectContaining({ id: staleTask.id })) + + // The active task should NOT be called + expect(mocks.agentChat).not.toHaveBeenCalledWith( + expect.objectContaining({ id: activeTask.id }), + ) + }) + }) + + describe('Concurrency Control', () => { + it('should limit transcode tasks to a concurrency of 1', async () => { + let resolveFirstTranscode: (value: unknown) => void = () => {} + const firstTranscodePromise = new Promise((resolve) => { + resolveFirstTranscode = resolve + }) + mocks.transcodeMedia.mockImplementationOnce(() => firstTranscodePromise) + mocks.transcodeMedia.mockImplementationOnce(() => Promise.resolve()) + + const task1 = await prisma.workflowTask.create({ + data: { + assetId: 'asset-1', + type: WorkflowTaskType.transcode, + status: WorkflowTaskStatus.pending, + }, + }) + + 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 trigger + await new Promise((resolve) => setTimeout(resolve, 50)) + + // The first task should be actively running + expect(mocks.transcodeMedia).toHaveBeenCalledWith(expect.objectContaining({ id: task1.id })) + // The second task should NOT have started yet because transcode pool limit is 1 + expect(mocks.transcodeMedia).not.toHaveBeenCalledWith( + expect.objectContaining({ id: task2.id }), + ) + + // Resolve the first task to let the second task execute + resolveFirstTranscode(undefined) + + // Wait briefly for the pool queue to process next item + await new Promise((resolve) => setTimeout(resolve, 50)) + + // The second task should now be running + expect(mocks.transcodeMedia).toHaveBeenCalledWith(expect.objectContaining({ id: task2.id })) + }) + + it('should limit general tasks to a concurrency of 5 and run them concurrently', async () => { + const activeResolvers: ((value: unknown) => void)[] = [] + mocks.agentChat.mockImplementation(() => { + return new Promise((resolve) => { + activeResolvers.push(resolve) + }) + }) + + // Create 7 general workflow tasks (limit is 5) + await Promise.all( + Array.from({ length: 7 }).map((_, i) => + prisma.workflowTask.create({ + data: { + assetId: `asset-chat-${i}`, + type: WorkflowTaskType.chat, + status: WorkflowTaskStatus.pending, + }, + }), + ), + ) + + // Wait briefly for Prisma Client Extension's async submits to trigger + await new Promise((resolve) => setTimeout(resolve, 100)) + + // Exactly 5 tasks should be running concurrently + expect(mocks.agentChat).toHaveBeenCalledTimes(5) + + // Resolve 2 tasks to let the remaining 2 start + activeResolvers[0](undefined) + activeResolvers[1](undefined) + + // Wait briefly for the pool to dequeue + await new Promise((resolve) => setTimeout(resolve, 50)) + + // Now all 7 tasks should have started + expect(mocks.agentChat).toHaveBeenCalledTimes(7) + + // Clean up remaining tasks + activeResolvers.slice(2).forEach((resolve) => resolve(undefined)) + await new Promise((resolve) => setTimeout(resolve, 50)) + }) + }) +}) diff --git a/src/workflow/local-executor.ts b/src/workflow/local-executor.ts index 6b36d19d..575c1b07 100644 --- a/src/workflow/local-executor.ts +++ b/src/workflow/local-executor.ts @@ -15,10 +15,46 @@ import { logger } from '@/logger' // eslint-disable-next-line @typescript-eslint/no-explicit-any ;(globalThis as any).__localLogger = logger +class ConcurrencyLimiter { + private activeCount = 0 + private queue: (() => void)[] = [] + + constructor(private readonly limit: number) {} + + async run(fn: () => Promise): Promise { + if (this.activeCount >= this.limit) { + await new Promise((resolve) => this.queue.push(resolve)) + } + this.activeCount++ + try { + return await fn() + } finally { + this.activeCount-- + const next = this.queue.shift() + if (next) { + next() + } + } + } + + // Exposed for testing concurrency status + getActiveCount(): number { + return this.activeCount + } + + getQueueLength(): number { + return this.queue.length + } +} + export class LocalExecutor implements Executor { private interval: Timer | null = null private processingTasks = new Set() + // 1 concurrency for transcode, 5 for other workflows + private transcodeLimiter = new ConcurrencyLimiter(1) + private generalLimiter = new ConcurrencyLimiter(5) + async submit(task: WorkflowTask): Promise { if (task.status !== WorkflowTaskStatus.pending) { await prisma.workflowTask.update({ @@ -27,12 +63,17 @@ export class LocalExecutor implements Executor { }) } - // In tests, we trigger processing immediately + // In tests, we trigger processing immediately using the appropriate limiter if (process.env.NODE_ENV === 'test') { setTimeout(() => { - this.processTaskWrapper(task).catch((err) => { - console.error(`[LocalExecutor] Failed to process task ${task.id}:`, err) - }) + const limiter = + task.type === WorkflowTaskType.transcode ? this.transcodeLimiter : this.generalLimiter + + limiter + .run(() => this.processTaskWrapper(task)) + .catch((err) => { + console.error(`[LocalExecutor] Failed to process task ${task.id}:`, err) + }) }, 0) } return task.id @@ -50,7 +91,9 @@ export class LocalExecutor implements Executor { } } - private async tick() { + // Returns the array of task promises so tests can await them to avoid early rollback. + async tick(): Promise[]> { + const promises: Promise[] = [] try { const staleTime = new Date(Date.now() - 30 * 1000) const tasks = await prisma.workflowTask.findMany({ @@ -68,19 +111,54 @@ export class LocalExecutor implements Executor { for (const task of tasks) { if (this.processingTasks.has(task.id)) continue - this.processTaskWrapper(task).catch((err) => { - console.error(`[LocalExecutor] Failed to process task ${task.id}:`, err) - }) + + const limiter = + task.type === WorkflowTaskType.transcode ? this.transcodeLimiter : this.generalLimiter + + const promise = limiter + .run(() => this.processTaskWrapper(task)) + .catch((err) => { + console.error(`[LocalExecutor] Failed to process task ${task.id}:`, err) + }) + promises.push(promise) } } catch (err) { console.error('Failed to fetch tasks:', err) } + return promises } 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: @@ -115,6 +193,8 @@ export class LocalExecutor implements Executor { 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) } }