refactor(transcode): offload video embedding chunk slicing to transcode queue (#539)

* refactor(transcode): offload video embedding chunk slicing to transcode queue

* fix(transcode): address video chunk offloading review findings
This commit is contained in:
Yiling-J
2026-11-22 11:52:58 +08:00
committed by GitHub
parent 3943407093
commit aabf59cbe7
23 changed files with 1226 additions and 434 deletions
+334 -121
View File
@@ -1,37 +1,25 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import {
generateTextEmbeddingActivity,
extractAiMetadataActivity,
getEmbeddingContextActivity,
saveAssetEmbeddingsActivity,
deleteAssetEmbeddingsActivity,
generateImageEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
getGemmaEmbeddingTargetFrameCount,
transcodeVideoChunksActivity,
} from './ai'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core'
import { prisma, AssetType, AssetStatus } from '@shumai/db'
import { prisma, AssetType, AssetStatus, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import {
DBOSError,
registerLocalTaskAbortController,
unregisterLocalTaskAbortController,
workflowService,
} from '@shumai/workflow-core'
import sharp from 'sharp'
vi.mock('fs', async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- importOriginal returns the raw fs module, typed dynamically as any here
const actual = await importOriginal<any>()
const mockRead = vi.fn((path, options) => {
if (typeof path === 'string' && (path.includes('video-chunk') || path.includes('out1.webp'))) {
return Buffer.from('chunk-data')
}
return actual.readFileSync(path, options)
})
return {
...actual,
writeFileSync: vi.fn(),
readFileSync: mockRead,
unlinkSync: vi.fn(),
}
})
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
@@ -39,35 +27,11 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
headObject: vi.fn(),
listObjects: vi.fn(),
downloadToFile: vi.fn(),
deleteObject: vi.fn(),
resolveInput: vi.fn().mockImplementation(async (_bucket, key) => `https://mock-storage/${key}`),
},
}))
vi.mock('@shumai/core/src/transcode/transcode', () => ({
transcodeService: {
extractVideoFrames: vi.fn(),
createTempDir: vi.fn().mockReturnValue('/tmp'),
removeDir: vi.fn(),
},
}))
vi.mock('child_process', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls
const execFileMock: any = vi.fn((file: any, args: any, cb: any) => {
cb(null, '120.0\n', '')
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls
execFileMock[Symbol.for('nodejs.util.promisify.custom')] = vi.fn(async (file: any) => {
if (file === 'ffprobe') {
return { stdout: '120.0\n', stderr: '' }
}
return { stdout: '', stderr: '' }
})
return {
execFile: execFileMock,
}
})
const mockEmbedContent = vi.fn().mockResolvedValue({
embeddings: [
{
@@ -503,82 +467,6 @@ describe('AI Activities Unit Tests', () => {
}),
).rejects.toThrow('is empty (0 bytes)')
})
describe('extractAiMetadataActivity', () => {
it('should return existing images if they are already in S3 storage', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock returned object cast as any due to partial implementation
vi.mocked(s3Service.headObject).mockResolvedValue({} as any)
vi.mocked(s3Service.listObjects).mockResolvedValue([
'project/ai_metadata/1.webp',
'project/ai_metadata/2.webp',
])
const res = await extractAiMetadataActivity({
assetKey: 'project/video.mp4',
filePath: '/tmp/video.mp4',
type: 'autofill',
isImage: false,
})
expect(res).toEqual(['project/ai_metadata/1.webp', 'project/ai_metadata/2.webp'])
expect(s3Service.headObject).toHaveBeenCalledWith('shumai', 'project/ai_metadata/1.webp')
expect(transcodeService.extractVideoFrames).not.toHaveBeenCalled()
})
it('should extract frames and upload to S3 if not already present', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not Found'))
vi.mocked(transcodeService.extractVideoFrames).mockResolvedValue(['/tmp/out1.webp'])
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock returned object cast as any due to partial implementation
vi.mocked(s3Service.putObject).mockResolvedValue({} as any)
const res = await extractAiMetadataActivity({
assetKey: 'project/video.mp4',
filePath: '/tmp/video.mp4',
type: 'autofill',
isImage: false,
})
expect(res).toEqual(['project/ai_metadata/out1.webp'])
expect(transcodeService.extractVideoFrames).toHaveBeenCalledWith({
inputFile: '/tmp/video.mp4',
outputDir: '/tmp',
numFrames: 30,
frameHeight: 720,
isImage: false,
})
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
'project/ai_metadata/out1.webp',
expect.any(Buffer),
expect.any(Number),
'image/webp',
)
})
it('should resolveInput from s3Service when filePath is not provided', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not Found'))
vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-storage/project/video.mp4')
vi.mocked(transcodeService.extractVideoFrames).mockResolvedValue(['/tmp/out1.webp'])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(s3Service.putObject).mockResolvedValue({} as any)
const res = await extractAiMetadataActivity({
assetKey: 'project/video.mp4',
type: 'autofill',
isImage: false,
})
expect(res).toEqual(['project/ai_metadata/out1.webp'])
expect(s3Service.resolveInput).toHaveBeenCalledWith('shumai', 'project/video.mp4')
expect(transcodeService.extractVideoFrames).toHaveBeenCalledWith({
inputFile: 'https://mock-storage/project/video.mp4',
outputDir: expect.any(String),
numFrames: 30,
frameHeight: 720,
isImage: false,
})
})
})
})
describe('AI Database Activities Integration', () => {
@@ -887,4 +775,329 @@ describe('AI Database Activities Integration', () => {
expect(after).toHaveLength(0)
})
})
describe('transcodeVideoChunksActivity', () => {
afterEach(() => {
delete process.env.EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS
})
it('should create a transcode_video_chunks WorkflowTask and await completion', async () => {
const waitForSpy = vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
],
},
},
}))
const res = await transcodeVideoChunksActivity({
parentTaskId: 'parent-123',
teamId: team.id,
projectId: 'proj-123',
assetId: asset.id,
assetKey: 'media/video.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
})
expect(res.chunks).toEqual([
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
])
expect(waitForSpy).toHaveBeenCalledTimes(1)
expect(waitForSpy).toHaveBeenCalledWith(
expect.objectContaining({
assetId: asset.id,
type: WorkflowTaskType.transcode_video_chunks,
}),
60 * 60 * 1000,
)
const createdTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video_chunks },
})
expect(createdTask).toBeDefined()
expect(createdTask?.payload?.videoChunks).toEqual({
parentTaskId: 'parent-123',
assetKey: 'media/video.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
})
})
it('should honor custom EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS env var', async () => {
process.env.EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS = '12345'
const waitForSpy = vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
],
},
},
}))
await transcodeVideoChunksActivity({
parentTaskId: 'parent-timeout-env',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
})
expect(waitForSpy).toHaveBeenCalledWith(expect.anything(), 12345)
})
it('should reuse an existing transcode_video_chunks task with the same parentTaskId on retry', async () => {
const existingChild = await prisma.workflowTask.create({
data: {
assetId: asset.id,
teamId: team.id,
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.processing,
payload: {
projectId: '',
videoChunks: {
parentTaskId: 'parent-retry-1',
assetKey: 'media/video.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
},
},
},
})
const waitForSpy = vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
],
},
},
}))
await transcodeVideoChunksActivity({
parentTaskId: 'parent-retry-1',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
})
expect(waitForSpy).toHaveBeenCalledWith(
expect.objectContaining({ id: existingChild.id }),
expect.any(Number),
)
const count = await prisma.workflowTask.count({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video_chunks },
})
expect(count).toBe(1)
})
it('should return empty chunks immediately when chunks array is empty', async () => {
const waitForSpy = vi.spyOn(workflowService, 'waitFor')
const res = await transcodeVideoChunksActivity({
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [],
})
expect(res.chunks).toEqual([])
expect(waitForSpy).not.toHaveBeenCalled()
})
it('should throw non-retryable ApplicationFailure when assetKey is empty', async () => {
await expect(
transcodeVideoChunksActivity({
assetId: asset.id,
assetKey: '',
chunks: [{ startTime: 0, endTime: 60 }],
}),
).rejects.toThrow('assetKey is required for video chunks transcoding')
})
it('should wrap child task failure as non-retryable ApplicationFailure to avoid duplicate child tasks', async () => {
vi.spyOn(workflowService, 'waitFor').mockRejectedValue(
new Error(
'Original video file is archived and no proxy is available. Restore the asset to generate embeddings.',
),
)
expect.assertions(2)
try {
await transcodeVideoChunksActivity({
parentTaskId: 'parent-child-fail',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('Original video file is archived')
}
})
it('should cancel child task and throw non-retryable ApplicationFailure on timeout', async () => {
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: false,
task,
}))
expect.assertions(4)
try {
await transcodeVideoChunksActivity({
parentTaskId: 'parent-timeout-fail',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('timed out')
}
const childTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video_chunks },
})
expect(cancelSpy).toHaveBeenCalledWith(childTask!.id)
expect(childTask?.status).toBe(WorkflowTaskStatus.failed)
})
it('should throw non-retryable ApplicationFailure when completed child task has invalid chunks output', async () => {
vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {},
},
}))
expect.assertions(2)
try {
await transcodeVideoChunksActivity({
parentTaskId: 'parent-invalid-output',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('completed without valid chunks output')
}
})
it('should cancel child transcode_video_chunks task when parent workflow is cancelled', async () => {
const parentTaskId = 'parent-cancel-test'
const abortController = new AbortController()
registerLocalTaskAbortController(parentTaskId, abortController)
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
vi.spyOn(workflowService, 'waitFor').mockImplementation(async () => {
abortController.abort()
throw new DBOSError.DBOSWorkflowCancelledError(parentTaskId)
})
try {
await expect(
transcodeVideoChunksActivity({
parentTaskId,
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
}),
).rejects.toThrow()
const childTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video_chunks },
})
expect(childTask).toBeDefined()
expect(cancelSpy).toHaveBeenCalledWith(childTask!.id)
expect(childTask?.status).toBe(WorkflowTaskStatus.failed)
} finally {
unregisterLocalTaskAbortController(parentTaskId)
}
})
it('should clean up uploaded chunks from S3 if parent workflow is cancelled just as child completes', async () => {
const parentTaskId = 'parent-cancel-race'
const abortController = new AbortController()
registerLocalTaskAbortController(parentTaskId, abortController)
vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => {
abortController.abort()
return {
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
],
},
},
}
})
try {
await expect(
transcodeVideoChunksActivity({
parentTaskId,
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
}),
).rejects.toThrow('Parent embedding workflow was cancelled before transcode completed')
expect(s3Service.deleteObject).toHaveBeenCalledWith(
'shumai',
`files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
)
} finally {
unregisterLocalTaskAbortController(parentTaskId)
}
})
})
})
+156 -209
View File
@@ -1,18 +1,16 @@
import { GoogleGenAI } from '@google/genai'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import { execFile } from 'child_process'
import { promisify } from 'util'
import { ulid } from 'ulid'
import { ApplicationFailure, defineStep } from '@shumai/workflow-core'
import { prisma } from '@shumai/db'
import { textEmbeddingService } from '@shumai/core/src/search/text-embedding'
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import {
ApplicationFailure,
defineStep,
getLocalTaskAbortSignal,
isDbosWorkflowCancelledError,
workflowService,
} from '@shumai/workflow-core'
import sharp from 'sharp'
const execFileAsync = promisify(execFile)
export interface Usage {
inputTokens: number
outputTokens: number
@@ -111,8 +109,6 @@ async function callGemmaEmbeddingServer(input: string | OpenAiEmbeddingItem[]):
}
}
import { textEmbeddingService } from '@shumai/core/src/search/text-embedding'
export interface GenerateTextEmbeddingParams {
text: string
teamId: string
@@ -157,66 +153,6 @@ export const generateTextEmbeddingActivity = defineStep(
},
)
export interface ExtractAiMetadataParams {
assetKey: string
filePath?: string
type: 'autofill'
isImage: boolean
}
export const extractAiMetadataActivity = defineStep(async function extractAiMetadataActivity(
params: ExtractAiMetadataParams,
): Promise<string[]> {
const bucket = process.env.S3_BUCKET || 'shumai'
const assetDir = path.dirname(params.assetKey)
const aiDir = path.join(assetDir, 'ai_metadata')
const generatedFiles: string[] = []
let tmpDir = params.filePath ? path.dirname(params.filePath) : ''
let cleanupTmp = false
if (!tmpDir) {
tmpDir = transcodeService.createTempDir('ai-meta-')
cleanupTmp = true
}
try {
if (params.type === 'autofill') {
const targetKey = path.join(aiDir, '1.webp')
try {
await s3Service.headObject(bucket, targetKey)
const keys = await s3Service.listObjects(bucket, aiDir)
return keys.filter((k) => k.toLowerCase().endsWith('.webp'))
} catch {
// Not found
}
const inputSource = params.filePath || (await s3Service.resolveInput(bucket, params.assetKey))
const files = await transcodeService.extractVideoFrames({
inputFile: inputSource,
outputDir: tmpDir,
numFrames: 30,
frameHeight: 720,
isImage: params.isImage,
})
for (const file of files) {
const name = path.basename(file)
const buffer = fs.readFileSync(file)
const key = path.join(aiDir, name)
await s3Service.putObject(bucket, key, buffer, buffer.length, 'image/webp')
generatedFiles.push(key)
}
}
} finally {
if (cleanupTmp && tmpDir) {
transcodeService.removeDir(tmpDir)
}
}
return generatedFiles
})
export const getEmbeddingContextActivity = defineStep(
async function getEmbeddingContextActivity(params: { teamId: string; assetId: string }) {
const team = await prisma.team.findUnique({
@@ -569,168 +505,179 @@ export const generateVideoChunkEmbeddingActivity = defineStep(
},
)
export interface TranscodeVideoChunkParams {
assetId: string
assetKey?: string
filePath?: string
export interface VideoChunkRange {
startTime: number
endTime: number
format?: 'video' | 'frames'
}
export const transcodeVideoChunkActivity = defineStep(async function transcodeVideoChunkActivity(
params: TranscodeVideoChunkParams,
): Promise<{ chunkKey: string }> {
if (!params.filePath && !params.assetKey) {
export interface TranscodedVideoChunk extends VideoChunkRange {
chunkKey: string
}
export interface TranscodeVideoChunksParams {
parentTaskId?: string
teamId?: string | null
projectId?: string | null
assetId: string
assetKey: string
format?: 'video' | 'frames'
chunks: VideoChunkRange[]
}
const DEFAULT_TRANSCODE_WAIT_TIMEOUT_MS = 60 * 60 * 1000 // 60 minutes
function getTranscodeWaitTimeoutMs(): number {
const parsed = parseInt(process.env.EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS || '', 10)
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_TRANSCODE_WAIT_TIMEOUT_MS
}
async function cancelChildTranscodeTask(childTaskId: string): Promise<void> {
try {
await workflowService.cancel(childTaskId)
} catch {
// Ignore DBOS cancel errors during cleanup
}
try {
await prisma.workflowTask.updateMany({
where: {
id: childTaskId,
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: { error: 'Parent embedding workflow was cancelled' },
},
})
} catch {
// Ignore DB update errors during cleanup
}
}
export const transcodeVideoChunksActivity = defineStep(async function transcodeVideoChunksActivity(
params: TranscodeVideoChunksParams,
): Promise<{ chunks: TranscodedVideoChunk[] }> {
if (!params.assetKey) {
throw ApplicationFailure.create({
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
message: 'assetKey is required for video chunks transcoding',
nonRetryable: true,
})
}
if (params.format === 'frames') {
const tmpDir = transcodeService.createTempDir('video-chunk-frames-')
try {
const bucket = process.env.S3_BUCKET || 'shumai'
const inputSource =
params.filePath ||
(params.assetKey ? await s3Service.resolveInput(bucket, params.assetKey) : '')
if (!inputSource) {
throw ApplicationFailure.create({
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
nonRetryable: true,
})
}
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
const duration = Math.max(0.1, params.endTime - params.startTime)
const fpsFilter = duration > 16 ? `fps=${16 / duration}` : 'fps=1'
const vframesArgs = duration > 16 ? ['-vframes', '16'] : []
await execFileAsync('ffmpeg', [
'-y',
'-loglevel',
'warning',
...(isRemote
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
: []),
'-ss',
params.startTime.toString(),
'-i',
inputSource,
'-map',
'0:V:0',
'-t',
duration.toString(),
'-vf',
fpsFilter,
...vframesArgs,
'-q:v',
'2',
path.join(tmpDir, 'frame_%04d.jpg'),
])
const frameFiles = fs
.readdirSync(tmpDir)
.filter((f) => /\.(jpe?g|png|webp)$/i.test(f))
.sort()
const archiveEntries: Record<string, Buffer> = {}
for (const file of frameFiles) {
archiveEntries[file] = fs.readFileSync(path.join(tmpDir, file))
}
const archive = new Bun.Archive(archiveEntries)
const archiveBytes = await archive.bytes()
const archiveData = Buffer.from(
archiveBytes.buffer,
archiveBytes.byteOffset,
archiveBytes.byteLength,
)
const key = `files/${params.assetId}/tmp-embedding-chunks/frames-${params.startTime}-${params.endTime}-${ulid()}.tar`
await s3Service.putObject(bucket, key, archiveData, archiveData.length, 'application/x-tar')
return { chunkKey: key }
} catch (err) {
if (err instanceof ApplicationFailure) {
throw err
}
throw ApplicationFailure.create({
message: `Failed to extract video chunk frames for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
})
} finally {
transcodeService.removeDir(tmpDir)
}
if (!params.chunks || params.chunks.length === 0) {
return { chunks: [] }
}
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}-${ulid()}.mp4`)
let childTask = null
if (params.parentTaskId) {
childTask = await prisma.workflowTask.findFirst({
where: {
assetId: params.assetId,
type: WorkflowTaskType.transcode_video_chunks,
status: {
in: [
WorkflowTaskStatus.pending,
WorkflowTaskStatus.processing,
WorkflowTaskStatus.completed,
],
},
payload: {
path: ['videoChunks', 'parentTaskId'],
equals: params.parentTaskId,
},
},
orderBy: { id: 'desc' },
})
}
if (!childTask) {
childTask = await prisma.workflowTask.create({
data: {
assetId: params.assetId,
teamId: params.teamId ?? null,
projectId: params.projectId ?? null,
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.pending,
payload: {
projectId: params.projectId ?? '',
videoChunks: {
parentTaskId: params.parentTaskId,
assetKey: params.assetKey,
format: params.format,
chunks: params.chunks,
},
},
},
})
}
const abortSignal = getLocalTaskAbortSignal(params.parentTaskId)
if (abortSignal?.aborted) {
await cancelChildTranscodeTask(childTask.id)
throw ApplicationFailure.create({
message: 'Parent embedding workflow was cancelled before transcode completed',
nonRetryable: true,
})
}
const onAbort = () => {
void cancelChildTranscodeTask(childTask.id)
}
abortSignal?.addEventListener('abort', onAbort, { once: true })
try {
const bucket = process.env.S3_BUCKET || 'shumai'
const inputSource =
params.filePath ||
(params.assetKey ? await s3Service.resolveInput(bucket, params.assetKey) : '')
if (!inputSource) {
const { task: completedTask, done } = await workflowService.waitFor(
childTask,
getTranscodeWaitTimeoutMs(),
)
if (!done) {
await cancelChildTranscodeTask(childTask.id)
throw ApplicationFailure.create({
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
message: `Transcode video chunks task ${childTask.id} timed out`,
nonRetryable: true,
})
}
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
// Slice video segment using ffmpeg, force 1fps and remove audio for gemini-embedding-2 optimization
// Note: -ss placed before -i for fast input seeking via demuxer Range requests
await execFileAsync('ffmpeg', [
'-y',
'-loglevel',
'warning',
...(isRemote
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
: []),
'-ss',
params.startTime.toString(),
'-i',
inputSource,
'-map',
'0:V:0',
'-t',
(params.endTime - params.startTime).toString(),
'-vf',
'fps=1',
'-c:v',
'libx264',
'-preset',
'ultrafast',
'-crf',
'28',
'-an',
chunkTmp,
])
const output = completedTask.output as { chunks?: TranscodedVideoChunk[] } | null
if (!output?.chunks || !Array.isArray(output.chunks)) {
throw ApplicationFailure.create({
message: `Transcode video chunks task ${childTask.id} completed without valid chunks output`,
nonRetryable: true,
})
}
const chunkData = fs.readFileSync(chunkTmp)
if (abortSignal?.aborted) {
const bucket = process.env.S3_BUCKET || 'shumai'
for (const chunk of output.chunks) {
try {
await s3Service.deleteObject(bucket, chunk.chunkKey)
} catch {
// Best-effort cleanup on cancellation race
}
}
throw ApplicationFailure.create({
message: 'Parent embedding workflow was cancelled before transcode completed',
nonRetryable: true,
})
}
// Upload to S3
const key = `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}-${ulid()}.mp4`
await s3Service.putObject(bucket, key, chunkData, chunkData.length, 'video/mp4')
return { chunkKey: key }
return { chunks: output.chunks }
} catch (err) {
if (abortSignal?.aborted || isDbosWorkflowCancelledError(err)) {
await cancelChildTranscodeTask(childTask.id)
throw err
}
if (err instanceof ApplicationFailure) {
throw err
}
// The child transcode workflow already applies its own step retry policy;
// fail fast here instead of spawning duplicate child tasks on parent retries.
throw ApplicationFailure.create({
message: `Failed to transcode video chunk for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
message: err instanceof Error ? err.message : String(err),
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
})
} finally {
if (fs.existsSync(chunkTmp)) {
try {
fs.unlinkSync(chunkTmp)
} catch (e) {
console.error('Failed to cleanup local chunk file:', e)
}
}
abortSignal?.removeEventListener('abort', onAbort)
}
})