mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 19:04:23 +00:00
* refactor(transcode): offload video embedding chunk slicing to transcode queue * fix(transcode): address video chunk offloading review findings
1104 lines
36 KiB
TypeScript
1104 lines
36 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
|
import {
|
|
generateTextEmbeddingActivity,
|
|
getEmbeddingContextActivity,
|
|
saveAssetEmbeddingsActivity,
|
|
deleteAssetEmbeddingsActivity,
|
|
generateImageEmbeddingActivity,
|
|
generateVideoChunkEmbeddingActivity,
|
|
getGemmaEmbeddingTargetFrameCount,
|
|
transcodeVideoChunksActivity,
|
|
} from './ai'
|
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
|
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('@shumai/core/src/s3/s3', () => ({
|
|
s3Service: {
|
|
getObject: vi.fn(),
|
|
putObject: vi.fn(),
|
|
headObject: vi.fn(),
|
|
listObjects: vi.fn(),
|
|
downloadToFile: vi.fn(),
|
|
deleteObject: vi.fn(),
|
|
resolveInput: vi.fn().mockImplementation(async (_bucket, key) => `https://mock-storage/${key}`),
|
|
},
|
|
}))
|
|
|
|
const mockEmbedContent = vi.fn().mockResolvedValue({
|
|
embeddings: [
|
|
{
|
|
values: [0.1, 0.2, 0.3],
|
|
},
|
|
],
|
|
})
|
|
|
|
vi.mock('@google/genai', () => {
|
|
return {
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention -- matches external library GoogleGenAI export naming convention
|
|
GoogleGenAI: class {
|
|
models = {
|
|
embedContent: mockEmbedContent,
|
|
}
|
|
},
|
|
}
|
|
})
|
|
|
|
describe('AI Activities Unit Tests', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
process.env.GEMINI_API_KEY = 'test-key'
|
|
delete process.env.EMBEDDING_PROVIDER
|
|
delete process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL
|
|
})
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals()
|
|
delete process.env.EMBEDDING_PROVIDER
|
|
delete process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL
|
|
})
|
|
|
|
it('should generate image embedding', async () => {
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from('test-image'),
|
|
contentType: 'image/png',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateImageEmbeddingActivity({
|
|
teamId: 't1',
|
|
assetKey: 'test.png',
|
|
mediaType: 'image/png',
|
|
})
|
|
|
|
expect(res.embedding).toEqual([0.1, 0.2, 0.3])
|
|
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'test.png')
|
|
})
|
|
|
|
it('should generate video embedding in chunks', async () => {
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from('test-video'),
|
|
contentType: 'video/mp4',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
|
|
})
|
|
|
|
expect(res.embedding).toEqual([0.1, 0.2, 0.3])
|
|
expect(s3Service.getObject).toHaveBeenCalledWith(
|
|
'shumai',
|
|
'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
|
|
)
|
|
})
|
|
|
|
it('should generate text embedding successfully', async () => {
|
|
const res = await generateTextEmbeddingActivity({
|
|
text: 'Search query',
|
|
teamId: 't1',
|
|
})
|
|
|
|
expect(res.embedding).toEqual([0.1, 0.2, 0.3])
|
|
expect(mockEmbedContent).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
model: 'gemini-embedding-2',
|
|
contents: [
|
|
expect.objectContaining({
|
|
parts: [{ text: 'Search query' }],
|
|
}),
|
|
],
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('should generate text embedding successfully with gemma-embedding-2-openai', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.1) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 15 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
const res = await generateTextEmbeddingActivity({
|
|
text: 'Search query',
|
|
teamId: 't1',
|
|
})
|
|
|
|
expect(res.embedding).toHaveLength(768)
|
|
expect(res.usage.model).toBe('embeddinggemma-2')
|
|
expect(res.usage.inputTokens).toBe(15)
|
|
expect(mockFetch).toHaveBeenCalledWith(
|
|
'http://localhost:9379/v1/embeddings',
|
|
expect.objectContaining({
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
model: 'embeddinggemma-2',
|
|
input: 'task: search query | text: Search query',
|
|
}),
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('should generate image embedding successfully with gemma-embedding-2-openai', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.2) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 140 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from('test-image'),
|
|
contentType: 'image/png',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateImageEmbeddingActivity({
|
|
teamId: 't1',
|
|
assetKey: 'img.png',
|
|
mediaType: 'image/png',
|
|
})
|
|
|
|
expect(res.embedding).toHaveLength(768)
|
|
expect(res.usage.model).toBe('embeddinggemma-2')
|
|
expect(res.usage.inputTokens).toBe(140)
|
|
expect(mockFetch).toHaveBeenCalledWith(
|
|
'http://localhost:9379/v1/embeddings',
|
|
expect.objectContaining({
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
model: 'embeddinggemma-2',
|
|
input: [
|
|
{
|
|
type: 'image_url',
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
image_url: {
|
|
url: `data:image/png;base64,${Buffer.from('test-image').toString('base64')}`,
|
|
},
|
|
},
|
|
],
|
|
}),
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('should respect custom GEMMA_EMBEDDING_OPENAI_BASE_URL with or without /v1 suffix', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.2) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 10 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
// Test with /v1
|
|
process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL = 'http://custom-host:9379/v1'
|
|
await generateTextEmbeddingActivity({ text: 'test query', teamId: 't1' })
|
|
expect(mockFetch).toHaveBeenLastCalledWith(
|
|
'http://custom-host:9379/v1/embeddings',
|
|
expect.anything(),
|
|
)
|
|
|
|
// Test without /v1
|
|
process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL = 'http://custom-host:9379'
|
|
await generateTextEmbeddingActivity({ text: 'test query', teamId: 't1' })
|
|
expect(mockFetch).toHaveBeenLastCalledWith(
|
|
'http://custom-host:9379/v1/embeddings',
|
|
expect.anything(),
|
|
)
|
|
})
|
|
|
|
it('should convert webp image to jpeg with gemma-embedding-2-openai', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.2) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 140 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
const webpBuffer = await sharp({
|
|
create: { width: 10, height: 10, channels: 3, background: { r: 255, g: 0, b: 0 } },
|
|
})
|
|
.webp()
|
|
.toBuffer()
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: webpBuffer,
|
|
contentType: 'image/webp',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateImageEmbeddingActivity({
|
|
teamId: 't1',
|
|
assetKey: 'img.webp',
|
|
mediaType: 'image/webp',
|
|
})
|
|
|
|
expect(res.embedding).toHaveLength(768)
|
|
expect(mockFetch).toHaveBeenCalledWith(
|
|
'http://localhost:9379/v1/embeddings',
|
|
expect.objectContaining({
|
|
method: 'POST',
|
|
body: expect.stringContaining('data:image/jpeg;base64,'),
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('should generate video chunk embedding from tar archive with gemma-embedding-2-openai', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.3) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 140 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
const sampleArchive = new Bun.Archive({
|
|
'frame_0001.jpg': Buffer.from('frame-1'),
|
|
})
|
|
const archiveBytes = await sampleArchive.bytes()
|
|
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from(archiveBytes.buffer, archiveBytes.byteOffset, archiveBytes.byteLength),
|
|
contentType: 'application/x-tar',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
|
|
})
|
|
|
|
expect(res.embedding).toHaveLength(768)
|
|
expect(res.usage.model).toBe('embeddinggemma-2')
|
|
expect(mockFetch).toHaveBeenCalled()
|
|
})
|
|
|
|
describe('getGemmaEmbeddingTargetFrameCount', () => {
|
|
it('should return 15 for standard aspect ratios', () => {
|
|
// 16:9
|
|
expect(getGemmaEmbeddingTargetFrameCount(1920, 1080)).toBe(15)
|
|
expect(getGemmaEmbeddingTargetFrameCount(1280, 720)).toBe(15)
|
|
expect(getGemmaEmbeddingTargetFrameCount(854, 480)).toBe(15)
|
|
// 9:16
|
|
expect(getGemmaEmbeddingTargetFrameCount(1080, 1920)).toBe(15)
|
|
// 1:1
|
|
expect(getGemmaEmbeddingTargetFrameCount(1080, 1080)).toBe(15)
|
|
expect(getGemmaEmbeddingTargetFrameCount(480, 480)).toBe(15)
|
|
// 4:3
|
|
expect(getGemmaEmbeddingTargetFrameCount(1440, 1080)).toBe(15)
|
|
expect(getGemmaEmbeddingTargetFrameCount(640, 480)).toBe(15)
|
|
// 3:4
|
|
expect(getGemmaEmbeddingTargetFrameCount(1080, 1440)).toBe(15)
|
|
// 21:9
|
|
expect(getGemmaEmbeddingTargetFrameCount(2560, 1080)).toBe(15)
|
|
expect(getGemmaEmbeddingTargetFrameCount(3440, 1440)).toBe(15)
|
|
})
|
|
|
|
it('should return 14 for non-standard aspect ratios and missing/invalid dimensions', () => {
|
|
expect(getGemmaEmbeddingTargetFrameCount(1000, 600)).toBe(14) // 5:3
|
|
expect(getGemmaEmbeddingTargetFrameCount(700, 500)).toBe(14) // 1.4:1
|
|
expect(getGemmaEmbeddingTargetFrameCount(854, 672)).toBe(14) // ~1.27:1
|
|
expect(getGemmaEmbeddingTargetFrameCount(undefined, undefined)).toBe(14)
|
|
expect(getGemmaEmbeddingTargetFrameCount(0, 0)).toBe(14)
|
|
expect(getGemmaEmbeddingTargetFrameCount(-100, 100)).toBe(14)
|
|
})
|
|
})
|
|
|
|
it('should sample uniform 15 frames when chunk archive contains standard 16:9 frames', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.3) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 140 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
const sampleJpg = await sharp({
|
|
create: {
|
|
width: 160,
|
|
height: 90,
|
|
channels: 3,
|
|
background: { r: 0, g: 0, b: 0 },
|
|
},
|
|
})
|
|
.jpeg()
|
|
.toBuffer()
|
|
|
|
const frames: Record<string, Buffer> = {}
|
|
for (let i = 1; i <= 30; i++) {
|
|
frames[`frame_${String(i).padStart(4, '0')}.jpg`] = sampleJpg
|
|
}
|
|
const sampleArchive = new Bun.Archive(frames)
|
|
const archiveBytes = await sampleArchive.bytes()
|
|
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from(archiveBytes.buffer, archiveBytes.byteOffset, archiveBytes.byteLength),
|
|
contentType: 'application/x-tar',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
|
|
})
|
|
|
|
expect(res.embedding).toHaveLength(768)
|
|
const requestBody = JSON.parse(mockFetch.mock.calls[0][1].body)
|
|
expect(requestBody.input).toHaveLength(15)
|
|
})
|
|
|
|
it('should fallback to 14 frames when chunk archive contains non-standard or unparseable frames', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.3) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 140 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
const frames: Record<string, Buffer> = {}
|
|
for (let i = 1; i <= 30; i++) {
|
|
frames[`frame_${String(i).padStart(4, '0')}.jpg`] = Buffer.from(`frame-${i}`)
|
|
}
|
|
const sampleArchive = new Bun.Archive(frames)
|
|
const archiveBytes = await sampleArchive.bytes()
|
|
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from(archiveBytes.buffer, archiveBytes.byteOffset, archiveBytes.byteLength),
|
|
contentType: 'application/x-tar',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
|
|
})
|
|
|
|
expect(res.embedding).toHaveLength(768)
|
|
const requestBody = JSON.parse(mockFetch.mock.calls[0][1].body)
|
|
expect(requestBody.input).toHaveLength(14)
|
|
})
|
|
|
|
it('should throw non-retryable ApplicationFailure when chunk archive contains no valid frames', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const sampleArchive = new Bun.Archive({
|
|
'info.txt': Buffer.from('not an image'),
|
|
})
|
|
const archiveBytes = await sampleArchive.bytes()
|
|
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from(archiveBytes.buffer, archiveBytes.byteOffset, archiveBytes.byteLength),
|
|
contentType: 'application/x-tar',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
await expect(
|
|
generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
|
|
}),
|
|
).rejects.toThrow('No extracted frames found in chunk archive')
|
|
})
|
|
|
|
it('should throw non-retryable ApplicationFailure when chunk archive data is corrupted', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from('corrupted non-tar bytes'),
|
|
contentType: 'application/x-tar',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
await expect(
|
|
generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
|
|
}),
|
|
).rejects.toThrow('Failed to read chunk archive')
|
|
})
|
|
|
|
it('should throw non-retryable ApplicationFailure when an extracted frame is empty (0 bytes)', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const sampleArchive = new Bun.Archive({
|
|
'frame_0001.jpg': Buffer.alloc(0),
|
|
})
|
|
const archiveBytes = await sampleArchive.bytes()
|
|
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from(archiveBytes.buffer, archiveBytes.byteOffset, archiveBytes.byteLength),
|
|
contentType: 'application/x-tar',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
await expect(
|
|
generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
|
|
}),
|
|
).rejects.toThrow('is empty (0 bytes)')
|
|
})
|
|
})
|
|
|
|
describe('AI Database Activities Integration', () => {
|
|
setupTestDbHooks()
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests
|
|
let team: any
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests
|
|
let user: any
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests
|
|
let asset: any
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests
|
|
let storageKey: any
|
|
|
|
beforeEach(async () => {
|
|
vi.restoreAllMocks()
|
|
|
|
team = await prisma.team.create({
|
|
data: { name: 'AI Team' },
|
|
})
|
|
|
|
user = await prisma.user.create({
|
|
data: {
|
|
name: 'AI Agent User',
|
|
email: 'aiagent@shumai.ai',
|
|
type: 'agent',
|
|
},
|
|
})
|
|
|
|
// Add user as a member of the team
|
|
await prisma.teamMember.create({
|
|
data: {
|
|
teamId: team.id,
|
|
userId: user.id,
|
|
role: 'editor',
|
|
},
|
|
})
|
|
|
|
storageKey = await prisma.storageKey.create({
|
|
data: {
|
|
key: 'media/video.mp4',
|
|
},
|
|
})
|
|
|
|
asset = await prisma.asset.create({
|
|
data: {
|
|
name: 'video.mp4',
|
|
type: AssetType.file,
|
|
status: AssetStatus.uploaded,
|
|
mediaType: 'video/mp4',
|
|
storageKeyId: storageKey.id,
|
|
},
|
|
})
|
|
})
|
|
|
|
describe('getEmbeddingContextActivity', () => {
|
|
it('should retrieve embedding context and throw if embedding agent not configured/enabled', async () => {
|
|
// Expect throw since agent not created yet
|
|
await expect(
|
|
getEmbeddingContextActivity({ teamId: team.id, assetId: asset.id }),
|
|
).rejects.toThrow('embedding feature is disabled or agent not found')
|
|
|
|
// Create embedding agent
|
|
await prisma.agent.create({
|
|
data: {
|
|
id: user.id, // match user.id
|
|
teamId: team.id,
|
|
type: 'embedding',
|
|
enabled: true,
|
|
config: {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
},
|
|
},
|
|
})
|
|
|
|
const ctx = await getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
})
|
|
|
|
expect(ctx.agent.id).toBe(user.id)
|
|
expect(ctx.asset.id).toBe(asset.id)
|
|
expect(ctx.asset.mediaType).toBe('video/mp4')
|
|
|
|
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
|
try {
|
|
await expect(
|
|
getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
}),
|
|
).rejects.toThrow('embedding feature is disabled or agent not found')
|
|
} finally {
|
|
delete process.env.ENABLE_EMBEDDING_AGENT
|
|
}
|
|
})
|
|
|
|
it('should parse valid positive chunk duration and fallback on invalid or negative ones', async () => {
|
|
// Create embedding agent if not already present
|
|
const existingAgent = await prisma.agent.findUnique({ where: { id: user.id } })
|
|
if (!existingAgent) {
|
|
await prisma.agent.create({
|
|
data: {
|
|
id: user.id,
|
|
teamId: team.id,
|
|
type: 'embedding',
|
|
enabled: true,
|
|
config: {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
},
|
|
},
|
|
})
|
|
}
|
|
|
|
// Test default/fallback
|
|
delete process.env.EMBEDDING_CHUNK_DURATION
|
|
let ctx = await getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
})
|
|
expect(ctx.chunkDuration).toBe(60.0)
|
|
expect(ctx.chunkOverlap).toBe(5.0)
|
|
|
|
// Test valid positive
|
|
process.env.EMBEDDING_CHUNK_DURATION = '45.5'
|
|
process.env.EMBEDDING_CHUNK_OVERLAP = '10.0'
|
|
ctx = await getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
})
|
|
expect(ctx.chunkDuration).toBe(45.5)
|
|
expect(ctx.chunkOverlap).toBe(10.0)
|
|
|
|
// Test negative/invalid for overlap
|
|
process.env.EMBEDDING_CHUNK_OVERLAP = '-5.0'
|
|
ctx = await getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
})
|
|
expect(ctx.chunkOverlap).toBe(5.0)
|
|
|
|
process.env.EMBEDDING_CHUNK_OVERLAP = 'invalid'
|
|
ctx = await getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
})
|
|
expect(ctx.chunkOverlap).toBe(5.0)
|
|
|
|
// Cleanup env
|
|
delete process.env.EMBEDDING_CHUNK_DURATION
|
|
delete process.env.EMBEDDING_CHUNK_OVERLAP
|
|
})
|
|
|
|
it('should return existing embeddings for the asset', async () => {
|
|
// Ensure agent exists
|
|
await prisma.agent.upsert({
|
|
where: { id: user.id },
|
|
update: {},
|
|
create: {
|
|
id: user.id,
|
|
teamId: team.id,
|
|
type: 'embedding',
|
|
enabled: true,
|
|
config: { provider: 'openai', model: 'gpt-4' },
|
|
},
|
|
})
|
|
|
|
await saveAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
embeddings: [
|
|
{ embedding: Array(1536).fill(0.01), startTime: 0.0, endTime: 60.0 },
|
|
{ embedding: Array(768).fill(0.02), startTime: 55.0, endTime: 115.0 },
|
|
],
|
|
})
|
|
|
|
const ctx = await getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
})
|
|
|
|
expect(ctx.existingEmbeddings).toHaveLength(2)
|
|
const chunk1 = ctx.existingEmbeddings.find((e) => e.startTime === 0)
|
|
expect(chunk1).toBeDefined()
|
|
expect(chunk1?.has1536).toBe(true)
|
|
expect(chunk1?.has768).toBe(false)
|
|
|
|
const chunk2 = ctx.existingEmbeddings.find((e) => e.startTime === 55)
|
|
expect(chunk2).toBeDefined()
|
|
expect(chunk2?.has1536).toBe(false)
|
|
expect(chunk2?.has768).toBe(true)
|
|
})
|
|
})
|
|
|
|
describe('saveAssetEmbeddingsActivity', () => {
|
|
it('should save embeddings with start and end times to the database', async () => {
|
|
const embeddings = [
|
|
{
|
|
embedding: Array(1536).fill(0.01),
|
|
startTime: 0.0,
|
|
endTime: 60.0,
|
|
},
|
|
{
|
|
embedding: Array(1536).fill(0.02),
|
|
},
|
|
]
|
|
|
|
await saveAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
embeddings,
|
|
})
|
|
|
|
// Query raw embeddings from DB
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- db query output is a raw postgres result array typed as any
|
|
const dbEmbeddings: any[] = await prisma.$queryRaw`
|
|
SELECT id, asset_id as "assetId", start_time as "startTime", end_time as "endTime"
|
|
FROM asset_embeddings
|
|
WHERE asset_id = ${asset.id}
|
|
ORDER BY start_time ASC NULLS LAST
|
|
`
|
|
|
|
expect(dbEmbeddings.length).toBe(2)
|
|
expect(dbEmbeddings[0].startTime).toBe(0.0)
|
|
expect(dbEmbeddings[0].endTime).toBe(60.0)
|
|
expect(dbEmbeddings[1].startTime).toBeNull()
|
|
})
|
|
|
|
it('should save 768-dim embeddings to embedding_768 column in database', async () => {
|
|
const embeddings = [
|
|
{
|
|
embedding: Array(768).fill(0.01),
|
|
startTime: 0.0,
|
|
endTime: 60.0,
|
|
},
|
|
{
|
|
embedding: Array(768).fill(0.02),
|
|
},
|
|
]
|
|
|
|
await saveAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
embeddings,
|
|
})
|
|
|
|
// Query raw embeddings from DB
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- db query output is a raw postgres result array typed as any
|
|
const dbEmbeddings: any[] = await prisma.$queryRaw`
|
|
SELECT id, asset_id as "assetId", (embedding_768 IS NOT NULL) as "has768", (embedding IS NOT NULL) as "has1536"
|
|
FROM asset_embeddings
|
|
WHERE asset_id = ${asset.id}
|
|
`
|
|
|
|
expect(dbEmbeddings.length).toBe(2)
|
|
expect(dbEmbeddings[0].has768).toBe(true)
|
|
expect(dbEmbeddings[0].has1536).toBe(false)
|
|
expect(dbEmbeddings[1].has768).toBe(true)
|
|
expect(dbEmbeddings[1].has1536).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('deleteAssetEmbeddingsActivity', () => {
|
|
it('should delete specific embeddings by id', async () => {
|
|
await saveAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
embeddings: [
|
|
{ embedding: Array(1536).fill(0.01), startTime: 0, endTime: 60 },
|
|
{ embedding: Array(1536).fill(0.02), startTime: 55, endTime: 115 },
|
|
],
|
|
})
|
|
|
|
const before = await prisma.assetEmbedding.findMany({
|
|
where: { assetId: asset.id },
|
|
})
|
|
expect(before).toHaveLength(2)
|
|
|
|
const targetId = before[0].id
|
|
await deleteAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
ids: [targetId],
|
|
})
|
|
|
|
const after = await prisma.assetEmbedding.findMany({
|
|
where: { assetId: asset.id },
|
|
})
|
|
expect(after).toHaveLength(1)
|
|
expect(after[0].id).not.toBe(targetId)
|
|
})
|
|
|
|
it('should delete all embeddings for an asset when ids is not provided', async () => {
|
|
await saveAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
embeddings: [
|
|
{ embedding: Array(1536).fill(0.01), startTime: 0, endTime: 60 },
|
|
{ embedding: Array(1536).fill(0.02), startTime: 55, endTime: 115 },
|
|
],
|
|
})
|
|
|
|
await deleteAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
})
|
|
|
|
const after = await prisma.assetEmbedding.findMany({
|
|
where: { assetId: asset.id },
|
|
})
|
|
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)
|
|
}
|
|
})
|
|
})
|
|
})
|