From 5f89be86d695e8e39160ccec63f0ea3b47b24706 Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 17 Oct 2026 16:25:02 +0800 Subject: [PATCH] fix(workflow): submit tasks via DBOSClient to allow enqueueing from steps Enqueuing workflows using DBOS.enqueueWorkflowWithOptions threw a DBOSInvalidWorkflowTransitionError when triggered from within a running step or activity (e.g. creating embedding or autofill tasks during video transcoding). Use DBOSClient to submit and cancel workflow tasks directly against the system database, detaching execution from the ambient workflow/step context. --- CHANGELOG.md | 3 ++ .../workflow-core/src/dbos-executor.test.ts | 49 +++++++++++++++---- packages/workflow-core/src/dbos-executor.ts | 36 ++++++++++---- packages/workflow-core/src/workflow.test.ts | 5 +- packages/workflow-core/src/workflow.ts | 4 ++ 5 files changed, 77 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98c1b9a1..2d15b2e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,11 @@ 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 + ### Changed + * **workflow**: Migrate the background workflow engine to DBOS, unifying all-in-one and dedicated worker deployments using the existing PostgreSQL database without requiring a separate Temporal cluster ## [0.5.3] - 2026-10-16 diff --git a/packages/workflow-core/src/dbos-executor.test.ts b/packages/workflow-core/src/dbos-executor.test.ts index 70ff8e36..13265a16 100644 --- a/packages/workflow-core/src/dbos-executor.test.ts +++ b/packages/workflow-core/src/dbos-executor.test.ts @@ -4,6 +4,27 @@ import { TaskQueueAgent, TaskQueueTranscode } from './workflow-utils' import { WorkflowTaskStatus, WorkflowTaskType, WorkflowTask } from '@shumai/db' import { DBOS } from '@dbos-inc/dbos-sdk' +let activeExecutor: DbosExecutor | null = null + +const stepFn = DBOS.registerStep( + async () => { + const mockTask = { + id: 'task-from-step', + type: WorkflowTaskType.chat, + status: WorkflowTaskStatus.pending, + } as WorkflowTask + return await activeExecutor!.submit(mockTask) + }, + { name: 'testStepSubmittingTask' }, +) + +const wf = DBOS.registerWorkflow( + async () => { + return await stepFn() + }, + { name: 'testWfRunningStep' }, +) + describe('DbosExecutor Tests', () => { let executor: DbosExecutor @@ -12,8 +33,8 @@ describe('DbosExecutor Tests', () => { executor = new DbosExecutor() }) - afterEach(() => { - executor.close() + afterEach(async () => { + await executor.shutdown() }) describe('Queue and URL resolution', () => { @@ -123,12 +144,15 @@ describe('DbosExecutor Tests', () => { describe('Submit', () => { it('should enqueue workflow with correct parameters', async () => { - executor.start() - const enqueueSpy = vi - .spyOn(DBOS, 'enqueueWorkflowWithOptions') - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/naming-convention -- mock handle - .mockResolvedValueOnce({ workflowID: 'task-123' } as any) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ;(executor as any).started = true vi.spyOn(executor, 'ensureLaunched').mockResolvedValueOnce(undefined) + const mockClient = { + // eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name + enqueue: vi.fn().mockResolvedValue({ workflowID: 'task-123' }), + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.spyOn(executor, 'getClient').mockResolvedValue(mockClient as any) const mockTask = { id: 'task-123', @@ -138,7 +162,7 @@ describe('DbosExecutor Tests', () => { const res = await executor.submit(mockTask) expect(res).toBe('task-123') - expect(enqueueSpy).toHaveBeenCalledWith( + expect(mockClient.enqueue).toHaveBeenCalledWith( expect.objectContaining({ queueName: TaskQueueAgent, workflowName: WorkflowTaskType.chat, @@ -147,8 +171,15 @@ describe('DbosExecutor Tests', () => { }), mockTask, ) + }) - enqueueSpy.mockRestore() + it('should allow submitting tasks from within a running DBOS step', async () => { + executor.start() + await executor.ensureLaunched() + + activeExecutor = executor + const result = await wf() + expect(result).toBe('task-from-step') }) }) }) diff --git a/packages/workflow-core/src/dbos-executor.ts b/packages/workflow-core/src/dbos-executor.ts index a6c43190..28fa6517 100644 --- a/packages/workflow-core/src/dbos-executor.ts +++ b/packages/workflow-core/src/dbos-executor.ts @@ -1,4 +1,4 @@ -import { DBOS } from '@dbos-inc/dbos-sdk' +import { DBOS, DBOSClient } from '@dbos-inc/dbos-sdk' import { logger } from '@shumai/core/src/logger' import { prisma, WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db' import type { Executor } from './executor' @@ -56,6 +56,7 @@ const registeredDbosWorkflowNames = new Set() export class DbosExecutor implements Executor { private launchPromise: Promise | null = null private started = false + private client: DBOSClient | null = null private listenQueues: string[] = [TaskQueueAgent, TaskQueueTranscode] private heartbeatIntervals = new Map() @@ -217,6 +218,15 @@ export class DbosExecutor implements Executor { } } + async getClient(): Promise { + if (!this.client) { + this.client = await DBOSClient.create({ + systemDatabaseUrl: getDbosDatabaseUrl(), + }) + } + return this.client + } + async submit(task: WorkflowTask): Promise { if (task.status !== WorkflowTaskStatus.pending) { await prisma.workflowTask.updateMany({ @@ -239,7 +249,8 @@ export class DbosExecutor implements Executor { } const queueName = getQueueForTaskType(workflowName) - const handle = await DBOS.enqueueWorkflowWithOptions( + const client = await this.getClient() + const handle = await client.enqueue( { queueName, workflowName, @@ -260,13 +271,12 @@ export class DbosExecutor implements Executor { this.heartbeatIntervals.delete(taskId) } triggerLocalCancel(taskId) - if (DBOS.isInitialized()) { - try { - await DBOS.cancelWorkflow(taskId) - logger.info({ taskId }, '[DbosExecutor] Cancelled workflow task') - } catch (err) { - logger.warn({ taskId, err }, '[DbosExecutor] Failed to cancel workflow task in DBOS') - } + try { + const client = await this.getClient() + await client.cancelWorkflow(taskId) + logger.info({ taskId }, '[DbosExecutor] Cancelled workflow task') + } catch (err) { + logger.warn({ taskId, err }, '[DbosExecutor] Failed to cancel workflow task in DBOS') } } @@ -283,6 +293,10 @@ export class DbosExecutor implements Executor { clearInterval(timer) } this.heartbeatIntervals.clear() + if (this.client) { + this.client.destroy().catch(() => {}) + this.client = null + } if (DBOS.isInitialized()) { DBOS.shutdown({ deregister: true }) .then(() => { @@ -301,6 +315,10 @@ export class DbosExecutor implements Executor { clearInterval(timer) } this.heartbeatIntervals.clear() + if (this.client) { + await this.client.destroy().catch(() => {}) + this.client = null + } if (DBOS.isInitialized()) { await DBOS.shutdown({ deregister: true }) registeredDbosWorkflowNames.clear() diff --git a/packages/workflow-core/src/workflow.test.ts b/packages/workflow-core/src/workflow.test.ts index 0e2a3be8..0c5a7581 100644 --- a/packages/workflow-core/src/workflow.test.ts +++ b/packages/workflow-core/src/workflow.test.ts @@ -39,10 +39,11 @@ describe('WorkflowService', () => { initTranscodeWorkflows() vi.clearAllMocks() workflowService.start() + await workflowService.ensureLaunched() }) - afterEach(() => { - workflowService.close() + afterEach(async () => { + await workflowService.shutdownWorkers() }) it('should process ai_embedding task locally', async () => { diff --git a/packages/workflow-core/src/workflow.ts b/packages/workflow-core/src/workflow.ts index 732fe4e9..cad98cb5 100644 --- a/packages/workflow-core/src/workflow.ts +++ b/packages/workflow-core/src/workflow.ts @@ -63,6 +63,10 @@ export class WorkflowService { this.executor.close() } + async ensureLaunched(): Promise { + await this.executor.ensureLaunched() + } + async shutdownWorkers(): Promise { await this.executor.shutdown() }