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
+2
View File
@@ -14,6 +14,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Changed
- **transcode**: Offload video chunk slicing for search embeddings to the transcode worker queue.
## [0.7.0] - 2026-11-18
### Added
+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)
}
})
+4 -2
View File
@@ -13,15 +13,17 @@ export function initAgentWorkflows() {
export * from './activities/agent'
export {
deleteAssetEmbeddingsActivity,
extractAiMetadataActivity,
generateImageEmbeddingActivity,
generateTextEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
saveAssetEmbeddingsActivity,
transcodeVideoChunksActivity,
type ExistingAssetEmbeddingInfo,
type ExtractAiMetadataParams,
type GeneratedEmbedding,
type GenerateTextEmbeddingParams,
type TranscodedVideoChunk,
type TranscodeVideoChunksParams,
type VideoChunkRange,
} from './activities/ai'
export * from './context/serialize-context'
export * from './operation-tools'
@@ -34,7 +34,7 @@ vi.mock('../activities/ai', async () => {
generateVideoChunkEmbeddingActivity: vi.fn(),
saveAssetEmbeddingsActivity: vi.fn(),
deleteAssetEmbeddingsActivity: vi.fn(),
transcodeVideoChunkActivity: vi.fn(),
transcodeVideoChunksActivity: vi.fn(),
deleteS3ObjectActivity: vi.fn(),
}
})
@@ -60,9 +60,7 @@ describe('Agent Embedding Workflow', () => {
updateTaskUsageActivity: vi.mocked(workflowCore.updateTaskUsageActivity),
createCommentActivity: vi.mocked(agentActivities.createCommentActivity),
updateCommentActivity: vi.mocked(agentActivities.updateCommentActivity),
downloadMediaToTmpActivity: vi.fn(),
cleanupTmpDirActivity: vi.fn(),
transcodeVideoChunkActivity: vi.mocked(aiActivities.transcodeVideoChunkActivity),
transcodeVideoChunksActivity: vi.mocked(aiActivities.transcodeVideoChunksActivity),
deleteS3ObjectActivity: vi.mocked(aiActivities.deleteS3ObjectActivity),
}
@@ -86,19 +84,21 @@ describe('Agent Embedding Workflow', () => {
embedding: [0.3, 0.4],
usage: { inputTokens: 3, outputTokens: 3, model: 'gpt' },
})
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
filePath: '/tmp/test.mp4',
tmpDir: '/tmp/test-dir',
})
mockActivities.transcodeVideoChunkActivity.mockImplementation(
async (params: { assetId: string; startTime: number; endTime: number }) => {
mockActivities.transcodeVideoChunksActivity.mockImplementation(
async (params: {
assetId: string
chunks: Array<{ startTime: number; endTime: number }>
}) => {
return {
chunkKey: `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}.mp4`,
chunks: params.chunks.map((c) => ({
startTime: c.startTime,
endTime: c.endTime,
chunkKey: `files/${params.assetId}/tmp-embedding-chunks/chunk-${c.startTime}-${c.endTime}.mp4`,
})),
}
},
)
mockActivities.deleteS3ObjectActivity.mockResolvedValue(undefined)
mockActivities.cleanupTmpDirActivity.mockResolvedValue(undefined)
})
it('should run agent embedding workflow successfully for image', async () => {
@@ -256,7 +256,7 @@ describe('Agent Embedding Workflow', () => {
)
})
it('should run agent embedding workflow successfully for video in chunks', async () => {
it('should run agent embedding workflow successfully for video in chunks via single batch transcode task', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
@@ -278,6 +278,7 @@ describe('Agent Embedding Workflow', () => {
status: 'pending',
assetId: 'a1',
teamId: 't1',
projectId: 'p1',
payload: {
projectId: 'p1',
agent: { sessionId: 's1', agentId: 'agent-1' },
@@ -287,28 +288,20 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
// Verify video chunk slicing activity called 3 times on transcode queue
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(3)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(1, {
// Verify batch video chunk slicing activity called once on transcode queue with all 3 chunks
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledWith({
parentTaskId: task.id,
teamId: 't1',
projectId: 'p1',
assetId: 'a1',
assetKey: 'test-transcoded.mp4',
startTime: 0,
endTime: 60,
format: 'video',
})
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(2, {
assetId: 'a1',
assetKey: 'test-transcoded.mp4',
startTime: 55,
endTime: 115,
format: 'video',
})
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(3, {
assetId: 'a1',
assetKey: 'test-transcoded.mp4',
startTime: 110,
endTime: 150,
format: 'video',
chunks: [
{ startTime: 0, endTime: 60 },
{ startTime: 55, endTime: 115 },
{ startTime: 110, endTime: 150 },
],
})
// Verify video chunk embedding generation (3 chunks) on agent queue
@@ -401,6 +394,7 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
expect(mockActivities.transcodeVideoChunksActivity).not.toHaveBeenCalled()
expect(mockActivities.saveAssetEmbeddingsActivity).not.toHaveBeenCalled()
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: task.id,
@@ -469,7 +463,7 @@ describe('Agent Embedding Workflow', () => {
})
})
it('should save completed chunks to DB immediately before subsequent chunk failure', async () => {
it('should save completed chunks to DB immediately and clean up all remaining temporary S3 chunks on failure', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
@@ -510,6 +504,18 @@ describe('Agent Embedding Workflow', () => {
assetId: 'a1',
embeddings: [{ embedding: [0.1, 0.2], startTime: 0, endTime: 60 }],
})
// All 3 temporary chunks (chunk 1 after success, chunk 2 and chunk 3 in finally) MUST be deleted from S3
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenCalledTimes(3)
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenNthCalledWith(1, {
key: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
})
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenNthCalledWith(2, {
key: 'files/a1/tmp-embedding-chunks/chunk-55-115.mp4',
})
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenNthCalledWith(3, {
key: 'files/a1/tmp-embedding-chunks/chunk-110-150.mp4',
})
})
it('should not create redundant chunks when video exactly matches chunk duration', async () => {
@@ -538,12 +544,11 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
// Verify only 1 chunk was created instead of 2 (0-60 and 55-60)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledWith(
// Verify only 1 chunk was requested instead of 2 (0-60 and 55-60)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledWith(
expect.objectContaining({
startTime: 0,
endTime: 60,
chunks: [{ startTime: 0, endTime: 60 }],
}),
)
})
@@ -575,11 +580,10 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledWith(
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledWith(
expect.objectContaining({
startTime: 0,
endTime: 30,
format: 'frames',
chunks: [{ startTime: 0, endTime: 30 }],
}),
)
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith(
@@ -626,14 +630,14 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
// Chunk 1 (0-60) should be skipped; only chunk 2 (55-115) and chunk 3 (110-150) should be transcoded and embedded
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(2)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ startTime: 55, endTime: 115 }),
)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ startTime: 110, endTime: 150 }),
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledWith(
expect.objectContaining({
chunks: [
{ startTime: 55, endTime: 115 },
{ startTime: 110, endTime: 150 },
],
}),
)
expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalledTimes(2)
+65 -47
View File
@@ -1,3 +1,4 @@
import { logger } from '@shumai/core/src/logger'
import type { WorkflowTask } from '@shumai/db'
import {
ApplicationFailure,
@@ -12,8 +13,9 @@ import {
generateVideoChunkEmbeddingActivity,
getEmbeddingContextActivity,
saveAssetEmbeddingsActivity,
transcodeVideoChunkActivity,
transcodeVideoChunksActivity,
type ExistingAssetEmbeddingInfo,
type VideoChunkRange,
} from '../activities/ai'
export interface GeneratedEmbedding {
@@ -148,6 +150,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
const overlap = chunkOverlap ?? 5.0
const step = Math.max(1, limit - overlap)
const missingChunks: VideoChunkRange[] = []
for (let start = 0.0; start < duration; start += step) {
let end = start + limit
if (end >= duration) {
@@ -163,52 +166,8 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
Math.abs(c.endTime - end) < 0.1,
)
if (chunkExists) {
// If this chunk reached the end of the video, stop
if (end >= duration) {
break
}
continue
}
// Step A: Slice chunk on transcode worker and upload to S3
const chunkRes = await transcodeVideoChunkActivity({
assetId: asset.id,
assetKey: embeddingKey,
startTime: start,
endTime: end,
format: isGemmaProvider ? 'frames' : 'video',
})
const { chunkKey } = chunkRes
try {
// Step B: Generate embedding on agent worker
const chunkResult = await generateVideoChunkEmbeddingActivity({
teamId: task.teamId,
chunkKey,
})
// Step C: Save chunk embedding to database immediately
await saveAssetEmbeddingsActivity({
assetId: task.assetId,
embeddings: [
{
embedding: chunkResult.embedding,
startTime: start,
endTime: end,
},
],
})
if (chunkResult.usage) {
usage.inputTokens += chunkResult.usage.inputTokens || 0
usage.outputTokens += chunkResult.usage.outputTokens || 0
}
} finally {
// Step D: Delete temporary chunk from S3
await deleteS3ObjectActivity({
key: chunkKey,
})
if (!chunkExists) {
missingChunks.push({ startTime: start, endTime: end })
}
// If this chunk reached the end of the video, stop to avoid redundant overlapping chunks
@@ -216,6 +175,65 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
break
}
}
if (missingChunks.length > 0) {
// Step A: Slice all missing chunks via batch task on transcode queue and upload to S3
const { chunks: transcodedChunks } = await transcodeVideoChunksActivity({
parentTaskId: task.id,
teamId: task.teamId,
projectId: task.projectId,
assetId: asset.id,
assetKey: embeddingKey,
format: isGemmaProvider ? 'frames' : 'video',
chunks: missingChunks,
})
const remainingChunkKeys = new Set(transcodedChunks.map((c) => c.chunkKey))
try {
for (const chunk of transcodedChunks) {
// Step B: Generate embedding on agent worker
const chunkResult = await generateVideoChunkEmbeddingActivity({
teamId: task.teamId,
chunkKey: chunk.chunkKey,
})
// Step C: Save chunk embedding to database immediately
await saveAssetEmbeddingsActivity({
assetId: task.assetId,
embeddings: [
{
embedding: chunkResult.embedding,
startTime: chunk.startTime,
endTime: chunk.endTime,
},
],
})
if (chunkResult.usage) {
usage.inputTokens += chunkResult.usage.inputTokens || 0
usage.outputTokens += chunkResult.usage.outputTokens || 0
}
// Step D: Delete temporary chunk from S3 as soon as it is embedded
await deleteS3ObjectActivity({
key: chunk.chunkKey,
})
remainingChunkKeys.delete(chunk.chunkKey)
}
} finally {
for (const key of remainingChunkKeys) {
try {
await deleteS3ObjectActivity({ key })
} catch (cleanupErr) {
logger.error(
{ taskId: task.id, chunkKey: key, err: cleanupErr },
'Failed to delete temporary chunk from S3',
)
}
}
}
}
}
// Update Usage
+1
View File
@@ -137,6 +137,7 @@ export class AssetArchiveService {
WorkflowTaskType.transcode_screenshot,
WorkflowTaskType.transcode_image_annotation,
WorkflowTaskType.transcode_watermark,
WorkflowTaskType.transcode_video_chunks,
],
},
},
+40
View File
@@ -5556,6 +5556,46 @@ describe('AssetService — natural sort by name', () => {
expect(restored?.isDeleted).toBe(false)
expect(restored?.status).toBe(AssetStatus.processed)
})
it('should restore asset with status "processed" even if an auxiliary transcode_video_chunks task is active', async () => {
const team = await prisma.team.create({ data: { name: 'Restore Video Chunks Team' } })
const project = await prisma.project.create({
data: { name: 'Restore Video Chunks Project', teamId: team.id },
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
status: AssetStatus.uploaded,
},
})
const file = await prisma.asset.create({
data: {
name: 'embedding-chunks-video.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
status: AssetStatus.trashed,
isDeleted: true,
deletedAt: new Date(),
},
})
await prisma.workflowTask.create({
data: {
assetId: file.id,
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.processing,
},
})
await assetService.restoreAssets([file.id])
const restored = await prisma.asset.findUnique({ where: { id: file.id } })
expect(restored?.isDeleted).toBe(false)
expect(restored?.status).toBe(AssetStatus.processed)
})
})
describe('HLS playlists', () => {
@@ -166,6 +166,15 @@ describe('EmbeddingService', () => {
projectId: project.id,
},
})
const staleChunkTask = await prisma.workflowTask.create({
data: {
assetId: videoAsset.id,
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.processing,
teamId: team.id,
projectId: project.id,
},
})
const initialEmbeddings = await prisma.assetEmbedding.count({
where: { assetId: videoAsset.id },
@@ -179,6 +188,12 @@ describe('EmbeddingService', () => {
expect(result.tasksCreated).toBe(3)
expect(result.skippedTeams).not.toContain('Active Embedding Team')
// Verify old transcode_video_chunks task was also wiped upfront
const remainingChunkTask = await prisma.workflowTask.findUnique({
where: { id: staleChunkTask.id },
})
expect(remainingChunkTask).toBeNull()
// Verify old embeddings were wiped upfront
const remainingEmbeddings = await prisma.assetEmbedding.count({
where: { assetId: videoAsset.id },
@@ -80,7 +80,9 @@ export class EmbeddingService {
await prisma.workflowTask.deleteMany({
where: {
assetId: { in: eligibleAssetIds },
type: WorkflowTaskType.ai_embedding,
type: {
in: [WorkflowTaskType.ai_embedding, WorkflowTaskType.transcode_video_chunks],
},
},
})
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "WorkflowTaskType" ADD VALUE 'transcode_video_chunks';
+1
View File
@@ -125,6 +125,7 @@ enum WorkflowTaskType {
transcode_image_annotation
transcode_watermark
transcode_3d
transcode_video_chunks
ai_metadata_autofill
chat
ai_embedding
+1
View File
@@ -154,6 +154,7 @@ export const WorkflowTaskType = {
transcode_image_annotation: 'transcode_image_annotation',
transcode_watermark: 'transcode_watermark',
transcode_3d: 'transcode_3d',
transcode_video_chunks: 'transcode_video_chunks',
ai_metadata_autofill: 'ai_metadata_autofill',
chat: 'chat',
ai_embedding: 'ai_embedding',
File diff suppressed because one or more lines are too long
+11
View File
@@ -360,6 +360,16 @@ declare global {
annotations?: AnnotationList | null
}
export interface VideoChunksSpec {
parentTaskId?: string
assetKey?: string
format?: 'video' | 'frames'
chunks: Array<{
startTime: number
endTime: number
}>
}
export interface WorkflowTaskPayload {
projectId: string
transcode?: TaskSpec
@@ -370,6 +380,7 @@ declare global {
screenshot?: ScreenshotSpec
imageAnnotation?: ImageAnnotationSpec
pdfPages?: PdfPagesSpec
videoChunks?: VideoChunksSpec
/** Render that produced this result, if any (set by the read_asset pipeline). */
assetRead?: AssetReadRequest
watermark?: WatermarkTaskPayload
@@ -313,6 +313,17 @@ describe('Workflow E2E - agentEmbeddingMedia', () => {
// 5. Verification
expect(completedTask.status).toBe('completed')
// Verify batch transcode_video_chunks task was created and completed on TaskQueueTranscode
const chunkTasks = await prisma.workflowTask.findMany({
where: {
assetId: asset.id,
type: 'transcode_video_chunks',
},
})
expect(chunkTasks).toHaveLength(1)
expect(chunkTasks[0].status).toBe(WorkflowTaskStatus.completed)
expect(chunkTasks[0].payload?.videoChunks?.parentTaskId).toBe(task.id)
// Verify raw embedding is saved in DB with start and end times
const dbEmbeddings = (await prisma.$queryRaw`
SELECT id, asset_id as "assetId", start_time as "startTime", end_time as "endTime"
@@ -323,6 +334,13 @@ describe('Workflow E2E - agentEmbeddingMedia', () => {
expect(dbEmbeddings.length).toBeGreaterThan(0)
expect(dbEmbeddings[0].startTime).toBe(0)
expect(dbEmbeddings[0].endTime).toBe(1)
// Verify all temporary embedding chunk files were cleaned up from S3
const remainingTmpChunks = await s3Service.listObjects(
'shumai-e2e-test-bucket-embedding',
`files/${asset.id}/tmp-embedding-chunks/`,
)
expect(remainingTmpChunks).toEqual([])
}, 50000)
it('should fail agentEmbeddingMedia workflow for an unsupported audio asset', async () => {
@@ -1,7 +1,11 @@
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { s3Service } from '@shumai/core/src/s3/s3'
import { prisma } from '@shumai/db'
import { prisma, AssetStatus, AssetType } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import {
registerLocalTaskAbortController,
unregisterLocalTaskAbortController,
} from '@shumai/workflow-core'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
@@ -1464,6 +1468,109 @@ describe('Transcode Activities', () => {
}
})
it('should fail fast with non-retryable error when task is already cancelled', async () => {
const taskId = 'task-chunk-pre-aborted'
const abortController = new AbortController()
abortController.abort()
registerLocalTaskAbortController(taskId, abortController)
try {
expect.assertions(3)
try {
await transcodeVideoChunkActivity({
taskId,
assetId: 'asset-abc',
filePath: '/tmp/test.mp4',
startTime: 0,
endTime: 10,
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('Video chunk transcoding cancelled')
}
expect(child_process.execFile).not.toHaveBeenCalled()
} finally {
unregisterLocalTaskAbortController(taskId)
}
})
it('should pass AbortSignal to ffmpeg and throw non-retryable error on in-flight cancellation', async () => {
const taskId = 'task-chunk-inflight-abort'
const abortController = new AbortController()
registerLocalTaskAbortController(taskId, abortController)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- execFile mockImplementation uses 4-arg overload with options
;(child_process.execFile as any).mockImplementation(
(
_file: string,
_args: string[],
options: { signal?: AbortSignal },
cb: (err: Error | null, result: { stdout: string; stderr: string }) => void,
) => {
expect(options?.signal).toBe(abortController.signal)
abortController.abort()
const abortErr = new Error('The operation was aborted') as Error & { code?: string }
abortErr.code = 'ABORT_ERR'
cb(abortErr, { stdout: '', stderr: '' })
},
)
try {
expect.assertions(4)
try {
await transcodeVideoChunkActivity({
taskId,
assetId: 'asset-abc',
filePath: '/tmp/test.mp4',
startTime: 0,
endTime: 10,
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('Video chunk transcoding cancelled')
}
expect(s3Service.putObject).not.toHaveBeenCalled()
} finally {
unregisterLocalTaskAbortController(taskId)
}
})
it('should fail with non-retryable error before S3 upload if asset is pending_purge', async () => {
const purgingAsset = await prisma.asset.create({
data: {
name: 'purging-video.mp4',
type: AssetType.file,
status: AssetStatus.pending_purge,
mediaType: 'video/mp4',
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- execFile mockImplementation returns void rather than ChildProcess
;(child_process.execFile as any).mockImplementation(
(
_file: string,
_args: string[],
cb: (err: Error | null, result: { stdout: string; stderr: string }) => void,
) => {
cb(null, { stdout: '', stderr: '' })
},
)
expect.assertions(3)
try {
await transcodeVideoChunkActivity({
assetId: purgingAsset.id,
assetKey: 'files/proxy-720p.mp4',
startTime: 0,
endTime: 10,
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('pending purge')
}
expect(s3Service.putObject).not.toHaveBeenCalled()
})
it('should return existing poster if already present in S3', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(s3Service.headObject).mockResolvedValue({} as any)
+62 -3
View File
@@ -1580,7 +1580,27 @@ export const createAutofillTaskIfEnabledActivity = defineStep(
},
)
async function ensureAssetNotPurgingByIdOrKey(assetId: string, assetKey?: string): Promise<void> {
const asset = await prisma.asset.findUnique({
where: { id: assetId },
select: { status: true, storageKey: { select: { status: true } } },
})
if (
asset &&
(asset.status === AssetStatus.pending_purge || asset.storageKey?.status === 'purging')
) {
throw ApplicationFailure.create({
message: 'Asset or storage key has been purged or is pending purge',
nonRetryable: true,
})
}
if (assetKey) {
await ensureAssetNotPurging(assetKey)
}
}
export interface TranscodeVideoChunkParams {
taskId?: string
assetId: string
assetKey?: string
filePath?: string
@@ -1599,6 +1619,28 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
})
}
const signal = getActivityCancellationSignal(params.taskId)
if (signal?.aborted) {
throw ApplicationFailure.create({
message: 'Video chunk transcoding cancelled',
nonRetryable: true,
})
}
const runFfmpeg = (args: string[]) =>
signal ? execFileAsync('ffmpeg', args, { signal }) : execFileAsync('ffmpeg', args)
const isAbortError = (err: unknown): boolean => {
const { code, message } = getErrorDetails(err)
const lowerMsg = message.toLowerCase()
return (
Boolean(signal?.aborted) ||
code === 'ABORT_ERR' ||
message.includes('aborted') ||
lowerMsg.includes('abort')
)
}
if (params.format === 'frames') {
const tmpDir = transcodeService.createTempDir('video-chunk-frames-')
try {
@@ -1618,7 +1660,7 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
const fpsFilter = duration > 16 ? `fps=${16 / duration}` : 'fps=1'
const vframesArgs = duration > 16 ? ['-vframes', '16'] : []
await execFileAsync('ffmpeg', [
await runFfmpeg([
'-y',
'-loglevel',
'warning',
@@ -1658,6 +1700,7 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
archiveBytes.byteOffset,
archiveBytes.byteLength,
)
await ensureAssetNotPurgingByIdOrKey(params.assetId, params.assetKey)
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')
@@ -1666,6 +1709,13 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
if (err instanceof ApplicationFailure) {
throw err
}
if (isAbortError(err)) {
throw ApplicationFailure.create({
message: 'Video chunk transcoding cancelled',
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
})
}
throw ApplicationFailure.create({
message: `Failed to extract video chunk frames for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
@@ -1691,7 +1741,7 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
// 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', [
await runFfmpeg([
'-y',
'-loglevel',
'warning',
@@ -1720,6 +1770,8 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
const chunkData = fs.readFileSync(chunkTmp)
await ensureAssetNotPurgingByIdOrKey(params.assetId, params.assetKey)
// Upload to S3
const key = `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}-${ulid()}.mp4`
@@ -1730,6 +1782,13 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
if (err instanceof ApplicationFailure) {
throw err
}
if (isAbortError(err)) {
throw ApplicationFailure.create({
message: 'Video chunk transcoding cancelled',
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
})
}
throw ApplicationFailure.create({
message: `Failed to transcode video chunk for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
@@ -1739,7 +1798,7 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
try {
fs.unlinkSync(chunkTmp)
} catch (e) {
console.error('Failed to cleanup local chunk file:', e)
logger.error({ err: e, chunkTmp }, 'Failed to cleanup local chunk file')
}
}
}
+3
View File
@@ -8,6 +8,7 @@ import { takeVideoScreenshotsWorkflow } from './workflows/take-video-screenshots
import { overlayImageAnnotationWorkflow } from './workflows/overlay-image-annotation'
import { transcodeWatermarkWorkflow } from './workflows/transcode-watermark'
import { transcode3dWorkflow } from './workflows/transcode-3d'
import { transcodeVideoChunksWorkflow } from './workflows/transcode-video-chunks'
import { transcodeMedia } from './workflows/transcode'
import { archiveAssetWorkflow } from './workflows/archive-asset'
import { restoreAssetWorkflow } from './workflows/restore-asset'
@@ -22,6 +23,7 @@ export function initTranscodeWorkflows() {
registerWorkflow(WorkflowTaskType.transcode_screenshot, takeVideoScreenshotsWorkflow)
registerWorkflow(WorkflowTaskType.transcode_image_annotation, overlayImageAnnotationWorkflow)
registerWorkflow(WorkflowTaskType.transcode_watermark, transcodeWatermarkWorkflow)
registerWorkflow(WorkflowTaskType.transcode_video_chunks, transcodeVideoChunksWorkflow)
registerWorkflow(WorkflowTaskType.archive_asset, archiveAssetWorkflow)
registerWorkflow(WorkflowTaskType.restore_asset, restoreAssetWorkflow)
}
@@ -30,6 +32,7 @@ export * from './transcoder'
export * from './workflows/transcode'
export * from './workflows/transcode-3d'
export * from './workflows/transcode-watermark'
export * from './workflows/transcode-video-chunks'
export * from './workflows/archive-asset'
export * from './workflows/restore-asset'
export * from './activities/transcode'
@@ -0,0 +1,262 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { transcodeVideoChunksWorkflow } from './transcode-video-chunks'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { getAssetActivity, updateTaskStatusActivity } from '@shumai/workflow-core'
import { deleteS3ObjectActivity, transcodeVideoChunkActivity } from '../activities/transcode'
vi.mock('@shumai/workflow-core', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
return {
...actual,
updateTaskStatusActivity: vi.fn(),
getAssetActivity: vi.fn(),
}
})
vi.mock('../activities/transcode', () => ({
transcodeVideoChunkActivity: vi.fn(),
deleteS3ObjectActivity: vi.fn(),
}))
function createMockTask(overrides?: Partial<WorkflowTask>): WorkflowTask {
return {
id: 'task-video-chunks',
assetId: 'asset-video',
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.pending,
sessionId: null,
output: null,
payload: {
projectId: 'proj-1',
videoChunks: {
parentTaskId: 'parent-emb-1',
assetKey: 'files/asset-video/proxy.mp4',
format: 'video',
chunks: [
{ startTime: 0, endTime: 60 },
{ startTime: 55, endTime: 110 },
],
},
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
...overrides,
}
}
describe('transcodeVideoChunksWorkflow', () => {
const mockActivities = {
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
getAssetActivity: vi.mocked(getAssetActivity),
transcodeVideoChunkActivity: vi.mocked(transcodeVideoChunkActivity),
deleteS3ObjectActivity: vi.mocked(deleteS3ObjectActivity),
}
beforeEach(() => {
vi.clearAllMocks()
mockActivities.updateTaskStatusActivity.mockResolvedValue({} as never)
mockActivities.deleteS3ObjectActivity.mockResolvedValue(undefined)
})
it('should transcode all requested video chunks and complete with chunk keys', async () => {
const task = createMockTask()
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-video',
status: 'processed',
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: false },
mediaType: 'video/mp4',
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
mockActivities.transcodeVideoChunkActivity
.mockResolvedValueOnce({
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
})
.mockResolvedValueOnce({
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-55-110.mp4',
})
await transcodeVideoChunksWorkflow(task)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(2)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(1, {
taskId: 'task-video-chunks',
assetId: 'asset-video',
assetKey: 'files/asset-video/proxy.mp4',
startTime: 0,
endTime: 60,
format: 'video',
})
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(2, {
taskId: 'task-video-chunks',
assetId: 'asset-video',
assetKey: 'files/asset-video/proxy.mp4',
startTime: 55,
endTime: 110,
format: 'video',
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-video-chunks',
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
},
{
startTime: 55,
endTime: 110,
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-55-110.mp4',
},
],
},
})
})
it('should fall back to videoTranscodes proxy when assetKey is omitted and support frames format on archived assets', async () => {
const task = createMockTask({
payload: {
projectId: 'proj-1',
videoChunks: {
parentTaskId: 'parent-emb-2',
format: 'frames',
chunks: [{ startTime: 0, endTime: 30 }],
},
},
})
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-video',
status: 'archived',
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: true },
mediaType: 'video/mp4',
media: {
videoTranscodes: [{ key: 'files/asset-video/proxy-720p.mp4' }],
},
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
mockActivities.transcodeVideoChunkActivity.mockResolvedValueOnce({
chunkKey: 'files/asset-video/tmp-embedding-chunks/frames-0-30.tar',
})
await transcodeVideoChunksWorkflow(task)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledWith({
taskId: 'task-video-chunks',
assetId: 'asset-video',
assetKey: 'files/asset-video/proxy-720p.mp4',
startTime: 0,
endTime: 30,
format: 'frames',
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-video-chunks',
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 30,
chunkKey: 'files/asset-video/tmp-embedding-chunks/frames-0-30.tar',
},
],
},
})
})
it('should fail with non-retryable ApplicationFailure when payload is invalid', async () => {
const task = createMockTask({
payload: {
projectId: 'proj-1',
},
})
await expect(transcodeVideoChunksWorkflow(task)).rejects.toThrow(
'Invalid payload for videoChunks task',
)
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-video-chunks',
status: WorkflowTaskStatus.failed,
output: { error: 'Invalid payload for videoChunks task' },
})
})
it('should fail fast when asset is archived and no videoTranscodes proxy is available', async () => {
const task = createMockTask({
payload: {
projectId: 'proj-1',
videoChunks: {
assetKey: 'files/asset-video/raw.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
},
},
})
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-video',
status: 'archived',
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: true },
mediaType: 'video/mp4',
media: {
videoTranscodes: [],
},
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
await expect(transcodeVideoChunksWorkflow(task)).rejects.toThrow(
'Original video file is archived and no proxy is available. Restore the asset to generate embeddings.',
)
expect(mockActivities.transcodeVideoChunkActivity).not.toHaveBeenCalled()
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-video-chunks',
status: WorkflowTaskStatus.failed,
output: {
error:
'Original video file is archived and no proxy is available. Restore the asset to generate embeddings.',
},
})
})
it('should clean up already-uploaded chunk files in S3 if a subsequent chunk fails', async () => {
const task = createMockTask()
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-video',
status: 'processed',
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: false },
mediaType: 'video/mp4',
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
mockActivities.transcodeVideoChunkActivity
.mockResolvedValueOnce({
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
})
.mockRejectedValueOnce(new Error('ffmpeg slice failed on chunk 2'))
await expect(transcodeVideoChunksWorkflow(task)).rejects.toThrow(
'ffmpeg slice failed on chunk 2',
)
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenCalledWith({
key: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-video-chunks',
status: WorkflowTaskStatus.failed,
output: { error: 'ffmpeg slice failed on chunk 2' },
})
})
})
@@ -0,0 +1,82 @@
import { logger } from '@shumai/core/src/logger'
import type { WorkflowTask } from '@shumai/db'
import { ApplicationFailure } from '@shumai/workflow-core'
import { deleteS3ObjectActivity, transcodeVideoChunkActivity } from '../activities/transcode'
import { completeTask, failTask, fetchAssetWithKey, startTask } from './common'
export interface TranscodedVideoChunkItem {
startTime: number
endTime: number
chunkKey: string
}
export async function transcodeVideoChunksWorkflow(task: WorkflowTask): Promise<void> {
const uploadedChunkKeys: string[] = []
try {
await startTask(task)
const payload = task.payload
if (!payload?.videoChunks || !Array.isArray(payload.videoChunks.chunks)) {
throw ApplicationFailure.create({
message: 'Invalid payload for videoChunks task',
nonRetryable: true,
})
}
const { asset, key } = await fetchAssetWithKey(task.assetId)
let targetKey = payload.videoChunks.assetKey || key
if (!payload.videoChunks.assetKey && asset?.media) {
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo
if (mediaInfo.videoTranscodes && mediaInfo.videoTranscodes.length > 0) {
const transcode = mediaInfo.videoTranscodes[0]
if (transcode?.key) {
targetKey = transcode.key
}
}
}
if (targetKey === key && (asset.storageKey?.isArchived || asset.status === 'archived')) {
throw ApplicationFailure.create({
message:
'Original video file is archived and no proxy is available. Restore the asset to generate embeddings.',
nonRetryable: true,
})
}
const chunks: TranscodedVideoChunkItem[] = []
for (const range of payload.videoChunks.chunks) {
const { chunkKey } = await transcodeVideoChunkActivity({
taskId: task.id,
assetId: asset.id,
assetKey: targetKey,
startTime: range.startTime,
endTime: range.endTime,
format: payload.videoChunks.format,
})
uploadedChunkKeys.push(chunkKey)
chunks.push({
startTime: range.startTime,
endTime: range.endTime,
chunkKey,
})
}
await completeTask(task.id, { chunks })
} catch (err) {
logger.error({ taskId: task.id, err }, 'transcodeVideoChunksWorkflow failed')
for (const chunkKey of uploadedChunkKeys) {
try {
await deleteS3ObjectActivity({ key: chunkKey })
} catch (cleanupErr) {
logger.error(
{ taskId: task.id, chunkKey, err: cleanupErr },
'Failed to clean up partial chunk',
)
}
}
await failTask(task.id, err)
throw err
}
}
@@ -42,6 +42,7 @@ describe('DbosExecutor Tests', () => {
expect(getQueueForTaskType(WorkflowTaskType.transcode)).toBe(TaskQueueTranscode)
expect(getQueueForTaskType(WorkflowTaskType.transcode_video)).toBe(TaskQueueTranscode)
expect(getQueueForTaskType(WorkflowTaskType.transcode_image)).toBe(TaskQueueTranscode)
expect(getQueueForTaskType(WorkflowTaskType.transcode_video_chunks)).toBe(TaskQueueTranscode)
expect(getQueueForTaskType(WorkflowTaskType.ai_embedding)).toBe(TaskQueueAgent)
expect(getQueueForTaskType(WorkflowTaskType.chat)).toBe(TaskQueueAgent)
expect(getQueueForTaskType(WorkflowTaskType.archive_asset)).toBe(TaskQueueArchive)
@@ -69,6 +69,7 @@ export function getQueueForTaskType(type: string | null | undefined): string {
case WorkflowTaskType.transcode_image_annotation:
case WorkflowTaskType.transcode_watermark:
case WorkflowTaskType.transcode_3d:
case WorkflowTaskType.transcode_video_chunks:
return TaskQueueTranscode
case WorkflowTaskType.archive_asset:
case WorkflowTaskType.restore_asset: