-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathexecution-core.ts
More file actions
926 lines (837 loc) · 30.2 KB
/
Copy pathexecution-core.ts
File metadata and controls
926 lines (837 loc) · 30.2 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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
/**
* Core workflow execution logic - shared by all execution paths
* This is the SINGLE source of truth for workflow execution
*/
import { db } from '@sim/db'
import { organization, workspace } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { filterUndefined, isPlainRecord, isRecordLike } from '@sim/utils/object'
import { mergeSubblockStateWithValues } from '@sim/workflow-persistence/subblocks'
import { eq } from 'drizzle-orm'
import type { Edge } from 'reactflow'
import { z } from 'zod'
import { type EffectivePiiRedaction, resolveEffectivePiiRedaction } from '@/lib/billing/retention'
import { getPersonalAndWorkspaceEnv } from '@/lib/environment/utils'
import { clearExecutionCancellation } from '@/lib/execution/cancellation'
import { warmLargeValueRefs } from '@/lib/execution/payloads/hydration'
import { parseLargeExecutionValue } from '@/lib/execution/payloads/large-execution-value'
import type { LoggingSession } from '@/lib/logs/execution/logging-session'
import { redactLargeValueRefsInValue } from '@/lib/logs/execution/pii-large-values'
import { redactObjectStrings } from '@/lib/logs/execution/pii-redaction'
import { buildTraceSpans } from '@/lib/logs/execution/trace-spans/trace-spans'
import { getUserEmailById } from '@/lib/users/queries'
import { getCustomBlockRowsForWorkspace } from '@/lib/workflows/custom-blocks/operations'
import {
loadDeployedWorkflowState,
loadWorkflowFromNormalizedTables,
} from '@/lib/workflows/persistence/utils'
import { TriggerUtils } from '@/lib/workflows/triggers/triggers'
import { updateWorkflowRunCounts } from '@/lib/workflows/utils'
import { withCustomBlockOverlay } from '@/blocks/custom/server-overlay'
import { Executor } from '@/executor'
import type { ExecutionSnapshot } from '@/executor/execution/snapshot'
import type {
ChildWorkflowContext,
ContextExtensions,
ExecutionCallbacks,
IterationContext,
SerializableExecutionState,
} from '@/executor/execution/types'
import type {
ExecutionResult,
NormalizedBlockOutput,
StartBlockRunMetadata,
} from '@/executor/types'
import { hasExecutionResult } from '@/executor/utils/errors'
import { isRunMetadataEnabled } from '@/executor/utils/start-block'
import { buildParallelSentinelEndId, buildSentinelEndId } from '@/executor/utils/subflow-utils'
import { Serializer } from '@/serializer'
const logger = createLogger('ExecutionCore')
const EnvVarsSchema = z.record(z.string(), z.string())
/**
* Surfaces the underlying driver error from a wrapped error chain.
*
* Drizzle wraps the original `postgres`/Node driver error as `error.cause`,
* which the logger's Error serializer drops (it only emits own-enumerable
* keys). Walking the chain from `error` itself and preferring the first error
* carrying a `code` exposes the diagnostic fields — notably the Postgres
* `code` — that distinguish a connection drop (`08006`), a rejected connection
* (`53300`), and a statement timeout (`57014`) behind an opaque "Failed query"
* message. Starting at `error` also captures a bare driver error that reaches
* this path unwrapped; when no error in the chain carries a `code`, it falls
* back to the first wrapped cause (the top-level error is already logged on its
* own, so it is not echoed here).
*/
function describeErrorCause(error: unknown): Record<string, unknown> | undefined {
try {
let driver: (Error & Record<string, unknown>) | undefined
let current: unknown = error
for (let depth = 0; depth < 10 && current instanceof Error; depth++) {
const candidate = current as Error & Record<string, unknown>
if (candidate.code !== undefined) {
driver = candidate
break
}
if (depth === 1) driver = candidate
current = candidate.cause
}
if (!driver) return undefined
return filterUndefined({
name: driver.name,
message: driver.message,
code: driver.code,
severity: driver.severity,
detail: driver.detail,
routine: driver.routine,
errno: driver.errno,
syscall: driver.syscall,
})
} catch {
return undefined
}
}
export interface ExecuteWorkflowCoreOptions {
snapshot: ExecutionSnapshot
callbacks: ExecutionCallbacks
loggingSession: LoggingSession
skipLogCreation?: boolean
abortSignal?: AbortSignal
includeFileBase64?: boolean
base64MaxBytes?: number
stopAfterBlockId?: string
/** Run-from-block mode: execute starting from a specific block using cached upstream outputs */
runFromBlock?: {
startBlockId: string
sourceSnapshot: SerializableExecutionState
sourceExecutionId?: string
}
}
function parseVariableValueByType(value: unknown, type: string): unknown {
const refValue = parseLargeExecutionValue(value)
if (refValue !== undefined) {
return refValue
}
if (value === null || value === undefined) {
switch (type) {
case 'number':
return 0
case 'boolean':
return false
case 'array':
return []
case 'object':
return {}
default:
return ''
}
}
if (type === 'number') {
if (typeof value === 'number') return value
if (typeof value === 'string') {
const num = Number(value)
return Number.isNaN(num) ? 0 : num
}
return 0
}
if (type === 'boolean') {
if (typeof value === 'boolean') return value
if (typeof value === 'string') {
return value.toLowerCase() === 'true'
}
return Boolean(value)
}
if (type === 'array') {
if (Array.isArray(value)) return value
if (typeof value === 'string' && value.trim()) {
try {
return JSON.parse(value)
} catch {
return []
}
}
return []
}
if (type === 'object') {
if (isRecordLike(value)) return value
if (typeof value === 'string' && value.trim()) {
try {
return JSON.parse(value)
} catch {
return {}
}
}
return {}
}
// string or plain
return typeof value === 'string' ? value : String(value)
}
type ExecutionErrorWithFinalizationFlag = Error & {
executionFinalizedByCore?: boolean
}
export const FINALIZED_EXECUTION_ID_TTL_MS = 5 * 60 * 1000
const finalizedExecutionIds = new Map<string, number>()
function cleanupExpiredFinalizedExecutionIds(now = Date.now()): void {
for (const [executionId, expiresAt] of finalizedExecutionIds.entries()) {
if (expiresAt <= now) {
finalizedExecutionIds.delete(executionId)
}
}
}
function rememberFinalizedExecutionId(executionId: string): void {
const now = Date.now()
cleanupExpiredFinalizedExecutionIds(now)
finalizedExecutionIds.set(executionId, now + FINALIZED_EXECUTION_ID_TTL_MS)
}
async function clearExecutionCancellationSafely(
executionId: string,
requestId: string
): Promise<void> {
try {
await clearExecutionCancellation(executionId)
} catch (error) {
logger.error(`[${requestId}] Failed to clear execution cancellation`, { error, executionId })
}
}
function markExecutionFinalizedByCore(error: unknown, executionId: string): void {
rememberFinalizedExecutionId(executionId)
if (error instanceof Error) {
;(error as ExecutionErrorWithFinalizationFlag).executionFinalizedByCore = true
}
}
export function wasExecutionFinalizedByCore(error: unknown, executionId?: string): boolean {
cleanupExpiredFinalizedExecutionIds()
if (executionId && finalizedExecutionIds.has(executionId)) {
return true
}
return (
error instanceof Error &&
(error as ExecutionErrorWithFinalizationFlag).executionFinalizedByCore === true
)
}
async function finalizeExecutionOutcome(params: {
result: ExecutionResult
loggingSession: LoggingSession
executionId: string
requestId: string
workflowInput: unknown
}): Promise<void> {
const { result, loggingSession, executionId, requestId, workflowInput } = params
const { traceSpans, totalDuration } = buildTraceSpans(result)
const endedAt = new Date().toISOString()
try {
try {
if (result.status === 'cancelled') {
await loggingSession.safeCompleteWithCancellation({
endedAt,
totalDurationMs: totalDuration || 0,
traceSpans: traceSpans || [],
})
return
}
if (result.status === 'paused') {
await loggingSession.safeCompleteWithPause({
endedAt,
totalDurationMs: totalDuration || 0,
traceSpans: traceSpans || [],
workflowInput,
})
return
}
await loggingSession.safeComplete({
endedAt,
totalDurationMs: totalDuration || 0,
finalOutput: result.output || {},
traceSpans: traceSpans || [],
workflowInput,
executionState: result.executionState,
})
} catch (error) {
logger.warn(`[${requestId}] Post-execution finalization failed`, {
executionId,
status: result.status,
error,
})
}
} finally {
await clearExecutionCancellationSafely(executionId, requestId)
}
}
async function finalizeExecutionError(params: {
error: unknown
loggingSession: LoggingSession
executionId: string
requestId: string
}): Promise<boolean> {
const { error, loggingSession, executionId, requestId } = params
const executionResult = hasExecutionResult(error) ? error.executionResult : undefined
const { traceSpans } = executionResult ? buildTraceSpans(executionResult) : { traceSpans: [] }
try {
await loggingSession.safeCompleteWithError({
endedAt: new Date().toISOString(),
totalDurationMs: executionResult?.metadata?.duration || 0,
error: {
message: getErrorMessage(error, 'Execution failed'),
stackTrace: error instanceof Error ? error.stack : undefined,
},
traceSpans,
})
return loggingSession.hasCompleted()
} catch (postExecError) {
logger.error(`[${requestId}] Post-execution error logging failed`, {
error: postExecError,
})
return false
} finally {
await clearExecutionCancellationSafely(executionId, requestId)
}
}
/**
* Establish the custom-block registry overlay for the execution's organization,
* then run the core. Wrapping here — the shared choke point for the sync route and
* the background job — puts `custom_block_*` types in scope for serialization,
* execution, and any nested child-workflow serialization (ALS propagates to the
* whole async subtree).
*/
export async function executeWorkflowCore(
options: ExecuteWorkflowCoreOptions
): Promise<ExecutionResult> {
const workspaceId = options.snapshot.metadata.workspaceId
const rows = workspaceId ? await getCustomBlockRowsForWorkspace(workspaceId) : []
return withCustomBlockOverlay(rows, () => executeWorkflowCoreImpl(options))
}
async function executeWorkflowCoreImpl(
options: ExecuteWorkflowCoreOptions
): Promise<ExecutionResult> {
const {
snapshot,
callbacks,
loggingSession,
skipLogCreation,
abortSignal,
includeFileBase64,
base64MaxBytes,
stopAfterBlockId,
runFromBlock,
} = options
const { metadata, workflow, input, workflowVariables, selectedOutputs } = snapshot
const { requestId, workflowId, userId, triggerType, executionId, triggerBlockId, useDraftState } =
metadata
const { onBlockStart, onBlockComplete, onStream, onChildWorkflowInstanceReady } = callbacks
const providedWorkspaceId = metadata.workspaceId
if (!providedWorkspaceId) {
throw new Error(`Execution metadata missing workspaceId for workflow ${workflowId}`)
}
let processedInput = input || {}
let deploymentVersionId: string | undefined
let loggingStarted = false
const pendingLifecycleCallbacks = new Set<Promise<void>>()
const trackLifecycleCallback = (promise: Promise<void>) => {
pendingLifecycleCallbacks.add(promise)
void promise
.finally(() => {
pendingLifecycleCallbacks.delete(promise)
})
.catch(() => {})
}
const waitForLifecycleCallbacks = async () => {
while (pendingLifecycleCallbacks.size > 0) {
await Promise.allSettled([...pendingLifecycleCallbacks])
}
}
try {
const personalEnvUserId =
metadata.isClientSession && metadata.sessionUserId
? metadata.sessionUserId
: metadata.workflowUserId
if (!personalEnvUserId) {
throw new Error('Missing workflowUserId in execution metadata')
}
/**
* Resolves the workflow state from the override, the draft tables, or the
* deployed snapshot. The async load (draft/deployed) has no data dependency
* on the environment load, so the two are awaited concurrently below.
*/
const loadWorkflowState = async () => {
if (metadata.workflowStateOverride) {
const override = metadata.workflowStateOverride
logger.info(`[${requestId}] Using workflow state override (diff workflow execution)`, {
blocksCount: Object.keys(override.blocks).length,
edgesCount: override.edges.length,
})
return {
blocks: override.blocks,
edges: override.edges,
loops: override.loops || {},
parallels: override.parallels || {},
deploymentVersionId: override.deploymentVersionId,
}
}
if (useDraftState) {
const draftData = await loadWorkflowFromNormalizedTables(workflowId)
if (!draftData) {
throw new Error('Workflow not found or not yet saved')
}
logger.info(
`[${requestId}] Using draft workflow state from normalized tables (client execution)`
)
return {
blocks: draftData.blocks,
edges: draftData.edges,
loops: draftData.loops,
parallels: draftData.parallels,
deploymentVersionId: undefined,
}
}
const deployedData = await loadDeployedWorkflowState(workflowId)
logger.info(`[${requestId}] Using deployed workflow state (deployed execution)`)
return {
blocks: deployedData.blocks,
edges: deployedData.edges,
loops: deployedData.loops,
parallels: deployedData.parallels,
deploymentVersionId: deployedData.deploymentVersionId,
}
}
const [workflowState, env] = await Promise.all([
loadWorkflowState(),
getPersonalAndWorkspaceEnv(personalEnvUserId, providedWorkspaceId),
])
const { blocks, loops, parallels } = workflowState
const edges: Edge[] = workflowState.edges
deploymentVersionId = workflowState.deploymentVersionId
const mergedStates = mergeSubblockStateWithValues(blocks)
const { personalEncrypted, workspaceEncrypted, personalDecrypted, workspaceDecrypted } = env
// Use encrypted values for logging (don't log decrypted secrets)
const variables = EnvVarsSchema.parse({ ...personalEncrypted, ...workspaceEncrypted })
// Use already-decrypted values for execution (no redundant decryption)
const decryptedEnvVars: Record<string, string> = { ...personalDecrypted, ...workspaceDecrypted }
loggingStarted = await loggingSession.safeStart({
userId,
billingAttribution: metadata.billingAttribution,
workspaceId: providedWorkspaceId,
variables,
triggerData: metadata.correlation ? { correlation: metadata.correlation } : undefined,
skipLogCreation,
deploymentVersionId,
workflowState: { blocks, edges, loops, parallels },
})
// Use edges directly - trigger-to-trigger edges are prevented at creation time
const filteredEdges = edges
// Check if this is a resume execution before trigger resolution
const resumeFromSnapshot = metadata.resumeFromSnapshot === true
const resumePendingQueue = snapshot.state?.pendingQueue
const resumeRemainingEdges = snapshot.state?.remainingEdges
const resumeTerminalNoop = metadata.resumeTerminalNoop === true
let resolvedTriggerBlockId = triggerBlockId
// Resume executions derive their queue from the snapshot. Even an empty
// queue is meaningful: a terminal pause block has no downstream work.
if (
resumeFromSnapshot &&
(resumePendingQueue !== undefined || resumeRemainingEdges !== undefined || resumeTerminalNoop)
) {
resolvedTriggerBlockId = undefined
logger.info(`[${requestId}] Skipping trigger resolution for resume execution`, {
pendingQueueLength: resumePendingQueue?.length ?? 0,
remainingEdgeCount: resumeRemainingEdges?.length ?? 0,
resumeTerminalNoop,
})
} else if (!triggerBlockId) {
const executionKind =
triggerType === 'api' || triggerType === 'chat'
? (triggerType as 'api' | 'chat')
: triggerType === 'webhook' || triggerType === 'schedule'
? 'external'
: 'manual'
const startBlock = TriggerUtils.findStartBlock(mergedStates, executionKind, false)
if (!startBlock) {
const errorMsg = 'No start block found. Add a start block to this workflow.'
logger.error(`[${requestId}] ${errorMsg}`)
throw new Error(errorMsg)
}
resolvedTriggerBlockId = startBlock.blockId
logger.info(`[${requestId}] Identified trigger block for ${executionKind} execution:`, {
blockId: resolvedTriggerBlockId,
blockType: startBlock.block.type,
path: startBlock.path,
})
}
// Serialize workflow
const serializedWorkflow = new Serializer().serializeWorkflow(
mergedStates,
filteredEdges,
loops,
parallels,
true
)
processedInput = input || {}
// Resolve stopAfterBlockId for loop/parallel containers to their sentinel-end IDs
let resolvedStopAfterBlockId = stopAfterBlockId
if (stopAfterBlockId) {
if (serializedWorkflow.loops?.[stopAfterBlockId]) {
resolvedStopAfterBlockId = buildSentinelEndId(stopAfterBlockId)
} else if (serializedWorkflow.parallels?.[stopAfterBlockId]) {
resolvedStopAfterBlockId = buildParallelSentinelEndId(stopAfterBlockId)
}
}
// Create and execute workflow with callbacks
if (resumeFromSnapshot) {
logger.info(`[${requestId}] Resume execution detected`, {
resumePendingQueue,
hasState: !!snapshot.state,
stateBlockStatesCount: snapshot.state
? Object.keys(snapshot.state.blockStates || {}).length
: 0,
executedBlocksCount: snapshot.state?.executedBlocks?.length ?? 0,
useDraftState,
})
}
const wrappedOnBlockComplete = (
blockId: string,
blockName: string,
blockType: string,
output: {
input?: unknown
output: NormalizedBlockOutput
executionTime: number
startedAt: string
endedAt: string
},
iterationContext?: IterationContext,
childWorkflowContext?: ChildWorkflowContext
) => {
let persistenceSucceeded = false
const persistencePromise = (async () => {
await loggingSession.onBlockComplete(blockId, blockName, blockType, output)
persistenceSucceeded = true
})().catch((error) => {
logger.warn(`[${requestId}] Block completion persistence failed`, {
executionId,
blockId,
blockType,
error,
})
})
const lifecyclePromise = (async () => {
await persistencePromise
if (!persistenceSucceeded || !onBlockComplete) return
try {
await onBlockComplete(
blockId,
blockName,
blockType,
output,
iterationContext,
childWorkflowContext
)
} catch (error) {
logger.warn(`[${requestId}] Block completion callback failed`, {
executionId,
blockId,
blockType,
error,
})
}
})()
trackLifecycleCallback(lifecyclePromise)
return persistencePromise
}
const wrappedOnBlockStart = (
blockId: string,
blockName: string,
blockType: string,
executionOrder: number,
iterationContext?: IterationContext,
childWorkflowContext?: ChildWorkflowContext
) => {
let persistenceSucceeded = false
const persistencePromise = (async () => {
await loggingSession.onBlockStart(blockId, blockName, blockType, new Date().toISOString())
persistenceSucceeded = true
})().catch((error) => {
logger.warn(`[${requestId}] Block start persistence failed`, {
executionId,
blockId,
blockType,
error,
})
})
const lifecyclePromise = (async () => {
await persistencePromise
if (!persistenceSucceeded || !onBlockStart) return
try {
await onBlockStart(
blockId,
blockName,
blockType,
executionOrder,
iterationContext,
childWorkflowContext
)
} catch (error) {
logger.warn(`[${requestId}] Block start callback failed`, {
executionId,
blockId,
blockType,
error,
})
}
})()
trackLifecycleCallback(lifecyclePromise)
return persistencePromise
}
const largeValueExecutionIds = Array.from(
new Set(
[executionId, ...(metadata.largeValueExecutionIds ?? [])].filter((id): id is string =>
Boolean(id)
)
)
)
const largeValueKeys = metadata.largeValueKeys
const fileKeys = metadata.fileKeys
const allowLargeValueWorkflowScope =
metadata.allowLargeValueWorkflowScope === true ||
metadata.resumeFromSnapshot === true ||
Boolean(runFromBlock?.sourceSnapshot && !runFromBlock.sourceExecutionId)
// Resolve the org/workspace PII redaction policy once; serves both the input
// stage (below) and the block-outputs stage (threaded into the executor).
// Resolved from stored rules UNCONDITIONALLY — deliberately NOT gated on the
// `pii-redaction` feature flag. The flag gates configuration (the settings
// route); a transient/false flag read at execution time would skip masking
// and leak PII (fail-open). Stored rules are only writable by entitled orgs,
// so their presence is the source of truth; absence yields the disabled
// default (one indexed lookup, no masking cost for non-PII orgs).
const [row] = await db
.select({ orgSettings: organization.dataRetentionSettings })
.from(workspace)
.leftJoin(organization, eq(organization.id, workspace.organizationId))
.where(eq(workspace.id, providedWorkspaceId))
.limit(1)
const piiRedaction: EffectivePiiRedaction = resolveEffectivePiiRedaction({
orgSettings: row?.orgSettings,
workspaceId: providedWorkspaceId,
})
if (piiRedaction.input.enabled) {
// Redact the input before the workflow sees it. `onFailure: 'throw'` aborts
// the run (handled by the surrounding catch) rather than feeding a scrub
// marker into execution or leaking unredacted input. A large input may
// already be offloaded to a large-value ref (opaque to the string walk), so
// hydrate → mask → re-store refs first, then mask inline strings.
const inputOpts = {
entityTypes: piiRedaction.input.entityTypes,
language: piiRedaction.input.language,
customPatterns: piiRedaction.input.customPatterns,
onFailure: 'throw' as const,
}
processedInput = await redactLargeValueRefsInValue(processedInput, {
...inputOpts,
store: {
workspaceId: providedWorkspaceId,
workflowId,
executionId,
userId: userId ?? undefined,
},
})
processedInput = await redactObjectStrings(processedInput, inputOpts)
}
if (piiRedaction.blockOutputs.enabled) {
// Resume / run-from-block restore prior block outputs into state. If those
// predate the blockOutputs stage being enabled, re-mask them so downstream
// blocks can't read unredacted PII from restored snapshot state. Masking is
// idempotent, so outputs already masked in the original run are unaffected.
//
// Two disjoint passes cover the whole state: `redactLargeValueRefsInValue`
// hydrates → masks → re-stores any value offloaded to large-value storage
// (>8MB refs the string walk treats as opaque), then `redactObjectStrings`
// masks the remaining inline string leaves. Both fail-fast (`throw`), so an
// unmaskable restored value aborts the resume rather than warming raw PII
// into `blockStates` for downstream blocks.
const blockOutputOpts = {
entityTypes: piiRedaction.blockOutputs.entityTypes,
language: piiRedaction.blockOutputs.language,
customPatterns: piiRedaction.blockOutputs.customPatterns,
onFailure: 'throw' as const,
}
const largeRefOpts = {
...blockOutputOpts,
store: {
workspaceId: providedWorkspaceId,
workflowId,
executionId,
userId: userId ?? undefined,
},
}
if (snapshot.state?.blockStates) {
const hydrated = await redactLargeValueRefsInValue(snapshot.state.blockStates, largeRefOpts)
snapshot.state.blockStates = await redactObjectStrings(hydrated, blockOutputOpts)
}
if (runFromBlock?.sourceSnapshot?.blockStates) {
const hydrated = await redactLargeValueRefsInValue(
runFromBlock.sourceSnapshot.blockStates,
largeRefOpts
)
runFromBlock.sourceSnapshot.blockStates = await redactObjectStrings(
hydrated,
blockOutputOpts
)
}
}
let startRunMetadata: StartBlockRunMetadata | undefined
if (resolvedTriggerBlockId) {
const entryBlock = serializedWorkflow.blocks.find(
(block) => block.id === resolvedTriggerBlockId
)
if (entryBlock && isRunMetadataEnabled(entryBlock)) {
startRunMetadata = {
userEmail: await getUserEmailById(userId),
workspaceId: providedWorkspaceId,
workflowId,
executionId,
executionType: triggerType,
executionMode: metadata.executionMode ?? 'sync',
startTime: metadata.startTime,
}
}
}
const contextExtensions: ContextExtensions = {
stream: !!onStream,
selectedOutputs,
executionId,
largeValueExecutionIds,
largeValueKeys,
fileKeys,
allowLargeValueWorkflowScope,
workspaceId: providedWorkspaceId,
userId,
isDeployedContext: !metadata.isClientSession,
enforceCredentialAccess: metadata.enforceCredentialAccess ?? false,
piiBlockOutputRedaction: piiRedaction.blockOutputs,
onBlockStart: wrappedOnBlockStart,
onBlockComplete: wrappedOnBlockComplete,
onStream,
resumeFromSnapshot,
resumePendingQueue,
remainingEdges: snapshot.state?.remainingEdges?.map((edge) => ({
source: edge.source,
target: edge.target,
sourceHandle: edge.sourceHandle ?? undefined,
targetHandle: edge.targetHandle ?? undefined,
})),
dagIncomingEdges: snapshot.state?.dagIncomingEdges,
snapshotState: snapshot.state,
metadata,
startRunMetadata,
abortSignal,
includeFileBase64,
base64MaxBytes,
stopAfterBlockId: resolvedStopAfterBlockId,
onChildWorkflowInstanceReady,
callChain: metadata.callChain,
}
if (snapshot.state) {
await warmLargeValueRefs(snapshot.state, {
workspaceId: providedWorkspaceId,
workflowId,
executionId,
largeValueExecutionIds,
largeValueKeys,
fileKeys,
allowLargeValueWorkflowScope,
userId,
})
}
for (const variable of Object.values(workflowVariables)) {
if (
isPlainRecord(variable) &&
variable.value !== undefined &&
typeof variable.type === 'string'
) {
variable.value = parseVariableValueByType(variable.value, variable.type)
}
}
const executorInstance = new Executor({
workflow: serializedWorkflow,
envVarValues: decryptedEnvVars,
workflowInput: processedInput,
workflowVariables,
contextExtensions,
})
const result = runFromBlock
? ((await executorInstance.executeFromBlock(
workflowId,
runFromBlock.startBlockId,
runFromBlock.sourceSnapshot
)) as ExecutionResult)
: ((await executorInstance.execute(workflowId, resolvedTriggerBlockId)) as ExecutionResult)
await waitForLifecycleCallbacks()
loggingSession.setPostExecutionPromise(
(async () => {
try {
await finalizeExecutionOutcome({
result,
loggingSession,
executionId,
requestId,
workflowInput: processedInput,
})
if (result.success && result.status !== 'paused') {
try {
await updateWorkflowRunCounts(workflowId)
} catch (runCountError) {
logger.error(`[${requestId}] Failed to update run counts`, { error: runCountError })
}
}
} catch (postExecError) {
logger.error(`[${requestId}] Post-execution logging failed`, { error: postExecError })
}
})()
)
logger.info(`[${requestId}] Workflow execution completed`, {
success: result.success,
status: result.status,
duration: result.metadata?.duration,
})
return result
} catch (error: unknown) {
const errorCause = describeErrorCause(error)
logger.error(
`[${requestId}] Execution failed:`,
error,
...(errorCause ? [{ cause: errorCause }] : [])
)
await waitForLifecycleCallbacks()
if (!loggingStarted) {
loggingStarted = await loggingSession.safeStart({
userId,
billingAttribution: metadata.billingAttribution,
workspaceId: providedWorkspaceId,
variables: {},
triggerData: metadata.correlation ? { correlation: metadata.correlation } : undefined,
skipLogCreation,
deploymentVersionId,
})
}
loggingSession.setPostExecutionPromise(
(async () => {
try {
const finalized = loggingStarted
? await finalizeExecutionError({
error,
loggingSession,
executionId,
requestId,
})
: false
if (finalized) {
markExecutionFinalizedByCore(error, executionId)
}
} catch (postExecError) {
logger.error(`[${requestId}] Post-execution error logging failed`, {
error: postExecError,
})
}
})()
)
throw error
}
}