Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(workflows): suppress duplicate workflow logs from email-queue routing reschedule (#64803)

Meikel Ratz1f9e238c73b9
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
index f80a36d1ddd7..96f4f4f3c82c 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
@@ -58,6 +58,20 @@ export class HogFunctionHandler implements ActionHandler {
result.invocation.queue = functionResult.invocation.queue
result.invocation.queueParameters = functionResult.invocation.queueParameters
result.invocation.queueMetadata = functionResult.invocation.queueMetadata
+ // Routing-only reschedule signature: the queue changed AND no explicit
+ // `queueScheduledAt` was set. That's the shape produced by `routeEmailToQueue`
+ // and `routeToQueue` in hog-executor.service.ts when moving a job between the
+ // hogflow and email queues — the next dequeue continues the same action on the
+ // new queue. Tag the action state so the executor can suppress the redundant
+ // "Resuming..." / "Workflow will pause until..." pair on the next dequeue.
+ //
+ // The queue-changed check is what keeps async pauses (fetches, SES throttle
+ // retries) out of this branch: both keep `queueScheduledAt` set OR leave the
+ // queue unchanged, so they don't satisfy both halves of the condition.
+ const queueChanged = functionResult.invocation.queue !== invocation.queue
+ if (queueChanged && !functionResult.invocation.queueScheduledAt) {
+ result.invocation.state.currentAction!.routingOnlyReschedule = true
+ }
return {
scheduledAt: functionResult.invocation.queueScheduledAt ?? DateTime.now(),
}
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
index 3ddc9134c19f..99a092e3b57d 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
@@ -173,7 +173,16 @@ export class HogFlowExecutorService {
return earlyExitResult
}
- logs.push(this.logExecutionTriggerInfo(invocation))
+ // Routing-only reschedule: the previous dequeue moved this job onto a dedicated queue
+ // (e.g. 'email' for SES rate-limit gating) and is continuing the same action. Suppress
+ // the redundant trigger log — the customer-visible story should be one Resuming line
+ // per real wake (delay, wait_until_condition, throttle retry), not a second one for
+ // an internal queue transition. The flag stays set so executeCurrentAction can also
+ // suppress its "Executing action..." debug log on this same continuation; it clears
+ // the flag itself after reading so subsequent actions on this dequeue log normally.
+ if (!invocation.state.currentAction?.routingOnlyReschedule) {
+ logs.push(this.logExecutionTriggerInfo(invocation))
+ }
while (!result || !result.finished) {
const nextInvocation: CyclotronJobInvocationHogFlow = result?.invocation ?? invocation
@@ -360,11 +369,20 @@ export class HogFlowExecutorService {
await this.observeDuplicateInvocation(invocation, currentAction)
- result.logs.push({
- level: 'debug',
- message: `Executing action ${actionIdForLogging(currentAction)}`,
- timestamp: DateTime.now(),
- })
+ // Routing-only reschedule continuation (see hog_function.ts): the previous dequeue
+ // set this flag so the executor knows the current call is just resuming an action
+ // that was momentarily parked to switch queues — not the start of a fresh action
+ // step. Suppress the redundant "Executing action..." log and consume the flag so
+ // subsequent actions (next handler returns nextAction → loop continues) log normally.
+ if (invocation.state.currentAction?.routingOnlyReschedule) {
+ invocation.state.currentAction.routingOnlyReschedule = false
+ } else {
+ result.logs.push({
+ level: 'debug',
+ message: `Executing action ${actionIdForLogging(currentAction)}`,
+ timestamp: DateTime.now(),
+ })
+ }
logger.debug('🦔', `[HogFlowActionRunner] Running action ${currentAction.type}`, {
action: currentAction,
invocation,
@@ -497,11 +515,18 @@ export class HogFlowExecutorService {
// If the result has scheduled for the future then we return that triggering a push back to the queue
result.invocation.queueScheduledAt = scheduledAt
result.finished = false
- result.logs.push({
- level: 'info',
- timestamp: DateTime.now(),
- message: `Workflow will pause until ${scheduledAt.toUTC().toISO()}`,
- })
+ // Routing-only reschedules (hog function moving the job onto a dedicated queue) don't
+ // represent a workflow-author-visible pause — the next dequeue fires almost
+ // immediately and continues the same action. Skip the "Workflow will pause until..."
+ // log in that case so it doesn't surface as a pause the workflow never actually took.
+ // Real pauses (delays, wait_until_condition, throttle retries) still log normally.
+ if (!result.invocation.state.currentAction?.routingOnlyReschedule) {
+ result.logs.push({
+ level: 'info',
+ timestamp: DateTime.now(),
+ message: `Workflow will pause until ${scheduledAt.toUTC().toISO()}`,
+ })
+ }
return result
}
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index b9987f900128..dd67ef043c20 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -345,6 +345,21 @@ export type HogFlowInvocationContext = {
eventMatchedEventUuid?: string
// Paired with the UUID to build the event link in the logs view; never displayed.
eventMatchedEventTimestamp?: string
+ // Set by hog-function action handler when it returns `finished: false` without an
+ // explicit `queueScheduledAt` — i.e. the reschedule is purely to move the job onto a
+ // dedicated queue (e.g. 'email' for SES rate-limit gating) and the next dequeue will
+ // continue the same action. Consumed across three sites in hogflow-executor.service.ts
+ // to suppress the redundant log lines that would otherwise leak the routing into
+ // customer-visible workflow logs:
+ // - `scheduleInvocation` on the dequeue that set it: skips the "Workflow will pause
+ // until..." line (the pause is sub-millisecond and not a real workflow pause).
+ // - Top of the next `execute()`: skips the "Resuming workflow execution at..." line.
+ // The flag is *not* cleared here — it stays set so `executeCurrentAction` can
+ // also act on it.
+ // - `executeCurrentAction` on the same next dequeue: skips the "Executing action..."
+ // debug line *and clears the flag* so any subsequent actions on the same dequeue
+ // (the email handler's `nextAction: exit`, etc.) log normally.
+ routingOnlyReschedule?: boolean
}
// Set by the subscription matcher consumer when an incoming event matched the
// workflow's event-based conversion goals. shouldExitEarly reads and clears it.
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index ee86d6735c3e..b9a25b3bff60 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -1556,6 +1556,98 @@ describe('Workflows E2E (email queue)', () => {
}, 10000)
})
+ it('does not emit duplicate Resuming / Executing / pause logs for the email-queue routing reschedule', async () => {
+ // Email steps reschedule themselves once to switch onto the dedicated email queue
+ // (see HogFunctionHandler.execute in actions/hog_function.ts). That second dequeue
+ // continues the *same* action and would otherwise re-emit "Resuming workflow execution
+ // at Email", "Executing action Email", and a "Workflow will pause until <basically
+ // now>" line — leaking the internal queue routing into customer-visible logs.
+ //
+ // The fix tags the action state with `routingOnlyReschedule: true` on the rescheduling
+ // dequeue and consumes it on the next dequeue to suppress those three lines. This test
+ // is the regression guard: trigger → email → exit should produce exactly one trigger
+ // log, one "Executing action [Action:email_1]" line, one "Email sent" line, and no
+ // routing-flavored pause / resume noise.
+ const hogFlow = new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withStatus('active')
+ .withExitCondition('exit_only_at_end')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: { type: 'event', filters: HOG_FILTERS_EXAMPLES.no_filters.filters ?? {} },
+ },
+ email_1: {
+ type: 'function_email',
+ config: {
+ template_id: 'template-workflows-e2e-email',
+ inputs: {
+ email: {
+ value: {
+ to: { email: '[email protected]', name: 'Recipient' },
+ from: { integrationId: 1, email: '[email protected]' },
+ subject: 'Routing-reschedule log test',
+ text: 'Test text',
+ html: '<p>Test html</p>',
+ },
+ },
+ },
+ },
+ },
+ exit: { type: 'exit', config: {} },
+ },
+ edges: [
+ { from: 'trigger', to: 'email_1', type: 'continue' },
+ { from: 'email_1', to: 'exit', type: 'continue' },
+ ],
+ })
+ .build()
+ await insertHogFlow(hub.postgres, hogFlow)
+
+ const { backgroundTask } = await eventsConsumer.processBatch([createGlobals()])
+ await backgroundTask
+
+ // Wait for the workflow to terminate so all logs from both dequeues have been produced.
+ await waitForExpect(async () => {
+ const jobs = await queryCyclotronJobs()
+ const terminal = jobs.filter(
+ (j: any) => j.status === 'completed' || j.status === 'failed' || j.status === 'canceled'
+ )
+ expect(terminal.length).toBeGreaterThanOrEqual(1)
+ }, 15000)
+
+ // Collect every log entry produced by this hogflow run from the Kafka topic.
+ const logMessages = mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_LOG_ENTRIES)
+ .map((m: any) => m.value.message as string)
+
+ // Sanity check: the test wired up correctly (email actually sent).
+ expect(logMessages.some((msg) => msg.includes('Email sent to [email protected]'))).toBe(true)
+
+ // The email action's "Executing action" debug log must fire EXACTLY ONCE despite the
+ // two dequeues it takes to switch queues. Anchor on the action id ('email_1') so we
+ // don't accidentally also match the trigger or exit action's lines.
+ const executingEmailLogs = logMessages.filter((msg) => msg === 'Executing action [Action:email_1]')
+ expect(executingEmailLogs).toHaveLength(1)
+
+ // The "Resuming workflow execution at" log fires at most once per dequeue — and the
+ // routing-continuation dequeue should be silent. So we should never see a Resuming
+ // line anchored on the email action (the first dequeue Starts at the trigger, not the
+ // email step).
+ const resumingEmailLogs = logMessages.filter(
+ (msg) => msg.includes('Resuming workflow execution at') && msg.includes('[Action:email_1]')
+ )
+ expect(resumingEmailLogs).toHaveLength(0)
+
+ // No "Workflow will pause until" lines either — the only pause in this workflow is the
+ // sub-millisecond routing reschedule, which the suppression should hide. Real pauses
+ // (delays, wait_until_condition, SES throttle retries) still log normally; they're
+ // covered by other tests in this file and aren't exercised here.
+ const pauseLogs = logMessages.filter((msg) => msg.startsWith('Workflow will pause until'))
+ expect(pauseLogs).toHaveLength(0)
+ })
+
it('re-routes between hogflow and email queues across email → fetch → email', async () => {
// Exercises the full ping-pong:
// hogflow worker → email queue (email_1) → email worker sends → routes back to hogflow
@@ -1671,6 +1763,248 @@ describe('Workflows E2E (email queue)', () => {
}, 10000)
})
+ it('suppresses routing logs in both directions across an email → fetch → email ping-pong', async () => {
+ // Companion regression guard to the single-email test above, extended to the full
+ // ping-pong (`hogflow → email → hogflow → email → exit`). Both routing directions
+ // — `routeEmailToQueue` (hogflow → email) and `routeToQueue` (email → hogflow,
+ // taken when a fetch action follows an email send) — go through the same
+ // `finished: false` + nullish `queueScheduledAt` branch in HogFunctionHandler, so
+ // both set `routingOnlyReschedule` and both routing dequeues should be silent in
+ // the logs. This test asserts that on a four-action workflow with two emails and
+ // a fetch between them, we still see exactly one Executing line per action and
+ // zero Resuming-at-email/fetch lines.
+ await insertHogFunctionTemplate(hub.postgres, {
+ id: 'template-workflows-e2e-fetch',
+ name: 'Workflows E2E Fetch',
+ code: `
+ let res := fetch(inputs.url, {'method': inputs.method});
+ print('Fetch result:', res.status);
+ `,
+ inputs_schema: [
+ { key: 'url', type: 'string', required: true },
+ { key: 'method', type: 'string', required: false },
+ ],
+ })
+
+ mockFetch.mockResolvedValue({
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ json: () => Promise.resolve({ success: true }),
+ text: () => Promise.resolve(JSON.stringify({ success: true })),
+ dump: () => Promise.resolve(),
+ })
+
+ const emailAction = (label: string) => ({
+ type: 'function_email' as const,
+ config: {
+ template_id: 'template-workflows-e2e-email',
+ inputs: {
+ email: {
+ value: {
+ to: { email: '[email protected]', name: 'Recipient' },
+ from: { integrationId: 1, email: '[email protected]' },
+ subject: label,
+ text: label,
+ html: `<p>${label}</p>`,
+ },
+ },
+ },
+ },
+ })
+
+ const hogFlow = new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withStatus('active')
+ .withExitCondition('exit_only_at_end')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: { type: 'event', filters: HOG_FILTERS_EXAMPLES.no_filters.filters ?? {} },
+ },
+ email_1: emailAction('Ping-pong email 1'),
+ fetch_1: {
+ type: 'function',
+ config: {
+ template_id: 'template-workflows-e2e-fetch',
+ inputs: {
+ url: { value: 'https://example.com/ping-pong-fetch' },
+ method: { value: 'POST' },
+ },
+ },
+ },
+ email_2: emailAction('Ping-pong email 2'),
+ exit: { type: 'exit', config: {} },
+ },
+ edges: [
+ { from: 'trigger', to: 'email_1', type: 'continue' },
+ { from: 'email_1', to: 'fetch_1', type: 'continue' },
+ { from: 'fetch_1', to: 'email_2', type: 'continue' },
+ { from: 'email_2', to: 'exit', type: 'continue' },
+ ],
+ })
+ .build()
+ await insertHogFlow(hub.postgres, hogFlow)
+
+ const { backgroundTask } = await eventsConsumer.processBatch([createGlobals()])
+ await backgroundTask
+
+ // Wait for both emails sent + the workflow terminated, so all four routing
+ // reschedules have happened and all their logs are in Kafka.
+ await waitForExpect(() => {
+ const sumCounts = (filter: (m: any) => boolean) =>
+ mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter(filter)
+ .reduce((sum: number, m: any) => sum + m.value.count, 0)
+
+ expect(sumCounts((m) => m.value.metric_name === 'email_sent')).toBe(2)
+ }, 15000)
+
+ await waitForExpect(async () => {
+ const jobs = await queryCyclotronJobs()
+ const terminal = jobs.filter(
+ (j: any) => j.status === 'completed' || j.status === 'failed' || j.status === 'canceled'
+ )
+ expect(terminal.length).toBeGreaterThanOrEqual(1)
+ }, 10000)
+
+ const logMessages = mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_LOG_ENTRIES)
+ .map((m: any) => m.value.message as string)
+
+ // Sanity: both emails actually sent (not a vacuous pass where suppression broke the
+ // flow). The "Email sent" log lines are prefixed with `[Action:email_X]` via
+ // `actionIdForLogging`, so we substring-match instead of equality-match.
+ expect(logMessages.filter((msg) => msg.includes('Email sent to [email protected]'))).toHaveLength(2)
+
+ // Each routed action runs across two dequeues but only the "real" execution should log.
+ // - email_1 routes hogflow → email, sends on the email queue
+ // - fetch_1 routes email → hogflow (because the next step is a non-email function),
+ // runs on the hogflow queue
+ // - email_2 routes hogflow → email, sends on the email queue
+ // - exit runs inline at the tail of email_2's dequeue.
+ // Trigger is NOT in this list: `ensureCurrentAction` advances `currentAction` past
+ // the trigger to its successor immediately, so the trigger action itself never
+ // reaches the "Executing action" log site.
+ for (const actionId of ['email_1', 'fetch_1', 'email_2', 'exit']) {
+ const executingLogs = logMessages.filter((msg) => msg === `Executing action [Action:${actionId}]`)
+ expect(executingLogs).toHaveLength(1)
+ }
+
+ // No `Resuming workflow execution at [Action:X]` lines for any of the routed actions.
+ // The first dequeue Starts at the trigger; subsequent transitions are all routing
+ // reschedules or in-loop next-action advances, none of which re-enter execute()
+ // with a non-suppressed flag for these actions.
+ for (const actionId of ['email_1', 'fetch_1', 'email_2']) {
+ const resumingLogs = logMessages.filter(
+ (msg) => msg.includes('Resuming workflow execution at') && msg.includes(`[Action:${actionId}]`)
+ )
+ expect(resumingLogs).toHaveLength(0)
+ }
+
+ // No `Workflow will pause until X` lines anywhere — the three routing reschedules
+ // (email_1, fetch_1, email_2) are all sub-millisecond and have to be silenced.
+ // The workflow has no delays or wait_until_condition steps so any pause log here
+ // would be the routing leak we're guarding against.
+ const pauseLogs = logMessages.filter((msg) => msg.startsWith('Workflow will pause until'))
+ expect(pauseLogs).toHaveLength(0)
+ })
+
+ it('keeps logging real pauses (delay before email) while still suppressing the routing reschedule', async () => {
+ // Counter-example test: the suppression must NOT silence real pauses. A workflow
+ // with `trigger → delay → email → exit` produces two reschedules:
+ // 1. The delay action returns an explicit `queueScheduledAt` 1s in the future
+ // (real pause — must keep logging "Workflow will pause until X" and the
+ // corresponding "Resuming workflow execution at [Action:delay_1]" on wake).
+ // 2. The email action returns no `queueScheduledAt` (routing-only — must be
+ // silent in both directions).
+ // If the fix over-reaches and suppresses real delay pauses, this test fails.
+ const hogFlow = new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withStatus('active')
+ .withExitCondition('exit_only_at_end')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: { type: 'event', filters: HOG_FILTERS_EXAMPLES.no_filters.filters ?? {} },
+ },
+ delay_1: { type: 'delay', config: { delay_duration: '1s' } },
+ email_1: {
+ type: 'function_email',
+ config: {
+ template_id: 'template-workflows-e2e-email',
+ inputs: {
+ email: {
+ value: {
+ to: { email: '[email protected]', name: 'Recipient' },
+ from: { integrationId: 1, email: '[email protected]' },
+ subject: 'After-delay email',
+ text: 'After-delay email',
+ html: '<p>After-delay email</p>',
+ },
+ },
+ },
+ },
+ },
+ exit: { type: 'exit', config: {} },
+ },
+ edges: [
+ { from: 'trigger', to: 'delay_1', type: 'continue' },
+ { from: 'delay_1', to: 'email_1', type: 'continue' },
+ { from: 'email_1', to: 'exit', type: 'continue' },
+ ],
+ })
+ .build()
+ await insertHogFlow(hub.postgres, hogFlow)
+
+ const { backgroundTask } = await eventsConsumer.processBatch([createGlobals()])
+ await backgroundTask
+
+ await waitForExpect(() => {
+ const sumCounts = (filter: (m: any) => boolean) =>
+ mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter(filter)
+ .reduce((sum: number, m: any) => sum + m.value.count, 0)
+ expect(sumCounts((m) => m.value.metric_name === 'email_sent')).toBe(1)
+ }, 15000)
+
+ await waitForExpect(async () => {
+ const jobs = await queryCyclotronJobs()
+ const terminal = jobs.filter(
+ (j: any) => j.status === 'completed' || j.status === 'failed' || j.status === 'canceled'
+ )
+ expect(terminal.length).toBeGreaterThanOrEqual(1)
+ }, 10000)
+
+ const logMessages = mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_LOG_ENTRIES)
+ .map((m: any) => m.value.message as string)
+
+ expect(logMessages.filter((msg) => msg.includes('Email sent to [email protected]'))).toHaveLength(1)
+
+ // The delay's pause log MUST fire — this is the regression guard against
+ // over-suppression. The only routing pause in this workflow (email_1 hopping onto
+ // the email queue) is sub-millisecond and silenced. So exactly one pause line
+ // should appear, and it must be the delay's.
+ const pauseLogs = logMessages.filter((msg) => msg.startsWith('Workflow will pause until'))
+ expect(pauseLogs).toHaveLength(1)
+
+ // The delay-wake Resuming log MUST fire — the workflow really did pause and resume.
+ // The delay handler returns `{ scheduledAt, nextAction: email_1 }` on the rescheduling
+ // dequeue, so `currentAction` is advanced to email_1 *before* the next dequeue. On
+ // wake we therefore see "Resuming workflow execution at [Action:email_1]", NOT at
+ // [Action:delay_1] — the delay is finished, email_1 is what's about to run. This must
+ // appear exactly once (the real wake from delay). The email's routing-continuation
+ // Resuming would be a SECOND identical line; the fix suppresses it, so length stays 1.
+ const resumingEmailLogs = logMessages.filter(
+ (msg) => msg.includes('Resuming workflow execution at') && msg.includes('[Action:email_1]')
+ )
+ expect(resumingEmailLogs).toHaveLength(1)
+ })
+
it('wakes a wait_until_condition parked on the email queue after an email step', async () => {
// Reproduces the prod bug: an email step routes the invocation to the email queue, so the
// following wait_until_condition parks on the email queue (not hogflow). The matcher must