diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d15b2e3..ae0b46cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed * **workflow**: Fix an issue where creating background tasks from within an active workflow step caused an invalid transition error during video processing +* **cli**: Fix an issue where running `shumai regenerate-embeddings` would report success without enqueueing tasks to background workers ### Changed diff --git a/apps/web/src/index.ts b/apps/web/src/index.ts index 2ef0746a..6997d954 100644 --- a/apps/web/src/index.ts +++ b/apps/web/src/index.ts @@ -53,8 +53,11 @@ const regenCmdIndex = cliArgs.findIndex((arg) => arg === 'regenerate-embeddings' if (regenCmdIndex !== -1) { try { + initAgentWorkflows() + initTranscodeWorkflows() console.log('🔄 Regenerating embeddings...') const result = await embeddingService.regenerateEmbeddings() + await workflowService.waitForPendingSubmissions() console.log( `✅ Successfully queued ${result.tasksCreated} embedding tasks for ${result.totalAssets} assets.`, ) diff --git a/packages/db/src/test-global-setup.ts b/packages/db/src/test-global-setup.ts index 51b354b0..d7d889d4 100644 --- a/packages/db/src/test-global-setup.ts +++ b/packages/db/src/test-global-setup.ts @@ -23,6 +23,15 @@ export async function globalTestSetup() { }, }) console.log('Prisma Migrations completed.') + + console.log('Applying DBOS Migrations...') + await execAsync('bun packages/workflow-core/src/migrate.ts', { + env: { + ...process.env, + DATABASE_URL: databaseUrl, + }, + }) + console.log('DBOS Migrations completed.') } export async function setup() { diff --git a/packages/workflow-core/src/dbos-executor.test.ts b/packages/workflow-core/src/dbos-executor.test.ts index 13265a16..bfc22f9e 100644 --- a/packages/workflow-core/src/dbos-executor.test.ts +++ b/packages/workflow-core/src/dbos-executor.test.ts @@ -173,13 +173,49 @@ describe('DbosExecutor Tests', () => { ) }) + it('should enqueue workflow via client even when executor is not started and no local workflows are registered', async () => { + // executor is not started and has no local workflows registered (e.g. CLI or producer mode) + const mockClient = { + // eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name + enqueue: vi.fn().mockResolvedValue({ workflowID: 'task-cli-123' }), + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.spyOn(executor, 'getClient').mockResolvedValue(mockClient as any) + + const mockTask = { + id: 'task-cli-123', + type: WorkflowTaskType.ai_embedding, + status: WorkflowTaskStatus.pending, + } as WorkflowTask + + const res = await executor.submit(mockTask) + expect(mockClient.enqueue).toHaveBeenCalledWith( + expect.objectContaining({ + queueName: TaskQueueAgent, + workflowName: WorkflowTaskType.ai_embedding, + // eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name + workflowID: 'task-cli-123', + }), + mockTask, + ) + expect(res).toBe('task-cli-123') + }) + it('should allow submitting tasks from within a running DBOS step', async () => { executor.start() await executor.ensureLaunched() + const mockClient = { + // eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name + enqueue: vi.fn().mockResolvedValue({ workflowID: 'task-from-step' }), + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.spyOn(executor, 'getClient').mockResolvedValue(mockClient as any) + activeExecutor = executor const result = await wf() expect(result).toBe('task-from-step') - }) + expect(mockClient.enqueue).toHaveBeenCalled() + }, 15000) }) }) diff --git a/packages/workflow-core/src/dbos-executor.ts b/packages/workflow-core/src/dbos-executor.ts index 28fa6517..2674e94a 100644 --- a/packages/workflow-core/src/dbos-executor.ts +++ b/packages/workflow-core/src/dbos-executor.ts @@ -59,6 +59,7 @@ export class DbosExecutor implements Executor { private client: DBOSClient | null = null private listenQueues: string[] = [TaskQueueAgent, TaskQueueTranscode] private heartbeatIntervals = new Map() + private inFlightSubmits = new Set>() constructor(listenQueues?: string[]) { if (listenQueues) { @@ -66,6 +67,10 @@ export class DbosExecutor implements Executor { } } + isStarted(): boolean { + return this.started + } + setListenQueues(queues: string[]): void { this.listenQueues = queues } @@ -163,6 +168,9 @@ export class DbosExecutor implements Executor { private getDefaultExecutorId(): string { if (process.env.DBOS__VMID) return process.env.DBOS__VMID if (process.env.SHUMAI_WORKER_ID) return process.env.SHUMAI_WORKER_ID + if (process.env.NODE_ENV === 'test') { + return `shumai-test-${process.pid}-${Math.random().toString(36).slice(2, 7)}` + } if (this.listenQueues.length === 0) return 'shumai-web' if (this.listenQueues.length === 1) { if (this.listenQueues[0] === TaskQueueTranscode) return 'shumai-transcode' @@ -183,19 +191,24 @@ export class DbosExecutor implements Executor { this.registerAllWorkflowsWithDbos() const isTest = process.env.NODE_ENV === 'test' + if (!isTest && !dbosMigrationsRan) { + await DBOS.migrate(getDbosDatabaseUrl()) + dbosMigrationsRan = true + } + DBOS.setConfig({ name: 'shumai', systemDatabaseUrl: getDbosDatabaseUrl(), + systemDatabasePoolSize: isTest ? 5 : undefined, applicationVersion: process.env.SHUMAI_VERSION || '1.0.0', // eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS config property name executorID: this.getDefaultExecutorId(), listenQueues: this.listenQueues, - runMigrations: !dbosMigrationsRan, + runMigrations: false, logLevel: isTest ? 'error' : 'info', }) await DBOS.launch() - dbosMigrationsRan = true const minPollingIntervalMs = isTest ? 50 : 1000 await DBOS.registerQueue(TaskQueueTranscode, { @@ -220,14 +233,26 @@ export class DbosExecutor implements Executor { async getClient(): Promise { if (!this.client) { + const isTest = process.env.NODE_ENV === 'test' this.client = await DBOSClient.create({ systemDatabaseUrl: getDbosDatabaseUrl(), + systemDatabasePoolSize: isTest ? 3 : undefined, }) } return this.client } async submit(task: WorkflowTask): Promise { + const submitPromise = this.doSubmit(task) + this.inFlightSubmits.add(submitPromise) + try { + return await submitPromise + } finally { + this.inFlightSubmits.delete(submitPromise) + } + } + + private async doSubmit(task: WorkflowTask): Promise { if (task.status !== WorkflowTaskStatus.pending) { await prisma.workflowTask.updateMany({ where: { id: task.id }, @@ -235,14 +260,10 @@ export class DbosExecutor implements Executor { }) } - // In unit tests that do not start the workflow service or register workflows, - // avoid launching DBOS in the background if no workflows are registered. - if (!this.started && getRegisteredWorkflows().size === 0) { - return task.id + if (this.started) { + await this.ensureLaunched() } - await this.ensureLaunched() - const workflowName = task.type if (!workflowName) { throw new Error(`WorkflowTask ${task.id} is missing task.type`) @@ -264,6 +285,12 @@ export class DbosExecutor implements Executor { return handle.workflowID } + async waitForPendingSubmissions(): Promise { + while (this.inFlightSubmits.size > 0) { + await Promise.allSettled(Array.from(this.inFlightSubmits)) + } + } + async cancel(taskId: string): Promise { const timer = this.heartbeatIntervals.get(taskId) if (timer) { @@ -289,6 +316,7 @@ export class DbosExecutor implements Executor { close(): void { this.started = false + this.waitForPendingSubmissions().catch(() => {}) for (const timer of this.heartbeatIntervals.values()) { clearInterval(timer) } @@ -298,9 +326,8 @@ export class DbosExecutor implements Executor { this.client = null } if (DBOS.isInitialized()) { - DBOS.shutdown({ deregister: true }) + DBOS.shutdown() .then(() => { - registeredDbosWorkflowNames.clear() this.launchPromise = null }) .catch((err) => { @@ -311,6 +338,7 @@ export class DbosExecutor implements Executor { async shutdown(): Promise { this.started = false + await this.waitForPendingSubmissions() for (const timer of this.heartbeatIntervals.values()) { clearInterval(timer) } @@ -320,8 +348,7 @@ export class DbosExecutor implements Executor { this.client = null } if (DBOS.isInitialized()) { - await DBOS.shutdown({ deregister: true }) - registeredDbosWorkflowNames.clear() + await DBOS.shutdown() this.launchPromise = null } } diff --git a/packages/workflow-core/src/migrate.ts b/packages/workflow-core/src/migrate.ts new file mode 100644 index 00000000..fc25d339 --- /dev/null +++ b/packages/workflow-core/src/migrate.ts @@ -0,0 +1,11 @@ +import { DBOS } from '@dbos-inc/dbos-sdk' +import { getDbosDatabaseUrl } from './dbos-executor' + +export async function migrateDbos(url?: string): Promise { + const dbUrl = getDbosDatabaseUrl(url) + await DBOS.migrate(dbUrl) +} + +if (import.meta.main) { + await migrateDbos() +} diff --git a/packages/workflow-core/src/workflow.test.ts b/packages/workflow-core/src/workflow.test.ts index 0c5a7581..9d8e3132 100644 --- a/packages/workflow-core/src/workflow.test.ts +++ b/packages/workflow-core/src/workflow.test.ts @@ -40,11 +40,11 @@ describe('WorkflowService', () => { vi.clearAllMocks() workflowService.start() await workflowService.ensureLaunched() - }) + }, 15000) afterEach(async () => { await workflowService.shutdownWorkers() - }) + }, 15000) it('should process ai_embedding task locally', async () => { const team = await prisma.team.create({ diff --git a/packages/workflow-core/src/workflow.ts b/packages/workflow-core/src/workflow.ts index cad98cb5..bcf63c3e 100644 --- a/packages/workflow-core/src/workflow.ts +++ b/packages/workflow-core/src/workflow.ts @@ -1,5 +1,6 @@ import { prisma, registerWorkflowCancel, registerWorkflowTrigger, WorkflowTask } from '@shumai/db' import { DbosExecutor } from './dbos-executor' +import { getRegisteredWorkflows } from './registry' export class WorkflowService { private executor: DbosExecutor @@ -71,6 +72,14 @@ export class WorkflowService { await this.executor.shutdown() } + isStarted(): boolean { + return this.executor.isStarted() + } + + async waitForPendingSubmissions(): Promise { + await this.executor.waitForPendingSubmissions() + } + // Starts DBOS worker for specific task queue(s) async startWorkers( queue: string | string[], @@ -87,6 +96,13 @@ export class WorkflowService { export const workflowService = new WorkflowService() registerWorkflowTrigger(async (task) => { + if ( + process.env.NODE_ENV === 'test' && + !workflowService.isStarted() && + getRegisteredWorkflows().size === 0 + ) { + return + } await workflowService.submit(task) }) registerWorkflowCancel(async (taskId) => {