{{ message }}
Repository navigation
Expand file tree
/
Copy pathworkflow-execution.ts
More file actions
418 lines (379 loc) · 16.1 KB
/
Copy pathworkflow-execution.ts
File metadata and controls
418 lines (379 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import { trace } from '@opentelemetry/api'
import {
parsePrincipal,
type SerializedPrincipalV1,
type WorkflowExecutionPrincipal,
} from '@sim/auth/principal'
import { createLogger, runWithRequestContext } from '@sim/logger'
import { toError } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { task, timeout } from '@trigger.dev/sdk'
import {
refreshExecutionSlotExpiry,
releaseExecutionSlot,
} from '@/lib/billing/calculations/usage-reservation'
import {
assertBillingAttributionSnapshot,
type BillingAttributionSnapshot,
} from '@/lib/billing/core/attribution'
import { getDeterministicAdmissionRejectionCode } from '@/lib/core/admission/rejection'
import { isReservationHeadroomDenial } from '@/lib/core/admission/transient-failure'
import { buildRecordedJobFailureResult } from '@/lib/core/async-jobs/recorded-failure'
import type { AsyncExecutionCorrelation } from '@/lib/core/async-jobs/types'
import type { ExecutionScope } from '@/lib/core/errors/execution-scope-deleted'
import { logFailureOnce } from '@/lib/core/errors/failure-log'
import {
capExecutionTimeoutMs,
createTimeoutAbortController,
ExecutionTimeoutError,
getAsyncExecutionTimeoutForBillingAttribution,
getExecutionDeadlineAt,
getTimeoutErrorMessage,
RESERVATION_TTL_BUFFER_MS,
} from '@/lib/core/execution-limits'
import type { RequestAttribution } from '@/lib/core/utils/request-attribution'
import {
isWorkflowStateRejection,
type PreprocessExecutionError,
preprocessExecution,
RATE_LIMIT_EXCEEDED_CODE,
} from '@/lib/execution/preprocessing'
import { LoggingSession } from '@/lib/logs/execution/logging-session'
import { buildTraceSpans } from '@/lib/logs/execution/trace-spans/trace-spans'
import { cleanupExecutionBase64Cache } from '@/lib/uploads/utils/user-file-base64.server'
import { executeWorkflowCore } from '@/lib/workflows/executor/execution-core'
import { handlePostExecutionPauseState } from '@/lib/workflows/executor/pause-persistence'
import {
isRecordedWorkflowFailure,
resolveDeletedExecutionScope,
} from '@/lib/workflows/executor/recorded-failure'
import { WORKFLOW_EXECUTION_CONCURRENCY_LIMIT } from '@/background/concurrency-limits'
import { ExecutionSnapshot } from '@/executor/execution/snapshot'
import type { ExecutionMetadata } from '@/executor/execution/types'
import { hasExecutionResult } from '@/executor/utils/errors'
import type { ResolvedSecretTraceProvenanceV1 } from '@/executor/utils/resolved-secret-trace-registry'
import type { CoreTriggerType } from '@/stores/logs/filters/types'
const logger = createLogger('TriggerWorkflowExecution')
const LEGACY_WORKFLOW_JOB_SESSION_ID = 'legacy-queued-workflow'
export function buildWorkflowCorrelation(
payload: WorkflowExecutionJobPayload
): AsyncExecutionCorrelation {
const executionId = payload.executionId || generateId()
const requestId = payload.requestId || payload.correlation?.requestId || executionId.slice(0, 8)
return {
executionId,
requestId,
source: 'workflow',
workflowId: payload.workflowId,
...(payload.correlation?.copilotToolCallId
? { copilotToolCallId: payload.correlation.copilotToolCallId }
: {}),
triggerType: payload.triggerType || payload.correlation?.triggerType || 'api',
}
}
export type WorkflowExecutionPayload = {
workflowId: string
principal: SerializedPrincipalV1
userId: string
billingAttribution: BillingAttributionSnapshot
workspaceId: string
input?: any
triggerType?: CoreTriggerType
triggerBlockId?: string
executionId?: string
requestId?: string
correlation?: AsyncExecutionCorrelation
metadata?: Record<string, any>
callChain?: string[]
/** Who queued the run, restored into the job's context so its events stay attributed. */
attribution?: RequestAttribution
executionMode?: 'sync' | 'stream' | 'async'
/** Upstream preprocessing already consumed rate-limit quota and owns the usage reservation. */
admissionCompleted?: boolean
/** Optional trusted cap already resolved by the async API admission boundary. */
executionTimeoutMs?: number
/** Authenticated input provenance validated by the workflow execution boundary. */
trustedInitialResolvedSecretTraceProvenance?: ResolvedSecretTraceProvenanceV1
/**
* Identity decisions the enqueuing surface already made. They must ride the
* payload because the worker has no request to re-derive them from, and a
* queued run that dropped them would resolve its personal variables as the
* workflow owner while still authorizing workspace variables as the actor.
*/
enforceCredentialAccess?: boolean
isPublicApiAccess?: boolean
}
type LegacyWorkflowExecutionPayload = Omit<WorkflowExecutionPayload, 'principal'> & {
/** Jobs queued before execution principals were introduced omit this field. */
principal?: undefined
}
type WorkflowExecutionJobPayload = WorkflowExecutionPayload | LegacyWorkflowExecutionPayload
/**
* Whether a preprocessing rejection is an outcome of the workflow's or account's state rather
* than a fault. A workflow-state rejection writes no execution log, so it completes at once. A
* quota or account rejection (exhausted usage, spent headroom, rate limit, suspended account)
* writes one, so it completes only once that log is saved; an unsaved one (an outage) still fails
* the job and alerts. A retryable rejection and every other failure fail the job.
*/
function isNonFaultPreprocessingRejection(
rejection: PreprocessExecutionError,
rejectionLogged: boolean
): boolean {
if (rejection.retryable === true) return false
if (isWorkflowStateRejection(rejection)) return true
const quotaRejection =
getDeterministicAdmissionRejectionCode(rejection) !== undefined ||
isReservationHeadroomDenial(rejection) ||
rejection.code === RATE_LIMIT_EXCEEDED_CODE
return quotaRejection && rejectionLogged
}
/** Completes the job with a failure already in the execution log, keeping it on the run's span. */
function completeWithRecordedFailure(workflowId: string, executionId: string, error: unknown) {
const failure = toError(error)
trace.getActiveSpan()?.recordException(failure)
return buildRecordedJobFailureResult({ workflowId, executionId, error: failure.message })
}
function requireLegacyWorkflowJobString(value: unknown, field: string): string {
if (typeof value !== 'string' || !value.trim()) {
throw new Error(`Legacy workflow job ${field} must be a non-empty string`)
}
return value
}
/** Restores only the actor decision recorded by the pre-principal queue payload. */
function parseWorkflowJobPrincipal(
payload: WorkflowExecutionJobPayload
): WorkflowExecutionPrincipal {
if (payload.principal !== undefined) return parsePrincipal(payload.principal)
const workflowId = requireLegacyWorkflowJobString(payload.workflowId, 'workflowId')
const workspaceId = requireLegacyWorkflowJobString(payload.workspaceId, 'workspaceId')
if (payload.enforceCredentialAccess === true) {
return {
kind: 'session',
userId: requireLegacyWorkflowJobString(payload.userId, 'userId'),
sessionId: LEGACY_WORKFLOW_JOB_SESSION_ID,
}
}
return { kind: 'system', serviceId: 'internal', workspaceId, workflowId }
}
/**
* Background workflow execution job
* @see preprocessExecution For detailed information on preprocessing checks
* @see executeWorkflowCore For the core workflow execution logic
*/
export async function executeWorkflowJob(
payload: WorkflowExecutionJobPayload,
externalAbortSignal?: AbortSignal
) {
const workflowId = payload.workflowId
const correlation = buildWorkflowCorrelation(payload)
const executionId = correlation.executionId
const requestId = correlation.requestId
let principal
let billingAttribution: BillingAttributionSnapshot
try {
principal = parseWorkflowJobPrincipal(payload)
billingAttribution = assertBillingAttributionSnapshot(payload.billingAttribution)
if (
billingAttribution.actorUserId !== payload.userId ||
billingAttribution.workspaceId !== payload.workspaceId
) {
throw new Error('Workflow job billing attribution does not match its actor and workspace')
}
} catch (error) {
await releaseExecutionSlot(executionId)
throw error
}
const timeoutController = createTimeoutAbortController(
capExecutionTimeoutMs(
getAsyncExecutionTimeoutForBillingAttribution(billingAttribution),
payload.executionTimeoutMs
),
externalAbortSignal
)
try {
const executionDeadlineAt = getExecutionDeadlineAt(timeoutController.signal)?.getTime()
let admissionCompleted = payload.admissionCompleted === true
if (admissionCompleted && executionDeadlineAt !== undefined) {
admissionCompleted = await refreshExecutionSlotExpiry(
executionId,
executionDeadlineAt + RESERVATION_TTL_BUFFER_MS
)
if (!admissionCompleted) {
logger.warn('Queued workflow reservation expired; repeating usage admission', {
workflowId,
executionId,
})
}
}
return await runWithRequestContext({ requestId, ...payload.attribution }, async () => {
logger.info(`[${requestId}] Starting workflow execution job: ${workflowId}`, {
userId: payload.userId,
triggerType: payload.triggerType,
executionId,
})
const triggerType = (correlation.triggerType || 'api') as CoreTriggerType
const loggingSession = new LoggingSession(workflowId, executionId, triggerType, requestId)
if (correlation.copilotToolCallId) {
loggingSession.setTrustedExecutionCorrelation(correlation)
}
loggingSession.setExecutionDeadlineAt(getExecutionDeadlineAt(timeoutController.signal))
let preprocessingRejection: PreprocessExecutionError | undefined
try {
const preprocessResult = await preprocessExecution({
workflowId: payload.workflowId,
userId: payload.userId,
triggerType: triggerType,
executionId: executionId,
requestId: requestId,
checkRateLimit: !admissionCompleted,
checkDeployment: true,
skipUsageLimits: admissionCompleted,
loggingSession: loggingSession,
triggerData: { correlation },
billingAttribution,
executionType: 'async',
executionDeadlineAt,
})
if (!preprocessResult.success) {
logger.error(`[${requestId}] Preprocessing failed: ${preprocessResult.error?.message}`, {
workflowId,
statusCode: preprocessResult.error?.statusCode,
})
preprocessingRejection = preprocessResult.error
throw new Error(preprocessResult.error?.message || 'Preprocessing failed')
}
const actorUserId = preprocessResult.actorUserId!
const workspaceId = preprocessResult.workflowRecord?.workspaceId
if (!workspaceId) {
throw new Error(`Workflow ${workflowId} has no associated workspace`)
}
logger.info(`[${requestId}] Preprocessing passed. Using actor: ${actorUserId}`)
const workflow = preprocessResult.workflowRecord!
const metadata: ExecutionMetadata = {
requestId,
executionId,
workflowId,
workspaceId,
userId: actorUserId,
principal,
billingAttribution: preprocessResult.billingAttribution,
sessionUserId: undefined,
workflowUserId: workflow.userId,
triggerType: payload.triggerType || 'api',
triggerBlockId: payload.triggerBlockId,
useDraftState: false,
startTime: new Date().toISOString(),
isClientSession: false,
enforceCredentialAccess: payload.enforceCredentialAccess ?? false,
isPublicApiAccess: payload.isPublicApiAccess ?? false,
callChain: payload.callChain,
correlation,
executionMode: payload.executionMode ?? 'async',
}
const snapshot = new ExecutionSnapshot(
metadata,
workflow,
payload.input,
workflow.variables || {},
[]
)
const result = await executeWorkflowCore({
snapshot,
callbacks: {},
loggingSession,
includeFileBase64: true,
base64MaxBytes: undefined,
abortSignal: timeoutController.signal,
trustedInitialResolvedSecretTraceProvenance:
payload.trustedInitialResolvedSecretTraceProvenance,
})
let timeoutError: ExecutionTimeoutError | undefined
if (
result.status === 'cancelled' &&
timeoutController.isTimedOut() &&
timeoutController.timeoutMs
) {
const timeoutErrorMessage = getTimeoutErrorMessage(timeoutController.timeoutMs)
logger.info(`[${requestId}] Workflow execution timed out`, {
timeoutMs: timeoutController.timeoutMs,
})
await loggingSession.markAsFailed(timeoutErrorMessage)
timeoutError = new ExecutionTimeoutError(timeoutErrorMessage)
} else {
await handlePostExecutionPauseState({ result, workflowId, executionId, loggingSession })
}
await loggingSession.waitForPostExecution()
if (timeoutError) throw timeoutError
logger.info(`[${requestId}] Workflow execution completed: ${workflowId}`, {
success: result.success,
executionTime: result.metadata?.duration,
executionId,
})
return {
success: result.success,
workflowId: payload.workflowId,
executionId,
output: result.output,
executedAt: new Date().toISOString(),
metadata: payload.metadata,
}
} catch (error: unknown) {
logFailureOnce(logger, `[${requestId}] Workflow execution failed: ${workflowId}`, error, {
metadata: () => loggingSession.projectDiagnosticError(error),
executionId,
})
const completeWithDeletedScope = (scope: ExecutionScope) => {
logger.info(`[${requestId}] Workflow execution ended: its ${scope} was deleted`, {
workflowId,
executionId,
})
return completeWithRecordedFailure(workflowId, executionId, error)
}
// Checked before the timeout: a deleted scope leaves nobody to alert about a slow run.
const deletedScope = await resolveDeletedExecutionScope(error, loggingSession)
if (deletedScope) return completeWithDeletedScope(deletedScope)
if (error instanceof ExecutionTimeoutError) throw error
// A failure core already recorded is the workflow's outcome, not a job fault; a run past
// its deadline (checked after the await, which can outlast it) still fails the job.
if (await isRecordedWorkflowFailure(error, executionId, loggingSession)) {
if (timeoutController.isTimedOut()) throw error
return completeWithRecordedFailure(workflowId, executionId, error)
}
const executionResult = hasExecutionResult(error) ? error.executionResult : undefined
const { traceSpans } = executionResult
? buildTraceSpans(executionResult)
: { traceSpans: [] }
await loggingSession.safeCompleteWithError({
error: {
message: toError(error).message,
stackTrace: error instanceof Error ? error.stack : undefined,
},
traceSpans,
executionState: executionResult?.executionState,
})
const scopeDeletedOnCompletion = loggingSession.getDeletedScope()
if (scopeDeletedOnCompletion) return completeWithDeletedScope(scopeDeletedOnCompletion)
if (
preprocessingRejection &&
isNonFaultPreprocessingRejection(preprocessingRejection, loggingSession.hasCompleted())
) {
return completeWithRecordedFailure(workflowId, executionId, error)
}
throw error
} finally {
void cleanupExecutionBase64Cache(executionId)
}
})
} finally {
timeoutController.cleanup()
}
}
export const workflowExecutionTask = task({
id: 'workflow-execution',
maxDuration: timeout.None,
machine: 'medium-2x',
queue: {
concurrencyLimit: WORKFLOW_EXECUTION_CONCURRENCY_LIMIT,
},
run: (payload: WorkflowExecutionJobPayload, { signal }) => executeWorkflowJob(payload, signal),
})
You can’t perform that action at this time.
