diff --git a/AGENTS.md b/AGENTS.md index 624c5b6b..331ebd42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -422,7 +422,15 @@ To prevent the engine from indefinitely retrying fatal, expected business valida - **Implementation**: Activities _can_ and _should_ call other services (e.g., `aiService`, `transcodeService`) or interact with the database directly. Database (Prisma) queries or updates are allowed in all activity types (e.g., agent or transcode) for simplicity. -- **Implementation**: Activities _can_ and _should_ call other services (e.g., `aiService`, `transcodeService`) or interact with the database directly. Database (Prisma) queries or updates are allowed in all activity types (e.g., agent or transcode) for simplicity. +### Worker Identity & Multi-Instance Deployments + +In multi-replica deployments (e.g., multiple transcode or agent worker instances), each worker instance MUST have a unique executor ID to prevent startup recovery from re-enqueueing workflows being actively processed by other live workers. + +- **Identity Derivation**: `DbosExecutor` automatically derives a unique per-instance ID: + - If `SHUMAI_WORKER_ID` or `DBOS__VMID` is set, it is used as the instance identifier. + - In Kubernetes, set `POD_NAME` (via Downward API: `fieldRef: { fieldPath: metadata.name }`) to provide stable, per-pod identity across StatefulSet restarts. + - In Docker/container environments, `HOSTNAME` (container ID) is automatically used. + - On bare metal/multi-process hosts, `process.pid` and an instance suffix are appended to guarantee uniqueness. ## Import conventions diff --git a/CHANGELOG.md b/CHANGELOG.md index ae0b46cc..bb5b30fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). * **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 +* **workflow**: Fix an issue where multiple worker replicas could share the same executor identity and disrupt live workflows on startup recovery ### Changed diff --git a/packages/workflow-core/src/dbos-executor.test.ts b/packages/workflow-core/src/dbos-executor.test.ts index bfc22f9e..eabfb253 100644 --- a/packages/workflow-core/src/dbos-executor.test.ts +++ b/packages/workflow-core/src/dbos-executor.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' import { DbosExecutor, getDbosDatabaseUrl, getQueueForTaskType } from './dbos-executor' import { TaskQueueAgent, TaskQueueTranscode } from './workflow-utils' -import { WorkflowTaskStatus, WorkflowTaskType, WorkflowTask } from '@shumai/db' +import { WorkflowTaskStatus, WorkflowTaskType, WorkflowTask, prisma } from '@shumai/db' import { DBOS } from '@dbos-inc/dbos-sdk' let activeExecutor: DbosExecutor | null = null @@ -101,6 +101,116 @@ describe('DbosExecutor Tests', () => { }) }) + describe('Executor Identity & Multi-instance Recovery', () => { + let originalEnv: NodeJS.ProcessEnv + + beforeEach(() => { + originalEnv = { ...process.env } + }) + + afterEach(() => { + process.env = originalEnv + }) + + it('should derive unique executor IDs for multiple replicas of the same role when no explicit ID is provided', () => { + process.env.NODE_ENV = 'production' + delete process.env.DBOS__VMID + delete process.env.SHUMAI_WORKER_ID + delete process.env.POD_NAME + + const worker1 = new DbosExecutor([TaskQueueTranscode]) + const worker2 = new DbosExecutor([TaskQueueTranscode]) + + const id1 = worker1.getExecutorId() + const id2 = worker2.getExecutorId() + + expect(id1).not.toBe(id2) + expect(id1).toContain('shumai-transcode') + expect(id2).toContain('shumai-transcode') + }) + + it('should incorporate SHUMAI_WORKER_ID or POD_NAME when configured', () => { + process.env.NODE_ENV = 'production' + delete process.env.DBOS__VMID + + process.env.SHUMAI_WORKER_ID = 'replica-42' + const workerWithId = new DbosExecutor([TaskQueueTranscode]) + expect(workerWithId.getExecutorId()).toBe('shumai-transcode-replica-42') + + delete process.env.SHUMAI_WORKER_ID + process.env.POD_NAME = 'shumai-transcode-pod-0' + const workerWithPod = new DbosExecutor([TaskQueueTranscode]) + expect(workerWithPod.getExecutorId()).toBe('shumai-transcode-pod-0') + }) + + it('should allow setting explicit executorId via constructor or setExecutorId', () => { + const customWorker = new DbosExecutor([TaskQueueAgent], 'my-custom-worker') + expect(customWorker.getExecutorId()).toBe('my-custom-worker') + + customWorker.setExecutorId('updated-worker-id') + expect(customWorker.getExecutorId()).toBe('updated-worker-id') + }) + + it('should not recover live workflows belonging to another executor ID on startup', async () => { + const activeWorkerId = `active-worker-${Date.now()}` + const newWorkerId = `new-worker-${Date.now()}` + const taskUuid = `task-recovery-test-${Date.now()}` + + // Seed a pending task claimed by activeWorkerId + await prisma.$queryRawUnsafe( + ` + INSERT INTO dbos.workflow_status ( + workflow_uuid, status, name, executor_id, created_at, updated_at, application_version, application_name, queue_name + ) VALUES ( + $1, 'PENDING', 'testRecoveryWorkflow', $2, 0, 0, '1.0.0', 'shumai', 'transcode_queue' + ) + `, + taskUuid, + activeWorkerId, + ) + + try { + // Launch a new worker with a distinct executor ID + const newWorker = new DbosExecutor([TaskQueueTranscode], newWorkerId) + newWorker.start() + await newWorker.ensureLaunched() + + // Verify the active worker's task was NOT recovered (remains PENDING with activeWorkerId) + const rowsAfterOtherWorker = await prisma.$queryRawUnsafe< + Array<{ status: string; executorId: string }> + >( + 'SELECT status, executor_id AS "executorId" FROM dbos.workflow_status WHERE workflow_uuid = $1', + taskUuid, + ) + expect(rowsAfterOtherWorker[0].status).toBe('PENDING') + expect(rowsAfterOtherWorker[0].executorId).toBe(activeWorkerId) + + await newWorker.shutdown() + + // Now simulate the active worker restarting with its OWN executor ID + const restartedWorker = new DbosExecutor([TaskQueueTranscode], activeWorkerId) + restartedWorker.start() + await restartedWorker.ensureLaunched() + + // Verify that on restart with the SAME executor ID, DBOS startup recovery DOES re-enqueue it + const rowsAfterRestart = await prisma.$queryRawUnsafe< + Array<{ status: string; executorId: string }> + >( + 'SELECT status, executor_id AS "executorId" FROM dbos.workflow_status WHERE workflow_uuid = $1', + taskUuid, + ) + expect(rowsAfterRestart[0].status).toBe('ENQUEUED') + + await restartedWorker.shutdown() + } finally { + await prisma.$queryRawUnsafe( + 'DELETE FROM dbos.workflow_status WHERE workflow_uuid = $1', + taskUuid, + ) + } + }, 20000) + }) + describe('Cancellation', () => { it('should trigger local cancellation and abort signal', async () => { const { diff --git a/packages/workflow-core/src/dbos-executor.ts b/packages/workflow-core/src/dbos-executor.ts index 2674e94a..7074ff85 100644 --- a/packages/workflow-core/src/dbos-executor.ts +++ b/packages/workflow-core/src/dbos-executor.ts @@ -1,3 +1,4 @@ +import os from 'node:os' import { DBOS, DBOSClient } from '@dbos-inc/dbos-sdk' import { logger } from '@shumai/core/src/logger' import { prisma, WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db' @@ -60,11 +61,16 @@ export class DbosExecutor implements Executor { private listenQueues: string[] = [TaskQueueAgent, TaskQueueTranscode] private heartbeatIntervals = new Map() private inFlightSubmits = new Set>() + private executorId?: string + private instanceSuffix = Math.random().toString(36).slice(2, 8) - constructor(listenQueues?: string[]) { + constructor(listenQueues?: string[], executorId?: string) { if (listenQueues) { this.listenQueues = listenQueues } + if (executorId) { + this.executorId = executorId + } } isStarted(): boolean { @@ -165,12 +171,7 @@ 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)}` - } + getRole(): string { if (this.listenQueues.length === 0) return 'shumai-web' if (this.listenQueues.length === 1) { if (this.listenQueues[0] === TaskQueueTranscode) return 'shumai-transcode' @@ -179,6 +180,40 @@ export class DbosExecutor implements Executor { return 'shumai-all' } + setExecutorId(id: string): void { + this.executorId = id + } + + getExecutorId(): string { + return this.getDefaultExecutorId() + } + + private getDefaultExecutorId(): string { + if (this.executorId) return this.executorId + if (process.env.DBOS__VMID) return process.env.DBOS__VMID + + const role = this.getRole() + if (process.env.SHUMAI_WORKER_ID) { + const workerId = process.env.SHUMAI_WORKER_ID + return workerId.startsWith(role) ? workerId : `${role}-${workerId}` + } + + if (process.env.NODE_ENV === 'test') { + return `shumai-test-${process.pid}-${this.instanceSuffix}` + } + + // In Kubernetes, POD_NAME is standard and stable across pod restarts in StatefulSets + if (process.env.POD_NAME) { + const pod = process.env.POD_NAME + return pod.startsWith(role) ? pod : `${role}-${pod}` + } + + // In Docker containers, HOSTNAME is set to the unique container short ID. + // If running on host machine / bare metal, disambiguate with pid and instance suffix. + const host = process.env.HOSTNAME || os.hostname() || 'instance' + return `${role}-${host}-${process.pid}-${this.instanceSuffix}` + } + async ensureLaunched(): Promise { if (DBOS.isInitialized()) { return