mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 03:14:11 +00:00
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:
@@ -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
@@ -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)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user