From a16a1515d7af16ae0054706319d8bccd2e5f3916 Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 18 Oct 2026 22:35:11 +0800 Subject: [PATCH] feat(deploy): implement KEDA ScaledJob and scale-to-zero On-Demand transcoding --- CHANGELOG.md | 3 +- apps/transcode/src/index.ts | 40 +++- apps/web/src/index.ts | 5 +- docs/configuration/distributed.mdx | 26 +-- eks/README.md | 176 +++++++++--------- eks/config.yaml | 2 + eks/eks-cluster.yaml | 21 ++- eks/kustomization.yaml | 1 - eks/shumai-transcode-hpa.yaml | 39 ---- eks/shumai-transcode.yaml | 142 +++++++++----- packages/db/src/prisma-json-types.ts | 7 + .../src/activities/transcode.test.ts | 34 ++++ .../transcode/src/activities/transcode.ts | 46 ++++- .../src/workflows/transcode-video.test.ts | 10 + .../src/workflows/transcode-video.ts | 14 +- packages/workflow-core/src/activities/task.ts | 6 +- .../workflow-core/src/dbos-executor.test.ts | 114 ++++++++++-- packages/workflow-core/src/dbos-executor.ts | 109 ++++++++--- packages/workflow-core/src/workflow.test.ts | 140 ++++++++++++++ packages/workflow-core/src/workflow.ts | 165 +++++++++++++++- 20 files changed, 845 insertions(+), 255 deletions(-) delete mode 100644 eks/shumai-transcode-hpa.yaml diff --git a/CHANGELOG.md b/CHANGELOG.md index 8870bcf5..45376f64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added -* **deploy**: Add dedicated `shumaione/shumai-transcode` Docker image and a complete AWS EKS deployment example (`eks/`) featuring Graviton5 (`c9g.xlarge`) Spot instances and horizontal autoscaling for media processing +* **deploy**: Add dedicated `shumaione/shumai-transcode` Docker image and a complete AWS EKS deployment example (`eks/`) featuring KEDA queue-driven autoscaling, `--once` worker execution mode, and Scale-to-Zero On-Demand Graviton5 instances for media processing +* **workflow**: Add automated stale-heartbeat recovery sweep to detect dead or terminated worker nodes and resume pending tasks in DBOS without losing completed steps * **storage**: Support configuring a separate public endpoint (`AWS_PUBLIC_ENDPOINT_URL_S3`) for browser-facing presigned URLs while preserving internal cluster endpoints for backend workers diff --git a/apps/transcode/src/index.ts b/apps/transcode/src/index.ts index 9145bb1b..17c1cdd2 100644 --- a/apps/transcode/src/index.ts +++ b/apps/transcode/src/index.ts @@ -14,14 +14,26 @@ async function run() { // Initialize workflows and activities initTranscodeWorkflows() - console.log('πŸš€ Starting Transcode Worker...') + const isOnce = process.argv.includes('--once') || process.env.SHUMAI_WORKER_ONCE === 'true' + if (isOnce) { + workflowService.getExecutor().setOnceMode(true) + console.log('πŸš€ Starting Transcode Worker in --once mode (single-task execution)...') + } else { + console.log('πŸš€ Starting Transcode Worker...') + } await workflowService.startWorkers(TaskQueueTranscode) let isShuttingDown = false + let idleTimer: Timer | null = null + const shutdown = async () => { if (isShuttingDown) return isShuttingDown = true + if (idleTimer) { + clearTimeout(idleTimer) + idleTimer = null + } console.log('Shutting down Transcode Worker gracefully...') try { await workflowService.shutdownWorkers() @@ -31,6 +43,32 @@ async function run() { process.exit(0) } + if (isOnce) { + const idleTimeoutMs = process.env.SHUMAI_WORKER_IDLE_TIMEOUT_MS + ? parseInt(process.env.SHUMAI_WORKER_IDLE_TIMEOUT_MS, 10) + : 15_000 + + idleTimer = setTimeout(async () => { + console.log( + `[Transcode Worker] No tasks received within idle timeout (${idleTimeoutMs / 1000}s), shutting down.`, + ) + await shutdown() + }, idleTimeoutMs) + + workflowService.getExecutor().on('workflowStarted', (task) => { + console.log(`[Transcode Worker] Claimed task ${task.id}, cancelling idle timer.`) + if (idleTimer) { + clearTimeout(idleTimer) + idleTimer = null + } + }) + + workflowService.getExecutor().on('workflowFinished', async ({ taskId }) => { + console.log(`[Transcode Worker] Completed task ${taskId} in --once mode, shutting down.`) + await shutdown() + }) + } + process.on('SIGINT', shutdown) process.on('SIGTERM', shutdown) } diff --git a/apps/web/src/index.ts b/apps/web/src/index.ts index 6997d954..80aef47e 100644 --- a/apps/web/src/index.ts +++ b/apps/web/src/index.ts @@ -109,6 +109,7 @@ async function run() { } workflowService.start(listenQueues) + workflowService.startStaleTaskRecovery() const isProd = process.env.NODE_ENV === 'production' @@ -206,8 +207,10 @@ async function run() { console.log(`πŸš€ Server running at ${server.url}`) - const shutdown = () => { + const shutdown = async () => { console.log('\nShutting down gracefully...') + workflowService.stopStaleTaskRecovery() + await workflowService.shutdownWorkers().catch(() => {}) assetService.stopCleanupJob() server.stop(true) process.exit(0) diff --git a/docs/configuration/distributed.mdx b/docs/configuration/distributed.mdx index 8cedd1db..42466e03 100644 --- a/docs/configuration/distributed.mdx +++ b/docs/configuration/distributed.mdx @@ -132,29 +132,33 @@ When running multiple replicas of the transcode or agent worker across multiple ## Scalable Deployment on Kubernetes & AWS EKS -For production cloud deployments requiring high-throughput media processing, Shumai can be deployed on Kubernetes or **AWS Elastic Kubernetes Service (AWS EKS)** with automated horizontal autoscaling. +For production cloud deployments requiring high-throughput media processing, Shumai can be deployed on Kubernetes or **AWS Elastic Kubernetes Service (AWS EKS)** with automated scale-to-zero queue-driven scaling via **KEDA (Kubernetes Event-driven Autoscaling)**. ```mermaid graph TD User([User / Web Browser]) -->|Port 80/3000| Server[Pod: shumai-server
SHUMAI_WORKERS=agent] - Server -->|Enqueue to transcode_queue| DB[(PostgreSQL: pgvector18)] + Server -->|Enqueue to transcode_queue| DB[(PostgreSQL: pgvector18
dbos.workflow_status)] Server -->|Direct Uploads / Stream Proxies| Storage[(S3 / Garage Storage)] - DB -->|Poll transcode_queue| Worker1[Pod: shumai-transcode-1] - DB -->|Poll transcode_queue| WorkerN[Pod: shumai-transcode-N
Autoscaled: 1..5 Replicas] - Worker1 -->|Fetch Source / Store Proxies| Storage - WorkerN -->|Fetch Source / Store Proxies| Storage + KEDA[KEDA ScaledJob
PostgreSQL Trigger
min: 0, max: 10] -.->|Monitors Queue| DB + KEDA -->|Spawns 1 Job per task| Job1[Job: shumai-transcode-1
--once mode] + KEDA -->|Spawns 1 Job per task| JobN[Job: shumai-transcode-N
--once mode] - HPA[HorizontalPodAutoscaler
Target: 70% CPU
min: 1, max: 5] -.->|Autoscale Pods| WorkerN - CA[Cluster Autoscaler] -.->|Autoscale c9g.xlarge Spot Nodes| WorkerN + Job1 -->|Fetch Source / Store Proxies| Storage + JobN -->|Fetch Source / Store Proxies| Storage + Job1 -->|Mark Complete & Exit 0| DB + JobN -->|Mark Complete & Exit 0| DB + + CA[Cluster Autoscaler / Karpenter] -.->|Scale-to-Zero On-Demand Nodes
0 to 10 instances| JobN ``` ### Key Architectural Highlights - **Decoupled Stateless Workers**: The main web and API server, database, and storage run on reliable On-Demand compute (`c9g.large`, `SHUMAI_WORKERS=agent`), delegating media transcoding to background workers orchestrated via DBOS task queues in PostgreSQL. -- **Dedicated Graviton5 Spot Compute (`c9g.xlarge`)**: Media encoding runs on 4 vCPU / 8 GiB RAM AWS Graviton5 Spot instances (~$0.08/hr), utilizing ARM64 vector optimizations and high-speed DDR5 memory to achieve exceptional encoding performance at minimal cost. -- **1:1 Pod-to-Node Scaling**: Worker pods request `3000m` CPU, guaranteeing that each active transcoding job gets an entire dedicated 4 vCPU `c9g.xlarge` instance without CPU throttling. -- **End-to-End Autoscaling**: Kubernetes HPA detects encoding load and scales worker pods (1 to 5 replicas), while Kubernetes Cluster Autoscaler provisions and terminates underlying EC2 Spot instances automatically. +- **Dedicated Graviton5 On-Demand Compute (`c9g.xlarge`)**: Media encoding runs on 4 vCPU / 8 GiB RAM AWS Graviton5 On-Demand instances (~$0.174/hr), utilizing ARM64 vector optimizations and high-speed DDR5 memory without involuntary Spot interruptions. +- **Queue-Driven Scale-to-Zero via KEDA**: KEDA monitors `dbos.workflow_status` for enqueued and pending transcode tasks and dynamically provisions Kubernetes `ScaledJob` resources (scaling 0 to 10). When the queue is empty, transcode nodes scale down to zero (`minSize: 0`), incurring **$0/hr** in worker costs. +- **Single-Workflow `--once` Mode**: Each worker pod runs in `--once` mode, claims exactly 1 workflow task, processes it to completion, and exits `0`. Because each task runs in an isolated Kubernetes Job, terminating or finishing jobs never interrupts peer tasks. +- **Automated Stale Task Recovery**: The core web server runs an integrated recovery sweep that detects stale or orphaned tasks (e.g. from node crash) and resumes them automatically in DBOS, with a 3-attempt cap to safely handle poison-pill media. ### Complete Deployment Example & Source Code diff --git a/eks/README.md b/eks/README.md index e258b1e1..7e3b85ea 100644 --- a/eks/README.md +++ b/eks/README.md @@ -1,10 +1,10 @@ -# Shumai on AWS EKS with Graviton5 Spot & Autoscaling +# Shumai on AWS EKS with KEDA & Scale-to-Zero On-Demand Workers -This directory contains a complete, production-ready Kubernetes deployment example for running Shumai on **Amazon Elastic Kubernetes Service (Amazon EKS)**, with horizontal autoscaling for compute-intensive media processing. +This directory contains a complete, production-ready Kubernetes deployment example for running Shumai on **Amazon Elastic Kubernetes Service (Amazon EKS)**, using **KEDA (Kubernetes Event-driven Autoscaling)** and **Scale-to-Zero On-Demand AWS Graviton5 instances** for compute-intensive media processing. -The example should also be straightforward to adapt to a generic Kubernetes cluster. +The example should also be straightforward to adapt to any standard Kubernetes cluster. -To demonstrate a fully self-hosted setup, it uses Garage as an S3-compatible object storage solution. However, if you're deploying on AWS, consider using **Amazon S3** instead of running your own S3-compatible storage server, as it can be significantly more cost-effective and easier to manage. +To demonstrate a fully self-hosted setup, it uses Garage as an S3-compatible object storage solution. However, if you're deploying on AWS, consider using **Amazon S3** instead of running your own S3-compatible storage server, as it is managed and highly scalable. --- @@ -27,7 +27,8 @@ To demonstrate a fully self-hosted setup, it uses Garage as an S3-compatible obj β”‚ β–Ό β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” Enqueue DBOS Tasks β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ shumai-server β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Ίβ”‚ shumai-postgres β”‚ β”‚ -β”‚ β”‚(SHUMAI_WORKERS=agent) β”‚ (transcode_queue) β”‚ (pgvector:pg18) β”‚ β”‚ +β”‚ β”‚(SHUMAI_WORKERS=agent) β”‚ (task_queue_transcode) β”‚ (pgvector:pg18) β”‚ β”‚ +β”‚ β”‚ [Stale Recovery Loop] β”‚ β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ Internal S3 Traffic β”‚ β”‚ β”‚ β–Ό β”‚ β”‚ @@ -36,22 +37,29 @@ To demonstrate a fully self-hosted setup, it uses Garage as an S3-compatible obj β”‚ β”‚ (dxflrs/garage) β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–²β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ Read Source / Write Proxies β”‚ Poll Tasks - β”‚ β–Ό + β”‚ Read Source / Write Proxies β”‚ + β”‚ β”‚ KEDA monitors + β”‚ β–Ό dbos.workflow_status + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ β”‚ KEDA Controller: ScaledJob β”‚ + β”‚ β”‚ Spawns 1 Job per enqueued task (0..10)β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”‚ + β”‚ β–Ό Creates K8s Jobs β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ Transcode Compute Pool (c9g.xlarge Graviton5 Spot, ~$0.08/hr, 1 Pod per Node) β”‚ +β”‚ Transcode Compute Pool (c9g.xlarge Graviton5 On-Demand, minSize: 0, maxSize: 10) β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ -β”‚ β”‚ shumai-transcode β”‚ β”‚ shumai-transcode β”‚ β”‚ shumai-transcode β”‚ β”‚ -β”‚ β”‚ (Worker Pod 1) β”‚ β”‚ (Worker Pod 2) β”‚ β”‚ (Worker Pod N) β”‚ β”‚ +β”‚ β”‚ Job: transcode-job-1 β”‚ β”‚ Job: transcode-job-2 β”‚ β”‚Job: transcode-job-Nβ”‚ β”‚ +β”‚ β”‚ (Worker Pod: --once) β”‚ β”‚ (Worker Pod: --once) β”‚ β”‚ (Worker Pod: --onceβ”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β–Ό β–Ό β–Ό β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ Node 1: c9g.xlarge β”‚ β”‚ Node 2: c9g.xlarge β”‚ β”‚ Node N: c9g.xlarge β”‚ β”‚ -β”‚ β”‚ (Spot) β”‚ β”‚ (Spot) β”‚ β”‚ (Spot) β”‚ β”‚ +β”‚ β”‚ (On-Demand) β”‚ β”‚ (On-Demand) β”‚ β”‚ (On-Demand) β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ -β”‚ HPA: Scales pods 1..5 on CPU > 70% β”‚ Cluster Autoscaler: Scales Spot nodes 1..5 β”‚ +β”‚ Scale-to-Zero: When queue is empty, 0 Jobs run and 0 EC2 instances are billed! β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` @@ -59,65 +67,51 @@ To demonstrate a fully self-hosted setup, it uses Garage as an S3-compatible obj ## Core Design Principles -### 1. Compute Tiering: On-Demand Core & Graviton Spot Workers +### 1. Scale-to-Zero On-Demand Instances (`minSize: 0`) -Media transcoding with FFmpeg is one of the most CPU-intensive workloads in modern web applications. To ensure rock-solid stability for persistent data while minimizing transcoding costs, this deployment strictly separates system services from media encoding: +Media transcoding with FFmpeg is bursty: hours may pass with zero transcoding activity, followed by sudden batches of 4K video uploads. -- **General System Node (`shumai-general`)**: A single 2 vCPU / 4 GiB RAM (`c9g.large` **On-Demand**) node (~$0.087/hr) hosts the Web UI, API server, PostgreSQL database, and Garage S3. - > [!IMPORTANT] - > **Why On-Demand for Core Services?** - > Spot instances are subject to involuntary AWS reclamation (interruption). Running stateful services (PostgreSQL, local S3 storage) and the primary user-facing API on an On-Demand instance guarantees that the database and storage layers are never killed, evicted, or subject to abrupt downtime. +- **Zero Idle Cost**: The transcode node group [`eks/eks-cluster.yaml`](./eks-cluster.yaml) is configured with `minSize: 0` and `desiredCapacity: 0`. When no media transcoding tasks are active, **zero transcode EC2 instances exist**, costing **$0/hr**. +- **No Spot Interruption Risk**: Transcoding jobs run on AWS Graviton5 **On-Demand** instances (`c9g.xlarge`, ~$0.174/hr). This eliminates the risk of Spot instances being reclaimed mid-encode by AWS, preventing wasted CPU cycles and avoiding unexpected transcoding delays. -- **Dedicated Transcode Pool (`shumai-transcode-spot`)**: High-performance 4 vCPU / 8 GiB RAM Graviton Spot instances (`c9g.xlarge` primary, with `c8g.xlarge` fallback pools) dedicated exclusively to media encoding. +### 2. KEDA `ScaledJob` vs. `Deployment` / `StatefulSet` -### 2. Task Orchestration via DBOS Transact +Standard Kubernetes Horizontal Pod Autoscaler (HPA) scales `Deployment` replicas based on metrics like CPU utilization. However, HPAs on Deployments suffer from severe limitations during video processing: +1. When a 1-minute video finishes on Pod A while a 30-minute video is still encoding on Pod B, CPU drops and HPA reduces replica count, which can arbitrarily terminate Pod B mid-encode. +2. StatefulSets scale down in strict ordinal order (`pod-4`, `pod-3`, etc.), which would terminate `pod-4` even if `pod-4` is the only pod currently transcoding! -All video and document transcoding jobs are enqueued to `transcode_queue` inside PostgreSQL via **DBOS Transact**. Transcode workers are completely stateless and consume jobs from the queue. Each worker pod uses the Kubernetes Downward API (`POD_NAME`) to obtain a unique, collision-free executor ID. +**KEDA `ScaledJob` solves this natively**: +- KEDA queries PostgreSQL directly: + ```sql + SELECT COUNT(*) FROM dbos.workflow_status WHERE queue_name = 'task_queue_transcode' AND status IN ('ENQUEUED', 'PENDING'); + ``` +- KEDA spawns an independent Kubernetes `Job` for each enqueued task. +- Each Job runs the transcode worker in `--once` mode. +- When the job's video finishes transcoding, the pod exits `0` and Kubernetes marks the Job completed. +- Completing or terminating one job **never impacts any other job**! -### 3. What Happens If Transcode Spot Nodes Are Interrupted or Killed? +### 3. Single-Task Worker Execution (`--once` Mode) -Because the transcode workers are completely stateless and coordinated via **DBOS Transact** against PostgreSQL on the On-Demand node: +In [`eks/shumai-transcode.yaml`](./shumai-transcode.yaml), the worker container runs with `bun run /app/apps/transcode/src/index.ts --once`: +- Transcode concurrency is strictly set to `1`. +- The worker claims 1 DBOS workflow task from `task_queue_transcode`. +- As soon as that task finishes (success, failure, or cancellation), the worker initiates graceful DBOS drain and exits with code `0`. +- **Idle Timeout**: If a job was spawned but another worker claimed the task first, the worker waits 15 seconds. If no task arrives within 15 seconds, it exits `0` cleanly so the pod and node can shut down. -1. **State Isolation**: - PostgreSQL, EBS persistent volume claims, the Web UI, and S3 storage live on the On-Demand node and are **never terminated** during Spot interruptions. -2. **AWS 2-Minute Interruption Warning & Graceful Drain**: - When AWS reclaims a Spot instance, it issues a 2-minute notice. Kubernetes drains the node and sends `SIGTERM` to the worker pod. With `terminationGracePeriodSeconds: 300`, the worker finishes any encoding step currently near completion, uploads the result to S3, and exits cleanly. -3. **Automatic Step Recovery via DBOS**: - If an instance is terminated abruptly mid-encode, **zero data or tasks are lost**. The video source file remains safe in S3. DBOS workflow step states are durably tracked in PostgreSQL; uncompleted tasks are detected by surviving or newly launched workers and automatically re-executed from their last durable checkpoint. -4. **Spot Capacity Pool Diversification**: - [`eks/eks-cluster.yaml`](./eks-cluster.yaml) configures `instanceTypes: [c9g.xlarge, c8g.xlarge]`. If AWS temporarily exhausts Graviton5 (`c9g.xlarge`) Spot capacity in an Availability Zone, the Auto Scaling Group immediately falls back to Graviton4 (`c8g.xlarge`) Spot capacity. All three families share the same 4 vCPU / 8 GiB RAM profile and ARM64 architecture. -5. **What If All Spot Nodes Are Killed Simultaneously?** - - Transcode worker pods enter `Pending` state (`Insufficient cpu`). - - All newly submitted transcode jobs queue safely inside PostgreSQL on the On-Demand node. No user uploads or jobs are dropped. - - The **Cluster Autoscaler** detects the `Pending` pods and continuously requests new EC2 Spot instances from AWS. - - As soon as Spot capacity becomes available (typically within 1–2 minutes), new nodes launch, pods schedule to `Running`, and workers resume draining the queue. +### 4. Automated Stale-Heartbeat Recovery Sweep ---- +If a worker node crashes abruptly (e.g. host kernel panic or hardware failure): +- Every active worker updates `WorkflowTask.heartbeat` in PostgreSQL every 5 seconds. +- The single core web server (`shumai-server`) runs a lightweight background sweep every 30 seconds (`workflowService.startStaleTaskRecovery()`). +- Any task stuck in `status = 'processing'` with `heartbeat < now() - 90s` and whose DBOS status is `'PENDING'` is automatically re-enqueued via `client.resumeWorkflow(task.id, { queueName })`. +- Resumed workflows skip already completed steps using DBOS durable operation outputs. +- **Poison-Pill Protection**: If a malformed media file crashes workers repeatedly, after 3 recovery attempts the task and asset are marked as `failed` to prevent infinite restart loops. -## Autoscaling Mechanics +### 5. Zombie Worker & Graceful Shutdown Safety -Autoscaling operates across two coordinated layers: - -```mermaid -flowchart LR - Upload[Video Uploads Spike] --> HPA[HPA detects CPU > 70%] - HPA --> ScalePods[Scale Pods 1 to 5] - ScalePods --> Pending[Pods Enter Pending: 3000m CPU needed] - Pending --> CA[Cluster Autoscaler launches c9g.xlarge Spot nodes] - CA --> Ready[1 Pod scheduled per dedicated c9g.xlarge Node] -``` - -1. **Horizontal Pod Autoscaler (HPA)**: - - Configured in [`shumai-transcode-hpa.yaml`](./shumai-transcode-hpa.yaml) targeting **70% CPU utilization** of the pod's `3000m` CPU request (= 2.1 vCPUs). - - When a video transcode starts, FFmpeg consumes ~3.5 cores, immediately exceeding 70% and prompting HPA to scale out worker pods (up to 5 replicas). -2. **1:1 Dedicated Pod-to-Node Allocation**: - - In [`shumai-transcode.yaml`](./shumai-transcode.yaml), worker pods request `cpu: 3000m` and `memory: 4Gi` with limits at `cpu: 3900m` and `memory: 6Gi`. - - Because a `c9g.xlarge` instance has `3920m` allocatable CPU, **strictly 1 transcode pod can fit per node**, giving FFmpeg unrestricted access to all 4 physical cores without CPU throttling. - - Additional pods enter `Pending` state, which immediately triggers the **Kubernetes Cluster Autoscaler** to scale up the AWS Auto Scaling Group (`shumai-transcode-spot`). -3. **Graceful Scale-Down & Task Safety**: - - **5-Minute HPA Stabilization Window** (`stabilizationWindowSeconds: 300`): Once the queue is clear and CPU drops to 0%, HPA holds replicas for 5 minutes to avoid pod thrashing if new uploads arrive. - - **5-Minute Termination Grace Period** (`terminationGracePeriodSeconds: 300`): When Kubernetes terminates a worker, it sends `SIGTERM`. The worker stops taking new jobs, drains the active FFmpeg transcode step, uploads proxies to S3, and exits cleanly. - - **10-Minute Node Cooldown**: Cluster Autoscaler waits for idle nodes to be unneeded for 10 minutes (`scale-down-unneeded-time=10m`) before cordoning, draining, and terminating the EC2 Spot instance. +- When Kubernetes drains a node or sends `SIGTERM`, `DBOS.shutdown({ workflowCompletionTimeoutMS: 290_000 })` gives the worker up to 290 seconds to finish its active FFmpeg step and upload proxies to S3. +- Heartbeats remain active throughout the shutdown drain period to prevent the web server from prematurely declaring the worker dead. +- If a slow worker resumes execution after ownership was transferred, DBOS raises `DBOSWorkflowConflictError` (code 5). Shumai catches this error and avoids overwriting the active task or asset status. --- @@ -128,6 +122,7 @@ flowchart LR - [AWS CLI](https://aws.amazon.com/cli/) installed and configured (`aws configure`). - [`eksctl`](https://eksctl.io/) installed. - [`kubectl`](https://kubernetes.io/docs/tasks/tools/) installed. +- [`helm`](https://helm.sh/) installed. ### Step 1: Provision the EKS Cluster @@ -138,12 +133,28 @@ eksctl create cluster -f eks/eks-cluster.yaml ``` This provisions: -- An EKS 1.31 control plane in a dedicated VPC across multiple AZs. -- `shumai-general`: 1x `c9g.large` On-Demand instance (labeled `workload: general`) for reliable API, database, and storage. -- `shumai-transcode-spot`: Autoscaling `c9g.xlarge` Spot instances with `c8g.xlarge` fallback pools (min: 1, max: 5, labeled `workload: transcode`). +- An EKS 1.31 control plane across multiple AZs. +- `shumai-general`: 1x `c9g.large` On-Demand instance (labeled `workload: general`) for API, database, and storage. +- `shumai-transcode`: Scale-to-zero `c9g.xlarge` On-Demand instance pool (`minSize: 0`, `maxSize: 10`, `desiredCapacity: 0`, tainted `dedicated=transcode:NoSchedule`). - AWS EBS CSI Driver with IAM OIDC roles. -### Step 2: Deploy the Shumai Stack +### Step 2: Install KEDA + +Install KEDA using Helm: + +```bash +helm repo add kedacore https://kedacore.github.io/charts +helm repo update +helm install keda kedacore/keda --namespace keda --create-namespace +``` + +Verify KEDA operator is running: + +```bash +kubectl get pods -n keda +``` + +### Step 3: Deploy the Shumai Stack Deploy all components with Kustomize: @@ -151,13 +162,13 @@ Deploy all components with Kustomize: kubectl apply -k eks/ ``` -Verify that all initial pods reach `Running` state: +Verify initial core pods on the general node reach `Running` state: ```bash kubectl get pods -n shumai -o wide ``` -### Step 3: Configure Public Access & S3 Endpoint +### Step 4: Configure Public Access & S3 Endpoint Retrieve the external LoadBalancer hostnames created by AWS: @@ -171,7 +182,6 @@ shumai-server LoadBalancer k8s-shumai-xxx.us-east-1.elb.amazonaws.com 80:31 garage-public LoadBalancer k8s-garage-xxx.us-east-1.elb.amazonaws.com 3900:31236/TCP ``` -#### Option A: Quick Testing (Automated 1-Liner) Inject the public Garage ELB hostname into `shumai-server`: ```bash @@ -179,19 +189,11 @@ GARAGE_ELB=$(kubectl get svc garage-public -n shumai -o jsonpath='{.status.loadB kubectl set env deployment/shumai-server -n shumai AWS_PUBLIC_ENDPOINT_URL_S3="http://${GARAGE_ELB}:3900" ``` -#### Option B: Production with Custom Domains -In production, point DNS records (e.g. Route 53) to your load balancers: -- Web App: `https://shumai.mycompany.com` -- S3 Storage: `https://s3.mycompany.com` +*(Note: In production with custom domains, point your DNS to the load balancers and configure `AWS_PUBLIC_ENDPOINT_URL_S3: https://s3.mycompany.com` in [`eks/config.yaml`](./config.yaml).)* -Set `AWS_PUBLIC_ENDPOINT_URL_S3: https://s3.mycompany.com` in [`eks/config.yaml`](./config.yaml) and apply once. +### Step 5: Deploy Kubernetes Cluster Autoscaler -#### Option C: Native Amazon S3 -If using real AWS S3, set `STORAGE_BACKEND: s3`, provide `S3_BUCKET`, and omit `AWS_PUBLIC_ENDPOINT_URL_S3` (native AWS S3 endpoints resolve globally). - -### Step 4: Deploy Kubernetes Cluster Autoscaler - -Deploy the official Cluster Autoscaler to enable automated node provisioning: +Deploy Cluster Autoscaler to dynamically provision `c9g.xlarge` EC2 nodes when KEDA jobs are created: ```bash curl -s https://raw.githubusercontent.com/kubernetes/autoscaler/master/cluster-autoscaler/cloudprovider/aws/examples/cluster-autoscaler-autodiscover.yaml \ @@ -202,20 +204,22 @@ curl -s https://raw.githubusercontent.com/kubernetes/autoscaler/master/cluster-a kubectl patch deployment cluster-autoscaler -n kube-system -p '{"spec":{"template":{"spec":{"nodeSelector":{"workload":"general"}}}}}' ``` -### Step 5: Test Horizontal Autoscaling +### Step 6: Test Scale-to-Zero Queue-Driven Autoscaling 1. Open `http://` in your browser and log in with your credentials. -2. Upload a batch of 10–20 video files simultaneously. -3. Watch the workers scale up horizontally: +2. Upload a batch of 5–10 video files simultaneously. +3. Observe KEDA detecting the tasks and spawning individual Kubernetes Jobs: ```bash - kubectl get hpa -n shumai -w + kubectl get scaledjobs -n shumai + kubectl get jobs -n shumai -w kubectl get pods -n shumai -l app=shumai-transcode -o wide - kubectl get nodes -L node.kubernetes.io/instance-type,workload + kubectl get nodes -L role,workload ``` -4. Observe that each worker consumes ~3 vCPUs on its dedicated `c9g.xlarge` instance. -5. Once all jobs complete, observe HPA scaling back down to 1 pod and Cluster Autoscaler terminating idle EC2 Spot instances. +4. Watch Cluster Autoscaler provision dedicated `c9g.xlarge` EC2 instances for the Jobs. +5. As each video finishes transcoding, its pod exits `0` and completes immediately. +6. Once all jobs are done, KEDA holds 0 jobs, and Cluster Autoscaler terminates all transcode EC2 instances, returning the transcode pool to **0 nodes ($0/hr)**! -### Step 6: Cluster Teardown & Cost Cleanup +### Step 7: Cluster Teardown & Cost Cleanup When you are finished testing, delete all resources to prevent ongoing cloud charges: diff --git a/eks/config.yaml b/eks/config.yaml index 7023155f..d3669c16 100644 --- a/eks/config.yaml +++ b/eks/config.yaml @@ -14,6 +14,7 @@ data: # Server & Worker Configuration SHUMAI_SERVER_PORT: '3000' CONCURRENCY_TRANSCODE: '1' + SHUMAI_WORKER_DRAIN_TIMEOUT_MS: '290000' --- apiVersion: v1 kind: Secret @@ -23,6 +24,7 @@ metadata: type: Opaque stringData: DATABASE_URL: 'postgresql://shumai:shumai_password@shumai-postgres.shumai.svc.cluster.local:5432/shumai_db?schema=public' + KEDA_DATABASE_URL: 'postgresql://shumai:shumai_password@shumai-postgres.shumai.svc.cluster.local:5432/shumai_db?sslmode=disable' BETTER_AUTH_SECRET: 'qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=' S3_ACCESS_KEY_ID: 'GKshumaiaccesskeyid001' S3_SECRET_ACCESS_KEY: 'shumaisecretaccesskey00000000000000001' diff --git a/eks/eks-cluster.yaml b/eks/eks-cluster.yaml index 57008d0f..73ef465f 100644 --- a/eks/eks-cluster.yaml +++ b/eks/eks-cluster.yaml @@ -34,20 +34,23 @@ managedNodeGroups: ebs: true # Transcoding compute pool: High-CPU media processing - # Uses Spot instances with capacity diversification across Graviton generations - - name: shumai-transcode-spot - instanceTypes: - - c9g.xlarge # 4 vCPU, 8 GiB RAM (Graviton5 Spot, ~$0.08/hr, primary) - - c8g.xlarge # 4 vCPU, 8 GiB RAM (Graviton4 Spot, ~$0.07/hr, fallback pool) - spot: true - minSize: 1 - maxSize: 5 - desiredCapacity: 1 + # Uses On-Demand instances with scale-to-zero (minSize: 0) managed by Cluster Autoscaler / Karpenter + - name: shumai-transcode + instanceType: c9g.xlarge # 4 vCPU, 8 GiB RAM (Graviton5 On-Demand, ~$0.174/hr) + spot: false + minSize: 0 + maxSize: 10 + desiredCapacity: 0 amiFamily: AmazonLinux2023 volumeSize: 50 volumeType: gp3 labels: workload: transcode + role: transcode + taints: + - key: dedicated + value: transcode + effect: NoSchedule iam: withAddonPolicies: autoScaler: true diff --git a/eks/kustomization.yaml b/eks/kustomization.yaml index ea1920ed..4cab21ed 100644 --- a/eks/kustomization.yaml +++ b/eks/kustomization.yaml @@ -8,4 +8,3 @@ resources: - garage.yaml - shumai-server.yaml - shumai-transcode.yaml - - shumai-transcode-hpa.yaml diff --git a/eks/shumai-transcode-hpa.yaml b/eks/shumai-transcode-hpa.yaml deleted file mode 100644 index 8e7ca868..00000000 --- a/eks/shumai-transcode-hpa.yaml +++ /dev/null @@ -1,39 +0,0 @@ -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: shumai-transcode-hpa - namespace: shumai - labels: - app: shumai-transcode -spec: - scaleTargetRef: - apiVersion: apps/v1 - kind: Deployment - name: shumai-transcode - minReplicas: 1 - maxReplicas: 5 - metrics: - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: 70 - behavior: - scaleUp: - stabilizationWindowSeconds: 0 - selectPolicy: Max - policies: - - type: Percent - value: 100 - periodSeconds: 15 - - type: Pods - value: 2 - periodSeconds: 15 - scaleDown: - stabilizationWindowSeconds: 300 - selectPolicy: Min - policies: - - type: Pods - value: 1 - periodSeconds: 60 diff --git a/eks/shumai-transcode.yaml b/eks/shumai-transcode.yaml index 48a4d29a..25f946ba 100644 --- a/eks/shumai-transcode.yaml +++ b/eks/shumai-transcode.yaml @@ -1,55 +1,97 @@ -apiVersion: apps/v1 -kind: Deployment +apiVersion: keda.sh/v1alpha1 +kind: TriggerAuthentication metadata: - name: shumai-transcode + name: keda-postgres-auth + namespace: shumai +spec: + secretTargetRef: + - parameter: connection + name: shumai-secret + key: KEDA_DATABASE_URL +--- +apiVersion: keda.sh/v1alpha1 +kind: ScaledJob +metadata: + name: shumai-transcode-scaler namespace: shumai labels: app: shumai-transcode spec: - replicas: 1 - selector: - matchLabels: - app: shumai-transcode - template: - metadata: - labels: - app: shumai-transcode - spec: - affinity: - nodeAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - nodeSelectorTerms: - - matchExpressions: - - key: eks.amazonaws.com/nodegroup - operator: In - values: - - shumai-transcode-spot - - matchExpressions: - - key: workload - operator: In - values: - - transcode - terminationGracePeriodSeconds: 300 - containers: - - name: worker - image: shumaione/shumai-transcode:latest - imagePullPolicy: IfNotPresent - env: - # Downward API: Injects the unique pod name so DbosExecutor assigns a unique, - # deterministic executor ID per worker replica across pod restarts. - - name: POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - envFrom: - - configMapRef: - name: shumai-config - - secretRef: - name: shumai-secret - resources: - requests: - cpu: 3000m - memory: 4Gi - limits: - cpu: 3900m - memory: 6Gi + jobTargetRef: + parallelism: 1 + completions: 1 + backoffLimit: 0 + template: + metadata: + labels: + app: shumai-transcode + spec: + restartPolicy: Never + terminationGracePeriodSeconds: 300 + tolerations: + - key: dedicated + operator: Equal + value: transcode + effect: NoSchedule + affinity: + nodeAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + nodeSelectorTerms: + - matchExpressions: + - key: role + operator: In + values: + - transcode + - matchExpressions: + - key: workload + operator: In + values: + - transcode + - matchExpressions: + - key: eks.amazonaws.com/nodegroup + operator: In + values: + - shumai-transcode + containers: + - name: worker + image: shumaione/shumai-transcode:latest + imagePullPolicy: IfNotPresent + command: + - bun + - run + - /app/apps/transcode/src/index.ts + - --once + env: + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: SHUMAI_WORKER_ONCE + value: 'true' + envFrom: + - configMapRef: + name: shumai-config + - secretRef: + name: shumai-secret + resources: + requests: + cpu: 3000m + memory: 4Gi + limits: + cpu: 3900m + memory: 6Gi + pollingInterval: 10 + successfulJobsHistoryLimit: 5 + failedJobsHistoryLimit: 10 + maxReplicaCount: 10 + rollout: + strategy: default + scalingStrategy: + strategy: default + triggers: + - type: postgresql + metadata: + query: "SELECT COUNT(*) FROM dbos.workflow_status WHERE queue_name = 'task_queue_transcode' AND status IN ('ENQUEUED', 'PENDING');" + targetQueryValue: '1' + authenticationRef: + name: keda-postgres-auth diff --git a/packages/db/src/prisma-json-types.ts b/packages/db/src/prisma-json-types.ts index da72629d..bb0e987b 100644 --- a/packages/db/src/prisma-json-types.ts +++ b/packages/db/src/prisma-json-types.ts @@ -360,6 +360,13 @@ declare global { imageAnnotation?: ImageAnnotationSpec pdfPages?: PdfPagesSpec watermark?: WatermarkTaskPayload + recoveryAttempts?: number + } + + export interface WorkflowTaskOutput { + error?: string + recoveryAttempts?: number + [key: string]: unknown } // ---------------------------------------------------------------------- diff --git a/packages/transcode/src/activities/transcode.test.ts b/packages/transcode/src/activities/transcode.test.ts index ac79059c..5400f428 100644 --- a/packages/transcode/src/activities/transcode.test.ts +++ b/packages/transcode/src/activities/transcode.test.ts @@ -218,6 +218,40 @@ describe('Transcode Activities', () => { ) }) + it('should resolve presigned URL when assetKey is provided without filePath for video', async () => { + const asset = await prisma.asset.create({ + data: { name: 'remote-video.mp4', type: 'file', status: 'uploaded' }, + }) + + vi.spyOn(s3Service, 'resolveInput').mockResolvedValueOnce( + 'http://s3.local/shumai/remote-video.mp4?presigned=true', + ) + vi.mocked(transcodeService.getVideoInfo).mockResolvedValueOnce({ + originalWidth: 1920, + originalHeight: 1080, + duration: 15, + bitRate: 1000000, + videoBitRate: 800000, + frameRate: 30, + totalFrames: 450, + hasAudio: false, + mimeType: 'video/mp4', + }) + + const result = await getMediaInfoActivity({ + assetId: asset.id, + assetKey: 'remote-video.mp4', + proxyType: 'video', + mediaType: 'video/mp4', + }) + + expect(s3Service.resolveInput).toHaveBeenCalledWith(expect.any(String), 'remote-video.mp4') + expect(transcodeService.getVideoInfo).toHaveBeenCalledWith( + 'http://s3.local/shumai/remote-video.mp4?presigned=true', + ) + expect(result.duration).toBe(15) + }) + it('should downgrade proxyType to audio when getVideoInfo throws No video stream found but audio exists', async () => { const asset = await prisma.asset.create({ data: { name: 'audio-with-art.mp4', type: 'file', status: 'uploaded' }, diff --git a/packages/transcode/src/activities/transcode.ts b/packages/transcode/src/activities/transcode.ts index e7a93c19..58dc1f32 100644 --- a/packages/transcode/src/activities/transcode.ts +++ b/packages/transcode/src/activities/transcode.ts @@ -94,19 +94,43 @@ async function ensureAssetNotPurging(assetKey: string): Promise { } export const getMediaInfoActivity = defineStep(async function getMediaInfoActivity(params: { - filePath: string + filePath?: string + assetKey?: string assetId: string proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null mediaType?: string }): Promise { + let tempLocalDir: string | undefined try { const proxyType = - params.proxyType || getProxyType(params.mediaType, params.filePath) || undefined + params.proxyType || + getProxyType(params.mediaType, params.filePath || params.assetKey) || + undefined const isVideo = proxyType === 'video' const isImage = proxyType === 'image' const isAudio = proxyType === 'audio' const isPdf = proxyType === 'pdf' + const bucket = process.env.S3_BUCKET || 'shumai' + let mediaSource = params.filePath + if (!mediaSource) { + if (params.assetKey) { + if (isVideo || isAudio) { + mediaSource = await s3Service.resolveInput(bucket, params.assetKey) + } else { + tempLocalDir = transcodeService.createTempDir('mediainfo-') + const ext = path.extname(params.assetKey) || (isImage ? '.jpg' : isPdf ? '.pdf' : '') + const localTarget = path.join(tempLocalDir, `input${ext}`) + mediaSource = await ensureLocalMediaFile(params.assetKey, localTarget) + } + } else { + throw ApplicationFailure.create({ + message: 'Neither filePath nor assetKey provided to getMediaInfoActivity', + nonRetryable: true, + }) + } + } + const fileType = isVideo ? 'video' : isAudio @@ -145,11 +169,11 @@ export const getMediaInfoActivity = defineStep(async function getMediaInfoActivi let isDowngradedToAudio = false let videoInfo: Awaited> | null = null try { - videoInfo = await transcodeService.getVideoInfo(params.filePath) + videoInfo = await transcodeService.getVideoInfo(mediaSource) } catch (err) { if (err instanceof Error && err.message.includes('No video stream found')) { try { - const audioInfo = await transcodeService.getAudioInfo(params.filePath) + const audioInfo = await transcodeService.getAudioInfo(mediaSource) isDowngradedToAudio = true mediaInfo.proxyType = 'audio' mediaInfo.duration = audioInfo.duration @@ -247,7 +271,7 @@ export const getMediaInfoActivity = defineStep(async function getMediaInfoActivi metadataUpdates.push({ key: 'audio_bit_depth', value: info.audioBitDepth }) } } else if (isAudio) { - const info = await transcodeService.getAudioInfo(params.filePath) + const info = await transcodeService.getAudioInfo(mediaSource) mediaInfo.duration = info.duration mediaInfo.metadata = { originalWidth: 0, @@ -278,7 +302,7 @@ export const getMediaInfoActivity = defineStep(async function getMediaInfoActivi if (info.audioBitDepth !== undefined) metadataUpdates.push({ key: 'audio_bit_depth', value: info.audioBitDepth }) } else if (isImage) { - const info = await transcodeService.getImageInfo(params.filePath) + const info = await transcodeService.getImageInfo(mediaSource) mediaInfo.metadata = { originalWidth: info.originalWidth, originalHeight: info.originalHeight, @@ -295,7 +319,7 @@ export const getMediaInfoActivity = defineStep(async function getMediaInfoActivi { key: 'resolution_height', value: info.originalHeight }, ) } else if (isPdf) { - const info = await transcodeService.getPdfInfo(params.filePath) + const info = await transcodeService.getPdfInfo(mediaSource) mediaInfo.frames = info.totalFrames mediaInfo.metadata = { originalWidth: info.originalWidth, @@ -328,6 +352,14 @@ export const getMediaInfoActivity = defineStep(async function getMediaInfoActivi nonRetryable: true, cause: err instanceof Error ? err : undefined, }) + } finally { + if (tempLocalDir) { + try { + fs.rmSync(tempLocalDir, { recursive: true, force: true }) + } catch { + // ignore cleanup error + } + } } }) diff --git a/packages/transcode/src/workflows/transcode-video.test.ts b/packages/transcode/src/workflows/transcode-video.test.ts index 037d8b42..028a0906 100644 --- a/packages/transcode/src/workflows/transcode-video.test.ts +++ b/packages/transcode/src/workflows/transcode-video.test.ts @@ -156,6 +156,16 @@ describe('transcodeVideoWorkflow', () => { }), }), }) + expect(mockActivities.getMediaInfoActivity).toHaveBeenCalledWith({ + assetKey: 'video.mp4', + assetId: 'asset-1', + proxyType: 'video', + mediaType: 'video/mp4', + }) + const getMediaInfoOrder = mockActivities.getMediaInfoActivity.mock.invocationCallOrder[0] + const downloadOrder = mockActivities.downloadMediaToTmpActivity.mock.invocationCallOrder[0] + expect(getMediaInfoOrder).toBeLessThan(downloadOrder) + expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({ assetId: 'asset-1', status: AssetStatus.processed, diff --git a/packages/transcode/src/workflows/transcode-video.ts b/packages/transcode/src/workflows/transcode-video.ts index 4ac42f46..d4153e76 100644 --- a/packages/transcode/src/workflows/transcode-video.ts +++ b/packages/transcode/src/workflows/transcode-video.ts @@ -35,16 +35,10 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise const { asset, key } = await fetchAssetWithKey(task.assetId) - const download = await downloadMediaToTmpActivity({ - assetKey: key, - }) - const { filePath } = download - tmpDir = download.tmpDir - const spec = task.payload?.transcode || {} const proxyType = asset.mediaType?.startsWith('audio/') ? 'audio' : 'video' const mediaInfo = await getMediaInfoActivity({ - filePath, + assetKey: key, assetId: asset.id, proxyType, mediaType: asset.mediaType || '', @@ -80,6 +74,12 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise }) } + const download = await downloadMediaToTmpActivity({ + assetKey: key, + }) + const { filePath } = download + tmpDir = download.tmpDir + // Generate the sprite (and its poster fallback) before the expensive proxy transcodes so the // file list can show a poster/sprite preview while the asset is still processing. if ((spec.sprite || (spec.poster && !mediaInfo.poster)) && isVideo) { diff --git a/packages/workflow-core/src/activities/task.ts b/packages/workflow-core/src/activities/task.ts index 189c3ff5..e99165fa 100644 --- a/packages/workflow-core/src/activities/task.ts +++ b/packages/workflow-core/src/activities/task.ts @@ -68,7 +68,7 @@ export const updateTaskStatusActivity = defineStep( where: { id: params.taskId }, data: { status: params.status, - output: params.output as Prisma.InputJsonValue, + output: params.output as PrismaJson.WorkflowTaskOutput, }, }) }, @@ -152,7 +152,9 @@ export const updateWorkflowTaskActivity = defineStep( data: { ...(params.status !== undefined ? { status: params.status } : {}), ...(params.heartbeat ? { heartbeat: new Date() } : {}), - ...(params.output !== undefined ? { output: params.output as Prisma.InputJsonValue } : {}), + ...(params.output !== undefined + ? { output: params.output as PrismaJson.WorkflowTaskOutput } + : {}), ...(params.inputTokens !== undefined ? { inputTokens: params.inputTokens } : {}), ...(params.outputTokens !== undefined ? { outputTokens: params.outputTokens } : {}), ...(params.model !== undefined ? { model: params.model } : {}), diff --git a/packages/workflow-core/src/dbos-executor.test.ts b/packages/workflow-core/src/dbos-executor.test.ts index 1caa360e..2fab9f29 100644 --- a/packages/workflow-core/src/dbos-executor.test.ts +++ b/packages/workflow-core/src/dbos-executor.test.ts @@ -133,18 +133,8 @@ describe('DbosExecutor Tests', () => { }) it('should only update queues the worker listens to or configures, leaving unmanaged queues untouched', async () => { - // Step 1: Agent worker sets agent concurrency to 1 - process.env.CONCURRENCY_AGENT = '1' - const agentWorker = new DbosExecutor([TaskQueueAgent]) - agentWorker.start() - await agentWorker.ensureLaunched() + const registerQueueSpy = vi.spyOn(DBOS, 'registerQueue') - const agentQueue = await DBOS.retrieveQueue(TaskQueueAgent) - expect(agentQueue?.workerConcurrency).toBe(1) - await agentWorker.shutdown() - - // Step 2: Dedicated transcode worker starts with transcode concurrency = 3 and unconfigured agent env - delete process.env.CONCURRENCY_AGENT process.env.CONCURRENCY_TRANSCODE = '3' const transcodeWorker = new DbosExecutor([TaskQueueTranscode]) try { @@ -152,12 +142,15 @@ describe('DbosExecutor Tests', () => { await transcodeWorker.ensureLaunched() const transcodeQueue = await DBOS.retrieveQueue(TaskQueueTranscode) - const agentQueueAfter = await DBOS.retrieveQueue(TaskQueueAgent) - expect(transcodeQueue?.workerConcurrency).toBe(3) - // Agent queue should still be 1, NOT overwritten by default 5 - expect(agentQueueAfter?.workerConcurrency).toBe(1) + + // transcodeWorker should only have registered TaskQueueTranscode, not unmanaged queues like TaskQueueAgent + const registeredQueueNames = registerQueueSpy.mock.calls.map((call) => call[0]) + expect(registeredQueueNames).toContain(TaskQueueTranscode) + expect(registeredQueueNames).not.toContain(TaskQueueAgent) } finally { + registerQueueSpy.mockRestore() + delete process.env.CONCURRENCY_TRANSCODE await transcodeWorker.shutdown() } }) @@ -390,4 +383,95 @@ describe('DbosExecutor Tests', () => { expect(mockClient.enqueue).toHaveBeenCalled() }, 15000) }) + + describe('Once mode, events, and conflict handling', () => { + it('should force concurrency to 1 in onceMode', () => { + executor.setOnceMode(true) + expect(executor.isOnceMode()).toBe(true) + expect(executor.getTranscodeConcurrencyLimit()).toBe(1) + }) + + it('should emit workflowStarted and workflowFinished events during execution', async () => { + let startedTask: WorkflowTask | null = null + let finishedPayload: { taskId: string; success: boolean } | null = null + + executor.on('workflowStarted', (task) => { + startedTask = task + }) + executor.on('workflowFinished', (payload) => { + finishedPayload = payload + }) + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const wrapper = (executor as any).createDbosWorkflowWrapper('test-events-workflow') + const { registerWorkflow } = await import('./dbos-executor') + registerWorkflow('test-events-workflow', async () => { + // do work + }) + + const task = await prisma.workflowTask.create({ + data: { + id: 'test-events-task', + assetId: 'asset-events', + type: WorkflowTaskType.transcode, + status: WorkflowTaskStatus.pending, + }, + }) + + await wrapper(task) + + expect(startedTask).toBeDefined() + expect((startedTask as WorkflowTask | null)?.id).toBe('test-events-task') + expect(finishedPayload).toBeDefined() + expect((finishedPayload as { taskId: string; success: boolean } | null)?.taskId).toBe( + 'test-events-task', + ) + expect((finishedPayload as { taskId: string; success: boolean } | null)?.success).toBe(true) + }) + + it('should handle DBOSWorkflowConflictError without marking task failed', async () => { + const { DBOSWorkflowConflictError: DbosWorkflowConflictError } = + await import('@dbos-inc/dbos-sdk') + const { registerWorkflow } = await import('./dbos-executor') + + registerWorkflow('test-conflict-workflow', async () => { + throw new DbosWorkflowConflictError('test-conflict-task') + }) + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const wrapper = (executor as any).createDbosWorkflowWrapper('test-conflict-workflow') + + const task = await prisma.workflowTask.create({ + data: { + id: 'test-conflict-task', + assetId: 'asset-conflict', + type: WorkflowTaskType.transcode, + status: WorkflowTaskStatus.pending, + }, + }) + + await expect(wrapper(task)).rejects.toThrow('is no longer owned by this execution') + + const updatedTask = await prisma.workflowTask.findUnique({ + where: { id: 'test-conflict-task' }, + }) + // Task should NOT be marked as failed! + expect(updatedTask?.status).not.toBe(WorkflowTaskStatus.failed) + }) + + it('should pass workflowCompletionTimeoutMs to DBOS.shutdown', async () => { + const shutdownSpy = vi.spyOn(DBOS, 'shutdown').mockResolvedValue(undefined) + const isInitSpy = vi.spyOn(DBOS, 'isInitialized').mockReturnValue(true) + + await executor.shutdown({ workflowCompletionTimeoutMs: 290000 }) + + expect(shutdownSpy).toHaveBeenCalledWith({ + // eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS SDK parameter name + workflowCompletionTimeoutMS: 290000, + }) + + shutdownSpy.mockRestore() + isInitSpy.mockRestore() + }) + }) }) diff --git a/packages/workflow-core/src/dbos-executor.ts b/packages/workflow-core/src/dbos-executor.ts index dc532e70..0f45885a 100644 --- a/packages/workflow-core/src/dbos-executor.ts +++ b/packages/workflow-core/src/dbos-executor.ts @@ -1,5 +1,6 @@ +import EventEmitter from 'node:events' import os from 'node:os' -import { DBOS, DBOSClient } from '@dbos-inc/dbos-sdk' +import { DBOS, DBOSClient, DBOSWorkflowConflictError } from '@dbos-inc/dbos-sdk' import { logger } from '@shumai/core/src/logger' import { prisma, WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db' import { @@ -12,6 +13,22 @@ import { unregisterLocalTaskAbortController, } from './workflow-utils' +export function isWorkflowConflictError(err: unknown): boolean { + if (err instanceof DBOSWorkflowConflictError) return true + if ( + err && + typeof err === 'object' && + 'dbosErrorCode' in err && + (err as { dbosErrorCode: unknown }).dbosErrorCode === 5 + ) { + return true + } + if (err instanceof Error && err.message.includes('is no longer owned by this execution')) { + return true + } + return false +} + export type WorkflowFn = (task: WorkflowTask) => Promise const workflowRegistry = new Map() @@ -63,7 +80,7 @@ export function getQueueForTaskType(type: string | null | undefined): string { let dbosMigrationsRan = false const registeredDbosWorkflowNames = new Set() -export class DbosExecutor { +export class DbosExecutor extends EventEmitter { private launchPromise: Promise | null = null private started = false private client: DBOSClient | null = null @@ -72,8 +89,10 @@ export class DbosExecutor { private inFlightSubmits = new Set>() private executorId?: string private instanceSuffix = Math.random().toString(36).slice(2, 8) + private onceMode = false constructor(listenQueues?: string[], executorId?: string) { + super() if (listenQueues) { this.listenQueues = listenQueues } @@ -82,6 +101,14 @@ export class DbosExecutor { } } + setOnceMode(once: boolean): void { + this.onceMode = once + } + + isOnceMode(): boolean { + return this.onceMode + } + isStarted(): boolean { return this.started } @@ -91,6 +118,7 @@ export class DbosExecutor { } getTranscodeConcurrencyLimit(): number { + if (this.onceMode) return 1 return getConcurrencyLimit(process.env.CONCURRENCY_TRANSCODE, 1) } @@ -116,6 +144,7 @@ export class DbosExecutor { if (!fn) { throw new Error(`No workflow registered for type: ${type}`) } + this.emit('workflowStarted', task) // Mark task as processing and start heartbeat try { await prisma.workflowTask.updateMany({ @@ -151,11 +180,20 @@ export class DbosExecutor { const abortController = new AbortController() registerLocalTaskAbortController(task.id, abortController) + let workflowError: unknown try { await runInLocalTaskContext({ taskId: task.id, abortController }, async () => { await fn(task) }) } catch (err) { + workflowError = err + if (isWorkflowConflictError(err)) { + logger.warn( + { taskId: task.id, type, err }, + '[DbosExecutor] Workflow execution superseded (ownership lost or conflict). Skipping marking task as failed.', + ) + throw err + } logger.error({ taskId: task.id, type, err }, `[DbosExecutor] Error in workflow ${type}`) try { await prisma.workflowTask.updateMany({ @@ -176,6 +214,12 @@ export class DbosExecutor { clearInterval(heartbeatInterval) this.heartbeatIntervals.delete(task.id) unregisterLocalTaskAbortController(task.id) + this.emit('workflowFinished', { + taskId: task.id, + type, + success: !workflowError, + error: workflowError, + }) } } } @@ -366,14 +410,17 @@ export class DbosExecutor { close(): void { this.started = false this.waitForPendingSubmissions().catch(() => {}) - for (const timer of this.heartbeatIntervals.values()) { - clearInterval(timer) - } - this.heartbeatIntervals.clear() - if (this.client) { - this.client.destroy().catch(() => {}) - this.client = null + const cleanupResources = () => { + for (const timer of this.heartbeatIntervals.values()) { + clearInterval(timer) + } + this.heartbeatIntervals.clear() + if (this.client) { + this.client.destroy().catch(() => {}) + this.client = null + } } + if (DBOS.isInitialized()) { DBOS.shutdown() .then(() => { @@ -382,23 +429,43 @@ export class DbosExecutor { .catch((err) => { logger.warn({ err }, '[DbosExecutor] Error during DBOS shutdown') }) + .finally(cleanupResources) + } else { + cleanupResources() } } - async shutdown(): Promise { + async shutdown(options?: { workflowCompletionTimeoutMs?: number }): Promise { this.started = false await this.waitForPendingSubmissions() - for (const timer of this.heartbeatIntervals.values()) { - clearInterval(timer) - } - this.heartbeatIntervals.clear() - if (this.client) { - await this.client.destroy().catch(() => {}) - this.client = null - } - if (DBOS.isInitialized()) { - await DBOS.shutdown() - this.launchPromise = null + + const timeoutMs = + options?.workflowCompletionTimeoutMs ?? + (process.env.SHUMAI_WORKER_DRAIN_TIMEOUT_MS + ? parseInt(process.env.SHUMAI_WORKER_DRAIN_TIMEOUT_MS, 10) + : undefined) + + try { + if (DBOS.isInitialized()) { + await DBOS.shutdown( + timeoutMs !== undefined + ? { + // eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS SDK parameter name + workflowCompletionTimeoutMS: timeoutMs, + } + : undefined, + ) + this.launchPromise = null + } + } finally { + for (const timer of this.heartbeatIntervals.values()) { + clearInterval(timer) + } + this.heartbeatIntervals.clear() + if (this.client) { + await this.client.destroy().catch(() => {}) + this.client = null + } } } } diff --git a/packages/workflow-core/src/workflow.test.ts b/packages/workflow-core/src/workflow.test.ts index 9d8e3132..71f958c2 100644 --- a/packages/workflow-core/src/workflow.test.ts +++ b/packages/workflow-core/src/workflow.test.ts @@ -188,4 +188,144 @@ describe('WorkflowService', () => { submitSpy.mockRestore() }) + + describe('Stale Task Recovery', () => { + it('should resume stale pending workflow task in DBOS and increment recoveryAttempts', async () => { + const task = await prisma.workflowTask.create({ + data: { + assetId: 'stale-asset-1', + type: WorkflowTaskType.transcode, + status: WorkflowTaskStatus.processing, + heartbeat: new Date(Date.now() - 100_000), // 100s ago + }, + }) + + const mockClient = { + retrieveWorkflow: vi.fn().mockReturnValue({ + getStatus: vi.fn().mockResolvedValue({ status: 'PENDING' }), + }), + resumeWorkflow: vi.fn().mockResolvedValue(undefined), + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.spyOn(workflowService.getExecutor(), 'getClient').mockResolvedValue(mockClient as any) + + const recoveredCount = await workflowService.recoverStaleTasks({ + staleThresholdMs: 90_000, + maxRecoveryAttempts: 3, + }) + + expect(recoveredCount).toBe(1) + expect(mockClient.resumeWorkflow).toHaveBeenCalledWith( + task.id, + expect.objectContaining({ queueName: expect.any(String) }), + ) + + const updatedTask = await prisma.workflowTask.findUnique({ + where: { id: task.id }, + }) + const output = updatedTask?.output as { recoveryAttempts?: number } | null + expect(output?.recoveryAttempts).toBe(1) + expect(updatedTask?.heartbeat?.getTime()).toBeGreaterThan(Date.now() - 5000) + }) + + it('should mark task and asset as failed when recoveryAttempts exceeds maxRecoveryAttempts', async () => { + const asset = await prisma.asset.create({ + data: { + id: 'poison-asset-1', + name: 'poison.mp4', + type: 'file', + status: 'processing', + }, + }) + + const task = await prisma.workflowTask.create({ + data: { + assetId: asset.id, + type: WorkflowTaskType.transcode, + status: WorkflowTaskStatus.processing, + heartbeat: new Date(Date.now() - 100_000), + output: { recoveryAttempts: 3 }, + }, + }) + + const mockClient = { + retrieveWorkflow: vi.fn(), + resumeWorkflow: vi.fn(), + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.spyOn(workflowService.getExecutor(), 'getClient').mockResolvedValue(mockClient as any) + + const recoveredCount = await workflowService.recoverStaleTasks({ + staleThresholdMs: 90_000, + maxRecoveryAttempts: 3, + }) + + expect(recoveredCount).toBe(1) + expect(mockClient.resumeWorkflow).not.toHaveBeenCalled() + + const updatedTask = await prisma.workflowTask.findUnique({ + where: { id: task.id }, + }) + expect(updatedTask?.status).toBe(WorkflowTaskStatus.failed) + const output = updatedTask?.output as { error?: string; recoveryAttempts?: number } | null + expect(output?.recoveryAttempts).toBe(4) + expect(output?.error).toContain('exceeded maximum stale recovery attempts') + + const updatedAsset = await prisma.asset.findUnique({ + where: { id: asset.id }, + }) + expect(updatedAsset?.status).toBe('failed') + }) + + it('should reconcile completed or cancelled DBOS workflow status', async () => { + const taskSuccess = await prisma.workflowTask.create({ + data: { + assetId: 'stale-asset-success', + type: WorkflowTaskType.transcode, + status: WorkflowTaskStatus.processing, + heartbeat: new Date(Date.now() - 100_000), + }, + }) + + const taskCancelled = await prisma.workflowTask.create({ + data: { + assetId: 'stale-asset-cancelled', + type: WorkflowTaskType.transcode, + status: WorkflowTaskStatus.processing, + heartbeat: new Date(Date.now() - 100_000), + }, + }) + + const mockClient = { + retrieveWorkflow: vi.fn().mockImplementation((taskId: string) => ({ + getStatus: vi.fn().mockResolvedValue({ + status: taskId === taskSuccess.id ? 'SUCCESS' : 'CANCELLED', + }), + })), + resumeWorkflow: vi.fn(), + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.spyOn(workflowService.getExecutor(), 'getClient').mockResolvedValue(mockClient as any) + + const count = await workflowService.recoverStaleTasks({ + staleThresholdMs: 90_000, + maxRecoveryAttempts: 3, + }) + + expect(count).toBe(2) + expect(mockClient.resumeWorkflow).not.toHaveBeenCalled() + + const updatedSuccess = await prisma.workflowTask.findUnique({ + where: { id: taskSuccess.id }, + }) + expect(updatedSuccess?.status).toBe(WorkflowTaskStatus.completed) + + const updatedCancelled = await prisma.workflowTask.findUnique({ + where: { id: taskCancelled.id }, + }) + expect(updatedCancelled?.status).toBe(WorkflowTaskStatus.failed) + const cancelledOutput = updatedCancelled?.output as { error?: string } | null + expect(cancelledOutput?.error).toBe('Workflow was cancelled') + }) + }) }) diff --git a/packages/workflow-core/src/workflow.ts b/packages/workflow-core/src/workflow.ts index 56c87502..5be41799 100644 --- a/packages/workflow-core/src/workflow.ts +++ b/packages/workflow-core/src/workflow.ts @@ -1,8 +1,17 @@ -import { prisma, registerWorkflowCancel, registerWorkflowTrigger, WorkflowTask } from '@shumai/db' -import { DbosExecutor, getRegisteredWorkflows } from './dbos-executor' +import { logger } from '@shumai/core/src/logger' +import { + AssetStatus, + prisma, + registerWorkflowCancel, + registerWorkflowTrigger, + WorkflowTask, + WorkflowTaskStatus, +} from '@shumai/db' +import { DbosExecutor, getQueueForTaskType, getRegisteredWorkflows } from './dbos-executor' export class WorkflowService { private executor: DbosExecutor + private staleRecoveryTimer: Timer | null = null constructor() { this.executor = new DbosExecutor() @@ -55,6 +64,7 @@ export class WorkflowService { } close(): void { + this.stopStaleTaskRecovery() this.executor.close() } @@ -62,8 +72,9 @@ export class WorkflowService { await this.executor.ensureLaunched() } - async shutdownWorkers(): Promise { - await this.executor.shutdown() + async shutdownWorkers(options?: { workflowCompletionTimeoutMs?: number }): Promise { + this.stopStaleTaskRecovery() + await this.executor.shutdown(options) } isStarted(): boolean { @@ -82,6 +93,152 @@ export class WorkflowService { this.executor.start() await this.executor.ensureLaunched() } + + startStaleTaskRecovery(options?: { + intervalMs?: number + staleThresholdMs?: number + maxRecoveryAttempts?: number + }): void { + if (this.staleRecoveryTimer) { + return + } + const intervalMs = options?.intervalMs ?? 30_000 + this.staleRecoveryTimer = setInterval(() => { + this.recoverStaleTasks(options).catch((err) => { + logger.error({ err }, '[WorkflowService] Stale task recovery sweep encountered an error') + }) + }, intervalMs) + } + + stopStaleTaskRecovery(): void { + if (this.staleRecoveryTimer) { + clearInterval(this.staleRecoveryTimer) + this.staleRecoveryTimer = null + } + } + + async recoverStaleTasks(options?: { + staleThresholdMs?: number + maxRecoveryAttempts?: number + }): Promise { + const staleThresholdMs = options?.staleThresholdMs ?? 90_000 + const maxRecoveryAttempts = options?.maxRecoveryAttempts ?? 3 + const cutoff = new Date(Date.now() - staleThresholdMs) + + const staleTasks = await prisma.workflowTask.findMany({ + where: { + status: WorkflowTaskStatus.processing, + heartbeat: { lt: cutoff }, + }, + }) + + if (staleTasks.length === 0) return 0 + + let recoveredCount = 0 + const client = await this.executor.getClient() + + for (const task of staleTasks) { + try { + const currentTask = await prisma.workflowTask.findUnique({ + where: { id: task.id }, + }) + if ( + !currentTask || + currentTask.status !== WorkflowTaskStatus.processing || + (currentTask.heartbeat && + currentTask.heartbeat.getTime() >= Date.now() - staleThresholdMs) + ) { + continue + } + + const output = (currentTask.output as PrismaJson.WorkflowTaskOutput | null) || {} + const recoveryAttempts = (output.recoveryAttempts ?? 0) + 1 + + if (recoveryAttempts > maxRecoveryAttempts) { + logger.error( + { taskId: task.id, recoveryAttempts, maxRecoveryAttempts }, + '[WorkflowService] Stale task exceeded max recovery attempts. Marking as failed.', + ) + await prisma.workflowTask.update({ + where: { id: task.id }, + data: { + status: WorkflowTaskStatus.failed, + output: { + ...output, + recoveryAttempts, + error: `Task exceeded maximum stale recovery attempts (${maxRecoveryAttempts}). Marked as failed.`, + }, + }, + }) + if (task.assetId && task.type && task.type.startsWith('transcode')) { + await prisma.asset.updateMany({ + where: { id: task.assetId, status: AssetStatus.processing }, + data: { status: AssetStatus.failed }, + }) + } + recoveredCount++ + continue + } + + const handle = client.retrieveWorkflow(task.id) + const wfStatus = await handle.getStatus().catch(() => null) + + if (wfStatus?.status === 'PENDING') { + await prisma.workflowTask.update({ + where: { id: task.id }, + data: { + heartbeat: new Date(), + output: { + ...output, + recoveryAttempts, + }, + }, + }) + const queueName = getQueueForTaskType(task.type) + await client.resumeWorkflow(task.id, { queueName }) + logger.info( + { taskId: task.id, queueName, recoveryAttempts }, + '[WorkflowService] Resumed stale pending workflow task in DBOS', + ) + recoveredCount++ + } else if (wfStatus?.status === 'SUCCESS') { + await prisma.workflowTask.update({ + where: { id: task.id }, + data: { status: WorkflowTaskStatus.completed }, + }) + recoveredCount++ + } else if (wfStatus?.status === 'ERROR') { + await prisma.workflowTask.update({ + where: { id: task.id }, + data: { + status: WorkflowTaskStatus.failed, + output: { + ...output, + error: wfStatus.error ? String(wfStatus.error) : 'Workflow failed in DBOS', + }, + }, + }) + recoveredCount++ + } else if (wfStatus?.status === 'CANCELLED') { + await prisma.workflowTask.update({ + where: { id: task.id }, + data: { + status: WorkflowTaskStatus.failed, + output: { + ...output, + error: 'Workflow was cancelled', + }, + }, + }) + recoveredCount++ + } + } catch (err) { + logger.warn({ taskId: task.id, err }, '[WorkflowService] Error while checking stale task') + } + } + + return recoveredCount + } } export const workflowService = new WorkflowService()