diff --git a/AGENTS.md b/AGENTS.md index 2c866f0a..adc14c41 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -304,6 +304,24 @@ We use a custom workflow engine that supports both **Local** (polling-based) and - `TemporalExecutor`: Submits tasks to a Temporal cluster. 4. **Automatic Submission**: New `WorkflowTask` records are automatically submitted to the `WorkflowService` via a Prisma Client Extension defined in `src/db.ts`. +### Non-Retryable Error Handling + +To prevent Temporal from indefinitely retrying fatal, expected business validation failures (e.g., missing records, invalid configurations, missing parameters), **never throw standard `Error` objects from workflow or activity logic.** Instead, throw a non-retryable `ApplicationFailure`. + +- **Workflow Boundary**: In workflows, import `ApplicationFailure` from `@temporalio/workflow`: + ```typescript + import { ApplicationFailure } from '@temporalio/workflow' + throw ApplicationFailure.create({ message: 'agentId missing in payload', nonRetryable: true }) + ``` +- **Activity Boundary**: In activities, import `ApplicationFailure` from `@temporalio/activity`: + ```typescript + import { ApplicationFailure } from '@temporalio/activity' + throw ApplicationFailure.create({ + message: 'no autofill agent found for team', + nonRetryable: true, + }) + ``` + ### Temporal Workflow Patterns - **Definition**: Define workflows as exported async functions. diff --git a/src/workflow/activities/db.ts b/src/workflow/activities/db.ts index 521ed10b..d7e20f57 100644 --- a/src/workflow/activities/db.ts +++ b/src/workflow/activities/db.ts @@ -1,4 +1,5 @@ import { prisma } from '@/db' +import { ApplicationFailure } from '@temporalio/activity' import type { AgentMessage, SessionTreeEntry } from '@earendil-works/pi-agent-core' import { ulid } from 'ulid' import { metadataService } from '@/services/metadata/metadata' @@ -295,7 +296,9 @@ export async function getAgentChatContextActivity(params: GetAgentChatContextPar const team = await prisma.team.findUnique({ where: { id: params.teamId }, }) - if (!team) throw new Error('failed to get team') + if (!team) { + throw ApplicationFailure.create({ message: 'failed to get team', nonRetryable: true }) + } const agent = await prisma.agent.findUnique({ where: { id: params.agentId }, @@ -305,11 +308,24 @@ export async function getAgentChatContextActivity(params: GetAgentChatContextPar }, }) if (!agent) { - throw new Error(`agent ${params.agentId} not found`) + throw ApplicationFailure.create({ + message: `agent ${params.agentId} not found`, + nonRetryable: true, + }) } - if (!agent.provider) throw new Error('agent has no provider configured') - if (!agent.modelRef) throw new Error('agent has no model configured') + if (!agent.provider) { + throw ApplicationFailure.create({ + message: 'agent has no provider configured', + nonRetryable: true, + }) + } + if (!agent.modelRef) { + throw ApplicationFailure.create({ + message: 'agent has no model configured', + nonRetryable: true, + }) + } const providerName = agent.provider.name @@ -350,13 +366,18 @@ export async function getAgentAutofillContextActivity(params: GetAgentAutofillCo }, }) if (!agent) { - throw new Error('no autofill agent found for team') + throw ApplicationFailure.create({ + message: 'no autofill agent found for team', + nonRetryable: true, + }) } const team = await prisma.team.findUnique({ where: { id: params.teamId }, }) - if (!team) throw new Error('failed to get team') + if (!team) { + throw ApplicationFailure.create({ message: 'failed to get team', nonRetryable: true }) + } // Find provider/model configuration const agentWithDetails = await prisma.agent.findUnique({ @@ -366,9 +387,21 @@ export async function getAgentAutofillContextActivity(params: GetAgentAutofillCo modelRef: true, }, }) - if (!agentWithDetails) throw new Error(`agent ${agent.id} not found`) - if (!agentWithDetails.provider) throw new Error('agent has no provider configured') - if (!agentWithDetails.modelRef) throw new Error('agent has no model configured') + if (!agentWithDetails) { + throw ApplicationFailure.create({ message: `agent ${agent.id} not found`, nonRetryable: true }) + } + if (!agentWithDetails.provider) { + throw ApplicationFailure.create({ + message: 'agent has no provider configured', + nonRetryable: true, + }) + } + if (!agentWithDetails.modelRef) { + throw ApplicationFailure.create({ + message: 'agent has no model configured', + nonRetryable: true, + }) + } const providerName = agentWithDetails.provider.name @@ -405,7 +438,9 @@ export async function getEmbeddingContextActivity(params: GetEmbeddingContextPar const team = await prisma.team.findUnique({ where: { id: params.teamId }, }) - if (!team) throw new Error('failed to get team') + if (!team) { + throw ApplicationFailure.create({ message: 'failed to get team', nonRetryable: true }) + } const agent = await prisma.agent.findFirst({ where: { @@ -415,24 +450,46 @@ export async function getEmbeddingContextActivity(params: GetEmbeddingContextPar }, }) if (!agent) { - throw new Error('embedding feature is disabled or agent not found') + throw ApplicationFailure.create({ + message: 'embedding feature is disabled or agent not found', + nonRetryable: true, + }) } const config = agent.config as unknown as PrismaJson.AgentConfig - if (!config.provider) throw new Error('embedding provider not configured') - if (!config.model) throw new Error('embedding model not configured') + if (!config.provider) { + throw ApplicationFailure.create({ + message: 'embedding provider not configured', + nonRetryable: true, + }) + } + if (!config.model) { + throw ApplicationFailure.create({ + message: 'embedding model not configured', + nonRetryable: true, + }) + } const asset = await prisma.asset.findUnique({ where: { id: params.assetId }, include: { storageKey: true }, }) - if (!asset) throw new Error('failed to get asset') - if (!asset.mediaType) throw new Error('asset has no media type') + if (!asset) { + throw ApplicationFailure.create({ message: 'failed to get asset', nonRetryable: true }) + } + if (!asset.mediaType) { + throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true }) + } const dbProvider = await prisma.provider.findFirst({ where: { teamId: params.teamId, name: config.provider }, }) - if (!dbProvider) throw new Error(`Provider ${config.provider} not found in database`) + if (!dbProvider) { + throw ApplicationFailure.create({ + message: `Provider ${config.provider} not found in database`, + nonRetryable: true, + }) + } return { agent, diff --git a/src/workflow/workflow.test.ts b/src/workflow/workflow.test.ts index 0271ad41..b45acbed 100644 --- a/src/workflow/workflow.test.ts +++ b/src/workflow/workflow.test.ts @@ -139,4 +139,49 @@ describe('WorkflowService', () => { // Even if it fails due to missing API keys, the fact that it's no longer 'pending' means the workflow was triggered. expect(finishedTask?.status).not.toBe(WorkflowTaskStatus.pending) }, 15000) + + it('should propagate ApplicationFailure correctly in local executor', async () => { + // Creating an ai_embedding task without any embedding agent configured for the team + const team = await prisma.team.create({ + data: { name: 'Failure Team' }, + }) + const project = await prisma.project.create({ + data: { name: 'Failure Project', teamId: team.id }, + }) + const asset = await prisma.asset.create({ + data: { + name: 'test.png', + storageKey: { create: { key: 'test/failure-test.png' } }, + status: 'uploaded', + type: 'file', + mediaType: 'image/png', + project: { connect: { id: project.id } }, + }, + }) + + const task = await prisma.workflowTask.create({ + data: { + assetId: asset.id, + type: WorkflowTaskType.ai_embedding, + status: WorkflowTaskStatus.pending, + teamId: team.id, + }, + }) + + let finishedTask = null + for (let i = 0; i < 20; i++) { + finishedTask = await prisma.workflowTask.findUnique({ + where: { id: task.id }, + }) + if (finishedTask?.status === WorkflowTaskStatus.failed) { + break + } + await new Promise((resolve) => setTimeout(resolve, 500)) + } + + expect(finishedTask?.status).toBe(WorkflowTaskStatus.failed) + expect((finishedTask?.output as Record)?.error).toBe( + 'embedding feature is disabled or agent not found', + ) + }, 15000) }) diff --git a/src/workflow/workflows/agent-autofill.ts b/src/workflow/workflows/agent-autofill.ts index 6399858b..658d8bff 100644 --- a/src/workflow/workflows/agent-autofill.ts +++ b/src/workflow/workflows/agent-autofill.ts @@ -1,3 +1,4 @@ +import { ApplicationFailure } from '@temporalio/workflow' import type { WorkflowTask } from '@/generated/prisma/client' import { getActivities, @@ -50,7 +51,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise { const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId) const key = asset?.storageKey?.key if (!asset || !asset.project || !key) { - throw new Error('Asset or project not found') + throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true }) } const teamId = asset.project.teamId const projectId = asset.project.id diff --git a/src/workflow/workflows/agent-chat.ts b/src/workflow/workflows/agent-chat.ts index 95be1b34..5e5cc8c7 100644 --- a/src/workflow/workflows/agent-chat.ts +++ b/src/workflow/workflows/agent-chat.ts @@ -1,3 +1,4 @@ +import { ApplicationFailure } from '@temporalio/workflow' import type { WorkflowTask } from '@/generated/prisma/client' import { executeActivity, @@ -31,18 +32,29 @@ export async function agentChat(task: WorkflowTask): Promise { }) const payload = task.payload - if (!payload) throw new Error('Task payload is missing') + if (!payload) { + throw ApplicationFailure.create({ message: 'Task payload is missing', nonRetryable: true }) + } const agentId = payload.agent?.agentId - if (!agentId) throw new Error('agentId missing in payload') + if (!agentId) { + throw ApplicationFailure.create({ message: 'agentId missing in payload', nonRetryable: true }) + } let sessionId = payload.agent?.sessionId // 1. Get User Comment const userCommentId = payload.agent?.userCommentId - if (!userCommentId) throw new Error('userCommentId missing in payload') + if (!userCommentId) { + throw ApplicationFailure.create({ + message: 'userCommentId missing in payload', + nonRetryable: true, + }) + } const userComment = await executeActivity(TaskQueueDb, getCommentActivity, userCommentId) - if (!userComment) throw new Error('User comment not found') + if (!userComment) { + throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true }) + } // 2. Create Placeholder Comment const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, { @@ -57,7 +69,7 @@ export async function agentChat(task: WorkflowTask): Promise { // 3. Get Asset const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId) if (!asset || !asset.project) { - throw new Error('Asset or project not found') + throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true }) } const teamId = asset.project.teamId diff --git a/src/workflow/workflows/agent-embedding.ts b/src/workflow/workflows/agent-embedding.ts index 3eae9e3d..ebd20117 100644 --- a/src/workflow/workflows/agent-embedding.ts +++ b/src/workflow/workflows/agent-embedding.ts @@ -1,3 +1,4 @@ +import { ApplicationFailure } from '@temporalio/workflow' import type { WorkflowTask } from '@/generated/prisma/client' import { getActivities, executeActivity, TaskQueueDb, TaskQueueAgent } from '../workflow-utils' @@ -32,7 +33,9 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise { }) placeholderCommentId = placeholder.id - if (!task.teamId) throw new Error('Task has no teamId') + if (!task.teamId) { + throw ApplicationFailure.create({ message: 'Task has no teamId', nonRetryable: true }) + } // 1. Fetch Agent Context (Database Activity on db_queue) const context = await executeActivity(TaskQueueDb, getEmbeddingContextActivity, { diff --git a/src/workflow/workflows/ai-transcription.ts b/src/workflow/workflows/ai-transcription.ts index 84959eec..7538fbfd 100644 --- a/src/workflow/workflows/ai-transcription.ts +++ b/src/workflow/workflows/ai-transcription.ts @@ -1,3 +1,4 @@ +import { ApplicationFailure } from '@temporalio/workflow' import type { WorkflowTask } from '@/generated/prisma/client' import { getActivities, @@ -44,7 +45,7 @@ export async function aiTranscriptionMedia(task: WorkflowTask): Promise { const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId) const key = asset?.storageKey?.key if (!asset || !key) { - throw new Error('Asset not found') + throw ApplicationFailure.create({ message: 'Asset not found', nonRetryable: true }) } // 2. Extract Audio (Requires FFmpeg)