fix(workflow): ensure CLI tasks are enqueued to DBOS and run DBOS migrations in global setup

- Initialize workflows and wait for pending DBOS submissions in shumai regenerate-embeddings CLI
- Remove no-op submit bypass and enqueue tasks via DBOSClient in producer and CLI contexts
- Add DBOS migration runner in test global setup to avoid concurrent migration deadlocks across test forks
- Update changelog and add regression tests
This commit is contained in:
yiling
2026-10-17 19:06:22 +08:00
parent 6966e5876e
commit 7e1e2441d7
8 changed files with 118 additions and 15 deletions
+1
View File
@@ -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
+3
View File
@@ -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.`,
)
+9
View File
@@ -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() {
@@ -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)
})
})
+39 -12
View File
@@ -59,6 +59,7 @@ export class DbosExecutor implements Executor {
private client: DBOSClient | null = null
private listenQueues: string[] = [TaskQueueAgent, TaskQueueTranscode]
private heartbeatIntervals = new Map<string, Timer>()
private inFlightSubmits = new Set<Promise<string>>()
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<DBOSClient> {
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<string> {
const submitPromise = this.doSubmit(task)
this.inFlightSubmits.add(submitPromise)
try {
return await submitPromise
} finally {
this.inFlightSubmits.delete(submitPromise)
}
}
private async doSubmit(task: WorkflowTask): Promise<string> {
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<void> {
while (this.inFlightSubmits.size > 0) {
await Promise.allSettled(Array.from(this.inFlightSubmits))
}
}
async cancel(taskId: string): Promise<void> {
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<void> {
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
}
}
+11
View File
@@ -0,0 +1,11 @@
import { DBOS } from '@dbos-inc/dbos-sdk'
import { getDbosDatabaseUrl } from './dbos-executor'
export async function migrateDbos(url?: string): Promise<void> {
const dbUrl = getDbosDatabaseUrl(url)
await DBOS.migrate(dbUrl)
}
if (import.meta.main) {
await migrateDbos()
}
+2 -2
View File
@@ -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({
+16
View File
@@ -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<void> {
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) => {