crbench//

← all cases

Hardcoded queue_name='hogflow' filter never finds email-routed parked waits

Tier 2 easy typescript · cross-file · real merged PR from PostHog/posthog #57847

Ground-truth defects

No planted defects (a false-positive trap — a clean review is the correct answer).

The change under review

diff (truncated — full diff)
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.ts
index 26662c32a08a..13c2d9ced0f2 100644
--- a/nodejs/src/capabilities.ts
+++ b/nodejs/src/capabilities.ts
@@ -27,6 +27,7 @@ export const CAPABILITIES_CDP_WORKFLOWS: PluginServerCapabilities = {
     cdpCyclotronWorkerHogFlow: true,
     cdpCyclotronV2Janitor: isDevEnv(),
     cdpHogflowScheduler: isDevEnv(),
+    cdpHogflowSubscriptionMatcher: isDevEnv(),
 }
 
 /** Realtime Cohorts - precalculated filters and cohort membership */
@@ -133,6 +134,10 @@ export function getPluginServerCapabilities(
             return {
                 cdpPrecalculatedFilters: true,
             }
+        case PluginServerMode.cdp_hogflow_subscription_matcher:
+            return {
+                cdpHogflowSubscriptionMatcher: true,
+            }
         case PluginServerMode.cdp_cohort_membership:
             return {
                 cdpCohortMembership: true,
diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts
new file mode 100644
index 000000000000..87b9981df07a
--- /dev/null
+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts
@@ -0,0 +1,781 @@
+import { HogFlow } from '../../schema/hogflow'
+import { parseJSON } from '../../utils/json-parse'
+import { logger } from '../../utils/logger'
+import * as posthogUtils from '../../utils/posthog'
+import { HogFunctionInvocationGlobals } from '../types'
+import * as hogExec from '../utils/hog-exec'
+import { CdpHogflowSubscriptionMatcherConsumer } from './cdp-hogflow-subscription-matcher.consumer'
+
+jest.mock('./cdp-base.consumer', () => {
+    return {
+        CdpConsumerBase: class {
+            constructor() {}
+            async start(): Promise<void> {}
+        },
+    }
+})
+
+jest.mock('../../kafka/consumer', () => ({
+    createKafkaConsumer: jest.fn().mockReturnValue({}),
+}))
+
+jest.mock('pg', () => {
+    const Pool = jest.fn()
+    return { Pool }
+})
+
+type MockRow = {
+    id: string
+    team_id: number
+    function_id: string
+    action_id: string | null
+    distinct_id: string | null
+    person_id: string | null
+    state?: Buffer | null
+}
+
+const eventBytecode = (eventName: string): any[] => ['_H', 1, 32, eventName, 32, 'event', 1, 1, 11]
+
+const makeHogFlow = (overrides: Partial<HogFlow> & { id: string; waitUntil?: boolean }): HogFlow => {
+    const { id, team_id, waitUntil = true, ...rest } = overrides
+    const waitAction = {
+        id: 'wait_node',
+        name: 'Wait',
+        type: 'wait_until_condition',
+        config: {
+            events: [
+                {
+                    filters: {
+                        bytecode: eventBytecode('wuc_subscribed'),
+                        events: [{ id: 'wuc_subscribed', name: 'wuc_subscribed', type: 'events', order: 0 }],
+                    },
+                },
+            ],
+            condition: { filters: null },
+            max_wait_duration: '5m',
+        },
+    }
+    return {
+        id,
+        team_id: team_id ?? 1,
+        version: 1,
+        status: 'active',
+        actions: [
+            {
+                id: 'trigger_node',
+                name: 'Trigger',
+                type: 'trigger',
+                config: { type: 'event', filters: {} },
+            },
+            ...(waitUntil ? [waitAction] : []),
+            { id: 'exit_node', name: 'Exit', type: 'exit', config: {} },
+        ],
+        edges: [],
+        conversion: null,
+        ...rest,
+    } as unknown as HogFlow
+}
+
+const makeGlobals = (overrides: Partial<HogFunctionInvocationGlobals>): HogFunctionInvocationGlobals =>
+    ({
+        project: { id: 1, name: 'Test', url: '' },
+        event: {
+            uuid: 'event-uuid',
+            event: 'wuc_subscribed',
+            distinct_id: 'user-1',
+            properties: {},
+            elements_chain: '',
+            timestamp: new Date().toISOString(),
+            url: '',
+        },
+        person: { id: 'person-uuid-1', properties: {}, name: 'User 1', url: '' },
+        ...overrides,
+    }) as HogFunctionInvocationGlobals
+
+interface QueryCall {
+    sql: string
+    params: any[]
+}
+
+class MatcherUnderTest extends CdpHogflowSubscriptionMatcherConsumer {
+    public calls: QueryCall[] = []
+    public findRows: MockRow[] = []
+    public wakeRows: MockRow[] = []
+    public updateRowCount = 0
+
+    constructor() {
+        // Non-empty URL satisfies the constructor's fail-fast guard; the real Pool (mocked
+        // via jest.mock('pg')) is immediately replaced below with a fixture-dispatching fake.
+        super({ CYCLOTRON_NODE_DATABASE_URL: 'postgres://test' } as any, {} as any)
+        // Wire a fake pool that dispatches queries to predefined fixtures.
+        const dispatch = (sql: string, params: any[]): Promise<{ rows: any[]; rowCount: number }> => {
+            if (sql === 'BEGIN' || sql === 'COMMIT' || sql === 'ROLLBACK') {
+                return Promise.resolve({ rows: [], rowCount: 0 })
+            }
+            this.calls.push({ sql, params })
+            if (sql.includes('SELECT id, team_id, function_id')) {
+                return Promise.resolve({ rows: this.findRows, rowCount: this.findRows.length })
+            }
+            if (sql.includes('SELECT id, state FROM cyclotron_jobs')) {
+                return Promise.resolve({ rows: this.wakeRows, rowCount: this.wakeRows.length })
+            }
+            if (sql.startsWith('UPDATE cyclotron_jobs')) {
+                return Promise.resolve({ rows: [], rowCount: this.updateRowCount })
+            }
+            return Promise.resolve({ rows: [], rowCount: 0 })
+        }
+        ;(this as any).cyclotronPool = {
+            query: jest.fn((sql: string, params: any[]) => dispatch(sql, params)),
+            connect: jest.fn(() =>
+                Promise.resolve({
+                    query: jest.fn((sql: string, params: any[]) => dispatch(sql, params)),
+                    release: jest.fn(),
+                })
+            ),
+        }
+        // Stub hogFlowManager
+        ;(this as any).hogFlowManager = {
+            getHogFlowsForTeams: jest.fn().mockResolvedValue({}),
+            getHogFlowsForTeam: jest.fn().mockResolvedValue([]),
+        }
+    }
+
+    public setHogFlows(map: Record<string, HogFlow>): void {
+        const byTeam: Record<number, HogFlow[]> = {}
+        for (const flow of Object.values(map)) {
+            byTeam[flow.team_id] = byTeam[flow.team_id] ?? []
+            byTeam[flow.team_id].push(flow)
+        }
+        ;(this as any).hogFlowManager.getHogFlowsForTeams.mockResolvedValue(byTeam)
+        ;(this as any).hogFlowManager.getHogFlowsForTeam.mockImplementation((teamId: number) =>
+            Promise.resolve(byTeam[teamId] ?? [])
+        )
+    }
+
+    public async runWake(invocationGlobals: HogFunctionInvocationGlobals[]): Promise<void> {
+        await (this as any).wakeMatchingWorkflows(invocationGlobals)
+    }
+}
+
+const stateBuffer = (state: any): Buffer => Buffer.from(JSON.stringify({ state }))
+
+describe('CdpHogflowSubscriptionMatcherConsumer', () => {
+    let matcher: MatcherUnderTest
+
+    beforeEach(() => {
+        matcher = new MatcherUnderTest()
+    })
+
+    describe('wakeMatchingWorkflows', () => {
+        it('is a no-op when no events have person_id', async () => {
+            await matcher.runWake([
+                makeGlobals({ person: undefined as any, event: { ...makeGlobals({}).event, distinct_id: '' } }),
+            ])
+            expect(matcher.calls).toHaveLength(0)
+        })
+
+        it('passes both distinct_ids and person_ids to the lookup query', async () => {
+            // Need a qualifying hogflow on the team or the team-level early-out skips findParkedJobs.
+            matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+            await matcher.runWake([
+                makeGlobals({}),
+                makeGlobals({
+                    event: { ...makeGlobals({}).event, distinct_id: 'user-2', uuid: 'e2' },
+                    person: { id: 'person-uuid-2', properties: {}, name: '', url: '' },
+                }),
+            ])
+            const lookup = matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))!
+            expect(lookup).not.toBeUndefined()
+            // Params are correlated (team, id) pairs: distinctTeamIds/distinctIds zip row-wise,
+            // and personTeamIds/personIds zip row-wise. Both events are team 1.
+            expect(lookup.params[0]).toEqual([1, 1]) // distinctTeamIds
+            expect(lookup.params[1]).toEqual(['user-1', 'user-2']) // distinctIds
+            expect(lookup.params[2]).toEqual([1, 1]) // personTeamIds
+            expect(lookup.params[3]).toEqual(['person-uuid-1', 'person-uuid-2']) // personIds
+            expect(lookup.params[4]).toEqual(['flow-1']) // functionIds
+        })
+
+        it('correlates team_id with distinct_id so a cross-team pairing is never queried or woken', async () => {
+            // Bug scenario: event A is (team 1, alice), event B is (team 2, bob). A naive
+            // `team_id = ANY([1,2]) AND distinct_id = ANY([alice,bob])` query would also match
+            // a parked job at (team 1, bob) — a team/id combination that no event in the batch
+            // actually carried. The lookup must only ever ask for (team 1, alice) and (team 2, bob).
+            matcher.setHogFlows({
+                'flow-1': makeHogFlow({ id: 'flow-1', team_id: 1 }),
+                'flow-2': makeHogFlow({ id: 'flow-2', team_id: 2 }),
+            })
+
+            // Pretend the DB still returned the cross-team false positive (team 1, bob). The
+            // in-memory guard must reject it because no batch event was for (team 1, bob).
+            matcher.findRows = [
+                {
+                    id: 'job-cross',
+                    team_id: 1,
+                    function_id: 'flow-1',
+                    action_id: 'wait_node',
+                    distinct_id: 'bob',
+                    person_id: null,
+                },
+            ]
+            matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({ currentAction: { id: 'wait_node' } }) }]
+            matcher.updateRowCount = 1
+
+            await matcher.runWake([
+                makeGlobals({
+                    project: { id: 1, name: 'T1', url: '' },
+                    event: { ...makeGlobals({}).event, distinct_id: 'alice', uuid: 'e1' },
+                    person: undefined,
+                }),
+                makeGlobals({
+                    project: { id: 2, name: 'T2', url: '' },
+                    event: { ...makeGlobals({}).event, distinct_id: 'bob', uuid: 'e2' },
+                    person: undefined,
+                }),
+            ])
+
+            // The correlated lookup params zip (team, distinct_id) row-wise: {(1,alice),(2,bob)}.
+            // (1,bob) must not appear — that's the cross-team combination that doesn't exist.
+            const lookup = matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))!
+            expect(lookup).not.toBeUndefined()
+            const pairs = lookup.params[0].map((teamId: number, i: number) => `${teamId}:${lookup.params[1][i]}`)
+            expect(pairs).toEqual(['1:alice', '2:bob'])
+            expect(pairs).not.toContain('1:bob')
+            // And the query is genuinely correlated (tuple form), not independent ANY/ANY.
+            expect(lookup.sql).toContain('(team_id, distinct_id) IN (SELECT * FROM unnest($1::int[], $2::text[]))')
+
+            // The stray cross-team candidate is filtered in-memory → no job is woken.
+            const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+            expect(update).toBeUndefined()
+        })
+
+        it('scopes the lookup to qualifying flows, excluding non-wait flows on the same team', async () => {
+            matcher.setHogFlows({
+                'flow-1': makeHogFlow({ id: 'flow-1' }),
+                'flow-2': makeHogFlow({ id: 'flow-2', waitUntil: false }),
+            })
+            await matcher.runWake([makeGlobals({})])
+            const lookup = matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))!
+            expect(lookup).not.toBeUndefined()
+            expect(lookup.params[4]).toEqual(['flow-1'])
+        })
+
+        it('skips cyclotron entirely when no team in the batch has a wait_until_condition or conversion goal', async () => {
+            // Default: no hogflows configured → team has nothing the matcher could wake.
+            // The cyclotron lookup must NOT fire.
+            await matcher.runWake([makeGlobals({})])
+            expect(matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))).toBeUndefined()
+        })
+
+        it('wakes when the matching event is not the first event in the batch for a distinct_id', async () => {
+            // Two events for the same user in one batch. The first does not match the
+            // wait condition; the second does. The matcher must evaluate both, not just
+            // the first one it indexed.
+            matcher.findRows = [
+                {
+                    id: 'job-1',
+                    team_id: 1,
+                    function_id: 'flow-1',
+                    action_id: 'wait_node',
+                    distinct_id: 'user-1',
+                    person_id: null,
+                },
+            ]
+            matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({ currentAction: { id: 'wait_node' } }) }]
+            matcher.updateRowCount = 1
+            matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+
+            await matcher.runWake([
+                makeGlobals({ event: { ...makeGlobals({}).event, event: 'random_event', uuid: 'e1' } }),
+                makeGlobals({ event: { ...makeGlobals({}).event, event: 'wuc_subscribed', uuid: 'e2' } }),
+            ])
+
+            const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+            expect(update).not.toBeUndefined()
+            expect(update!.params[0]).toEqual(['job-1'])
+        })
+
+        it('wakes a job matched by distinct_id (event-triggered scenario)', async () => {
+            matcher.findRows = [
+                {
+                    id: 'job-1',
+                    team_id: 1,
+                    function_id: 'flow-1',
+                    action_id: 'wait_node',
+                    distinct_id: 'user-1',
+                    person_id: null,
+                },
+            ]
+            matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({ currentAction: { id: 'wait_node' } }) }]
+            matcher.updateRowCount = 1
+            matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+
+            await matcher.runWake([makeGlobals({})])
+
+            const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+            expect(update).not.toBeUndefined()
+            expect(update!.params[0]).toEqual(['job-1'])
+            const newState = parseJSON(update!.params[1][0].toString('utf-8')) as any
+            expect(newState.state.currentAction.eventMatched).toBe(true)
+            // The matching event's name and UUID are persisted so the executor log and the
+            // logs view can pinpoint exactly which event woke the step.
+            expect(newState.state.currentAction.eventMatchedEvent).toBe('wuc_subscribed')
+            expect(newState.state.currentAction.eventMatchedEventUuid).toBe('event-uuid')
+            expect(newState.state.conversionMatched).toBeUndefined()
+        })
+
+        it('logs the hogflow id alongside the action id when wait-step bytecode evaluation throws', async () => {
+            const errorSpy = jest.spyOn(logger, 'error').mockReturnValue(undefined as any)
+            const execSpy = jest.spyOn(hogExec, 'execHog').mockRejectedValue(new Error('boom'))
+            const captureSpy = jest.spyOn(posthogUtils, 'captureException').mockReturnValue(undefined as any)
+
+            try {
+                matcher.findRows = [
+                    {
+                        id: 'job-1',
+                        team_id: 1,
+                        function_id: 'flow-1',
+                        action_id: 'wait_node',
+                        distinct_id: 'user-1',
+                        person_id: null,
+                    },
+                ]
+                matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+                await matcher.runWake([makeGlobals({})])
+
+                const errorCall = errorSpy.mock.calls.find((c) => c[1] === 'Bytecode evaluation error')
+                expect(errorCall).toBeDefined()
+                expect(errorCall![2]).toMatchObject({ hogFlowId: 'flow-1', actionId: 'wait_node' })
+                expect(captureSpy).toHaveBeenCalledWith(expect.any(Error), {
+                    extra: { hogFlowId: 'flow-1', actionId: 'wait_node' },
+                })
+            } finally {
+                errorSpy.mockRestore()
+                execSpy.mockRestore()
+                captureSpy.mockRestore()
+            }
+        })
+
+        it('does not wake when the wait step has events without bytecode (fail-closed)', async () => {
+            // HogFlowSerializer compiles bytecode at save time; a row that reaches the
+            // matcher without bytecode is malformed and must not fall back to event-name
+            // matching, which would silently bypass property filters.
+            matcher.findRows = [
+                {
+                    id: 'job-1',
+                    team_id: 1,
+                    function_id: 'flow-1',
+                    action_id: 'wait_node',
+                    distinct_id: 'user-1',
+                    person_id: null,
+                },
+            ]
+            matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({ currentAction: { id: 'wait_node' } }) }]
+            matcher.updateRowCount = 1
+            const flow = makeHogFlow({ id: 'flow-1' })
+            ;(flow.actions as any[])[1].config.events[0].filters.bytecode = []
+            matcher.setHogFlows({ 'flow-1': flow })
+
+            await matcher.runWake([makeGlobals({})])
+
+            const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+            expect(update).toBeUndefined()
+        })
+
+        it('skips waking a matched job whose state has no currentAction', async () => {
+            matcher.findRows = [
+                {
+                    id: 'job-1',
+                    team_id: 1,
+                    function_id: 'flow-1',
+                    action_id: 'wait_node',
+                    distinct_id: 'user-1',
+                    person_id: null,
+                },
+            ]
+            // State is missing currentAction, so the matcher cannot tag the wake as an
+            // event match. It must skip the job rather than misclassify it as a timeout.
+            matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({}) }]
+            matcher.updateRowCount = 1
+            matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+
+            await matcher.runWake([makeGlobals({})])
+
+            const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+            expect(update).toBeUndefined()
+        })
+
+        it('still wakes a job for a conversion match when stepMatched lacks currentAction', async () => {
+            matcher.findRows = [
+                {
+                    id: 'job-1',
+                    team_id: 1,
+                    function_id: 'flow-1',
+                    action_id: 'wait_node',
+                    distinct_id: 'user-1',
+                    person_id: null,
+                },
+            ]
+            // State missing currentAction: we cannot tag eventMatched, but the same incoming
+            // event also satisfies the workflow's conversion goal, which is independent of
+            // currentAction - that wake must still happen.
+            matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({}) }]
+            matcher.updateRowCount = 1
+            matcher.setHogFlows({
+                'flow-1': makeHogFlow({
+                    id: 'flow-1',
+                    conversion: {
+                        window_minutes: null,
+                        filters: {},
+                        bytecode: [],
+                        events: [
+                            {
+                                filters: {
+                                    events: [{ id: 'wuc_subscribed' }],
+                                    bytecode: eventBytecode('wuc_subscribed'),
+                                },
+                            },
+                        ],
+                    },
+                } as any),
+            })
+
+            await matcher.runWake([makeGlobals({})])
+
+            const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+            expect(update).not.toBeUndefined()
+            const newState = parseJSON(update!.params[1][0].toString('utf-8')) as any
+            expect(newState.state.conversionMatched).toBe(true)
+            // currentAction is missing in input state, so eventMatched must not have been set
+            expect(newState.state.currentAction).toBeUndefined()
+        })
+
+        it('wakes a job matched by person_id (batch-triggered scenario, distinct_id mismatch)', async () => {
+            matcher.findRows = [
+                {
+                    id: 'job-batch',
+                    team_id: 1,
+                    function_id: 'flow-1',
+                    action_id: 'wait_node',
+                    distinct_id: null,
+                    person_id: 'person-uuid-1',
+                },
+            ]
+            matcher.wakeRows = [
+                {
+                    ...matcher.findRows[0],
+                    state: stateBuffer({ currentAction: { id: 'wait_node' }, personId: 'person-uuid-1' }),
+                },
+            ]
+            matcher.updateRowCount = 1
+            matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+

Leaderboard for this case

easy · 7 of 9 bots kept a clean review (78% solve rate).

#BotResultCaughtCoverageFindingsFalse alarms
1 Cubic solved — — 5 0
2 cursor solved — — 1 0
3 Drape (Deep Review) solved — — 8 0
4 Drape (Review) solved — — 5 0
5 greptile solved — — 2 0
6 Mjolnir (Opus 5.5) solved — — 3 0
7 qodo solved — — 5 0
8 Claude Code (Opus 5.5) miss — — 5 1
9 Mjolnir (Sonnet 5.5) miss — — 1 1

Bot results

Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
valid · impact high
A repo grep finds eventMatched/conversionMatched only in the matcher, its test and types.ts. Nothing in the executor reads these flags. The wait handler (conditional_branch.ts) only re-checks config.condition against the original trigger globals, so these wakes do nothing and the job gets rescheduled. [grounded: tree nodejs/src/cdp/types.ts] [consensus 3/3: valid=3]
valid · impact medium
consumer-v1 is the default (CONSUMER_USE_V2 false). It stores offsets in .finally() whether the task succeeds or fails, so a failed processBatch still advances offsets. That contradicts the new code's comment and test that assume no-advance replay. [grounded: tree nodejs/src/kafka/consumer/consumer-v1.ts] [consensus 3/4: valid=3, invalid=1]
valid · impact medium
Candidate events are matched with no check against currentAction.startedAtTimestamp. Events from before the job parked, such as the trigger event if the matcher lags behind the trigger pipeline, can therefore match and wake the job. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The lookup returns every parked hogflow job for the flow, whatever its action type. Conversion matching runs for all of them and never checks exit_condition, so jobs on delays or other steps get scheduled = NOW() and wake early. [grounded: diff] [consensus 3/3: valid=3]
invalid
Actions are always re-validated with non-draft checks when a flow is activated. A status-only activation re-validates the stored actions, and a payload that includes actions is validated as non-draft because status is active. So the draft bytecode in the wait-step events is replaced or rejected before the flow can run, and it never reaches the matcher. [invalid: contradiction] [consensus 3/3: invalid=3]
raw comments (5)
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:193
Nothing in the executor reads the wake flags this consumer writes. `currentAction.eventMatched`, `eventMatchedEvent`, `eventMatchedEventUuid` and `conversionMatched` are only referenced here and in the type definitions. The comment in `cdp/types.ts` says `shouldExitEarly` reads and clears `conversionMatched`, but it doesn't: it only re-runs `conversion.bytecode`/`filters` against the trigger event's `filterGlobals`. Likewise, `wait_until_condition` in `conditional_branch.ts` only re-checks `config.condition` against the original trigger globals. So when a job is woken because a `config.events` entry or `conversion.events` matched, the executor re-evaluates against the old trigger event, gets no match, and parks the job again. Event-based waits and event conversion goals never take effect, and every wake is wasted executor work. The `conversionMatched` flag is also never cleared, so it stays set in the job state.
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:406
The comment says returning the work as `backgroundTask` keeps the offset from advancing past a failed batch, and that the pod will crash and replay. In `consumer-v1`, offsets are stored in `backgroundTask.finally(...)`, which runs whether the task succeeds or fails. If `findParkedJobs` or `wakeJobs` throws (for example, a Postgres error), the batch's offsets are still committed and the matching events are lost for good. The affected workflows then fall through to their timeout branch with no replay.
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:176
Events are never checked against when the job started waiting (for example, `currentAction.startedAtTimestamp`). The matcher reads `events_json` independently of the trigger pipeline. If it lags, it can match an event that happened before the job parked, including the trigger event that started the workflow. A wait like 'wait until event X', or a conversion goal on the trigger event, would then fire immediately. The step completes early or the person is counted as converted, even though nothing happened after the wait began.
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:185
Conversion matching runs for every parked candidate in the flow, not just jobs at a `wait_until_condition` step. It also ignores the flow's `exit_condition`. A job parked on a delay or another scheduled step gets `scheduled = NOW()` and is woken early whenever any conversion event matches, even in flows whose `exit_condition` doesn't exit on conversion. Those early wakes cause extra executions and, depending on how the action handler reschedules, can shorten delays.
products/workflows/backend/api/hog_flow.py:242
For draft `wait_until_condition` `config.events` whose filters fail validation, the raw client-supplied filters, including any client-provided `bytecode`, are stored as-is. The conversion-events path explicitly strips `bytecode` in this case so the filter fails closed. Activation re-validates actions only when `actions` isn't in the payload, so this path is inconsistent. Strip `bytecode` here too, so unvalidated client bytecode can never reach the matcher's `execHog`.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
valid · impact high
Grep of nodejs/src shows that eventMatched/conversionMatched appear only in the matcher, its test and types.ts. No executor code reads them, even though the comment says shouldExitEarly does. Woken jobs therefore just re-evaluate the stored state. [grounded: tree nodejs/src/cdp/types.ts] [consensus 3/3: valid=3]
valid · impact low
config is a JSONField and events entries are not schema-validated. A non-dict entry makes .get raise AttributeError, which becomes a 500 response. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
hog-exec.ts catches exceptions inside execHog (`catch (e) { error = e`) and returns them, so the catch in runBytecode never fires. Failures are silently treated as non-matches and are never logged or counted. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
The try/catch wraps getHogFlowsForTeam, getTeam and the globals conversion, so transient lookup failures are swallowed. The event is dropped and the Kafka offset still advances. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
With no hogflows, wakeMatchingWorkflows returns at `Object.keys(hogflows).length === 0` before findParkedJobs runs. The test therefore never reaches the `if (!hogflow) continue` branch it claims to cover. [grounded: diff] [consensus 3/3: valid=3]
raw comments (6)
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:558
<!-- cubic:v=b71e95ff-3f88-4da4-b727-c7f25b27ff01 --> <!-- cubic:review-run=97470b21-1e93-50ce-ac7d-a261e1be0457 --> <!-- metadata:{"confidence":9} --> P1: When this flag is set, the executor still evaluates the persisted trigger event because it never reads `eventMatched` or `conversionMatched`. The job is woken without the incoming event, so the wait or conversion match is missed and the workflow re-waits; pass the matched event to the executor or add handling for these flags. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts, line 558: <comment>When this flag is set, the executor still evaluates the persisted trigger event because it never reads `eventMatched` or `conversionMatched`. The job is woken without the incoming event, so the wait or conversion match is missed and the workflow re-waits; pass the matched event to the executor or add handling for these flags.</comment> <file context> @@ -0,0 +1,585 @@ + if (updatedState.currentAction) { + updatedState.currentAction = { + ...updatedState.currentAction, + eventMatched: true, + eventMatchedEvent: req.eventName, + eventMatchedEventUuid: req.eventUuid, </file context> ``` </details>
products/workflows/backend/api/hog_flow.py:238
<!-- cubic:v=97e21868-1176-40d7-8c44-1ca2c13cced8 --> <!-- cubic:review-run=97470b21-1e93-50ce-ac7d-a261e1be0457 --> <!-- metadata:{"confidence":9} --> P2: When a workflow contains a malformed event entry or non-object `filters`, validation can raise `AttributeError` or a serializer type error and return 500 because these JSON fields are not schema-validated. Validate each events value as a list of objects and each filters value as an object before calling `.get()` or the serializer in both the wait and conversion loops. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At products/workflows/backend/api/hog_flow.py, line 238: <comment>When a workflow contains a malformed event entry or non-object `filters`, validation can raise `AttributeError` or a serializer type error and return 500 because these JSON fields are not schema-validated. Validate each events value as a list of objects and each filters value as an object before calling `.get()` or the serializer in both the wait and conversion loops.</comment> <file context> @@ -233,6 +233,19 @@ def validate(self, data): + if data.get("type") == "wait_until_condition": + wait_events = data.get("config", {}).get("events") or [] + for event_config in wait_events: + filters = event_config.get("filters") + if filters is not None: </file context> ``` </details>
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:537
<!-- cubic:v=be40c3db-1418-42a5-ade0-e4a22c7ce0b3 --> <!-- cubic:review-run=97470b21-1e93-50ce-ac7d-a261e1be0457 --> <!-- metadata:{"confidence":10} --> P2: When Hog VM execution fails, `execHog` returns an error instead of throwing, so `runBytecode` silently treats the filter as non-matching and never records the failure. Check `result.error` and `result.execResult?.error` before returning the boolean. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts, line 536: <comment>When Hog VM execution fails, `execHog` returns an error instead of throwing, so `runBytecode` silently treats the filter as non-matching and never records the failure. Check `result.error` and `result.execResult?.error` before returning the boolean.</comment> <file context> @@ -0,0 +1,585 @@ + return false + } + try { + const result = await execHog(bytecode, { globals: filterGlobals }) + return result.execResult?.result === true + } catch (err) { </file context> ``` </details> ```suggestion const result = await execHog(bytecode, { globals: filterGlobals }) if (!result.execResult || result.error || result.execResult.error) { throw result.error ?? result.execResult?.error ?? new Error('Bytecode evaluation failed') } return result.execResult.result === true ```
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:388
<!-- cubic:v=72ba3c2b-0bff-400f-a75f-62268bb5342b --> <!-- cubic:review-run=97470b21-1e93-50ce-ac7d-a261e1be0457 --> <!-- metadata:{"confidence":9} --> P2: When a team/cache lookup or globals conversion transiently fails, this catch treats it as a parse error and drops the event, allowing Kafka offsets to advance without a wake attempt. Catch malformed payloads separately and rethrow lookup or conversion failures so the batch is replayed. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts, line 388: <comment>When a team/cache lookup or globals conversion transiently fails, this catch treats it as a parse error and drops the event, allowing Kafka offsets to advance without a wake attempt. Catch malformed payloads separately and rethrow lookup or conversion failures so the batch is replayed.</comment> <file context> @@ -0,0 +1,585 @@ + return + } + events.push(convertToHogFunctionInvocationGlobals(clickHouseEvent, team, this.config.SITE_URL)) + } catch (e) { + logger.error('Error parsing message', e) + counterParseError.labels({ error: e.message }).inc() </file context> ``` </details>
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts:539
<!-- cubic:v=dd68d0d3-9d3e-4fc5-807f-f110213b0a58 --> <!-- cubic:review-run=97470b21-1e93-50ce-ac7d-a261e1be0457 --> <!-- metadata:{"confidence":8} --> P2: This test passes for the wrong reason and never exercises the branch it claims to cover. `setHogFlows({})` makes `getHogFlowsForTeams` resolve to `{}`, so in `wakeMatchingWorkflows` the `Object.keys(hogflows).length === 0` early return fires before `findParkedJobs` is ever called. The parked `findRows` candidate (function_id `unknown-flow`) is therefore never queried or evaluated, and the candidate-loop fallthrough `if (!hogflow) continue` is never reached. To actually test 'candidate whose hogflow is not in the cache', the team must have at least one qualifying flow (so the cyclotron lookup fires) while the candidate's own function_id is absent from the map. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts, line 539: <comment>This test passes for the wrong reason and never exercises the branch it claims to cover. `setHogFlows({})` makes `getHogFlowsForTeams` resolve to `{}`, so in `wakeMatchingWorkflows` the `Object.keys(hogflows).length === 0` early return fires before `findParkedJobs` is ever called. The parked `findRows` candidate (function_id `unknown-flow`) is therefore never queried or evaluated, and the candidate-loop fallthrough `if (!hogflow) continue` is never reached. To actually test 'candidate whose hogflow is not in the cache', the team must have at least one qualifying flow (so the cyclotron lookup fires) while the candidate's own function_id is absent from the map.</comment> <file context> @@ -0,0 +1,781 @@ + expect(update).toBeUndefined() + }) + + it('skips candidates whose hogflow is not in cache', async () => { + matcher.findRows = [ + { </file context> ``` </details> ```suggestion it('skips candidates whose hogflow is not in cache', async () => { matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) }) // team has a qualifying flow so the lookup fires matcher.findRows = [ { id: 'job-1', team_id: 1, function_id: 'unknown-flow', action_id: 'wait_node', distinct_id: 'user-1', person_id: null }, ] await matcher.runWake([makeGlobals({})]) // lookup fires, candidate filtered by the cache-miss branch, no job is woken expect(matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))).not.toBeUndefined() expect(matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))).toBeUndefined() }) ```
PR-level
<!-- cubic:review-summary:start --> **5 issues found** across 11 files <!-- cubic:review-summary:end --> <details> <summary>Prompt for AI agents (unresolved issues)</summary> ```text Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately. <file name="products/workflows/backend/api/hog_flow.py"> <violation number="1" location="products/workflows/backend/api/hog_flow.py:238"> P2: When a workflow contains a malformed event entry or non-object `filters`, validation can raise `AttributeError` or a serializer type error and return 500 because these JSON fields are not schema-validated. Validate each events value as a list of objects and each filters value as an object before calling `.get()` or the serializer in both the wait and conversion loops.</violation> </file> <file name="nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts"> <violation number="1" location="nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:388"> P2: When a team/cache lookup or globals conversion transiently fails, this catch treats it as a parse error and drops the event, allowing Kafka offsets to advance without a wake attempt. Catch malformed payloads separately and rethrow lookup or conversion failures so the batch is replayed.</violation> <violation number="2" location="nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:536"> P2: When Hog VM execution fails, `execHog` returns an error instead of throwing, so `runBytecode` silently treats the filter as non-matching and never records the failure. Check `result.error` and `result.execResult?.error` before returning the boolean.</violation> <violation number="3" location="nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:558"> P1: When this flag is set, the executor still evaluates the persisted trigger event because it never reads `eventMatched` or `conversionMatched`. The job is woken without the incoming event, so the wait or conversion match is missed and the workflow re-waits; pass the matched event to the executor or add handling for these flags.</violation> </file> <file name="nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts"> <violation number="1" location="nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts:539"> P2: This test passes for the wrong reason and never exercises the branch it claims to cover. `setHogFlows({})` makes `getHogFlowsForTeams` resolve to `{}`, so in `wakeMatchingWorkflows` the `Object.keys(hogflows).length === 0` early return fires before `findParkedJobs` is ever called. The parked `findRows` candidate (function_id `unknown-flow`) is therefore never queried or evaluated, and the candidate-loop fallthrough `if (!hogflow) continue` is never reached. To actually test 'candidate whose hogflow is not in the cache', the team must have at least one qualifying flow (so the cyclotron lookup fires) while the candidate's own function_id is absent from the map.</violation> </file> ``` </details> <sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/66/ai_pr_review_github_delivery_339b6fc58192fdd24b1c2815f596870e201465d2d304a388fcdf041deee14a4a?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F66)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_339b6fc58192fdd24b1c2815f596870e201465d2d304a388fcdf041deee14a4a:3d602d58ccabeb4d079850211a99a190a3195455:97470b21-1e93-50ce-ac7d-a261e1be0457 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
valid · impact high
A repo grep finds eventMatched/conversionMatched only in the matcher, its test and types.ts. The executor's shouldExitEarly (hogflow-executor.service.ts:249+) checks only conversion.filters/bytecode, and wait_until_condition still goes through ConditionalBranchHandler. So the matcher sets scheduled=NOW() and writes flags that nothing reads, and woken jobs never take the match or conversion-exit path. This is an incomplete change introduced by this PR. [grounded: diff] [consensus 3/3: valid=3]
raw comments (2)
nodejs/src/cdp/types.ts:347
### Wake flags unused by executor **High Severity** <!-- DESCRIPTION START --> The matcher wakes parked jobs by setting `scheduled` to now and writing `eventMatched` / `conversionMatched`, and the new types claim `shouldExitEarly` reads and clears `conversionMatched`. The hogflow executor never inspects those flags: `ConditionalBranchHandler` still evaluates only `config.condition` against the original trigger event, and `shouldExitEarly` still uses only `conversion.filters` / `conversion.bytecode`. Event-based waits therefore re-park and later take the timeout branch instead of the match branch. Conversion wakes also skip remaining delays on jobs already advanced past a delay, then continue the workflow instead of exiting. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: 73d1774f-0d00-4209-8579-94168ccf203f --> <!-- LOCATIONS START nodejs/src/cdp/types.ts#L334-L347 nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts#L547-L584 nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts#L192-L208 LOCATIONS END --> <details> <summary>Additional Locations (2)</summary> - [`nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts#L547-L584`](https://github.com/drape-io/crbench-cursor-2026-09/blob/22969da2bf36c70f74a1601d44b8d439b269c14f/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts#L547-L584) - [`nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts#L192-L208`](https://github.com/drape-io/crbench-cursor-2026-09/blob/22969da2bf36c70f74a1601d44b8d439b269c14f/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts#L192-L208) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjExOTRiOWJhLTBhMmMtNDA5Ny1hYzlkLTg5NzRkNGU0NzU5ZCIsImVuY3J5cHRpb25LZXkiOiJOWk5HTzhXdlNfZ1h4ajRkeU9PdFczb2ljQ195d1ZYQ2lRQ0tVWVhPdXBBIiwiYnJhbmNoIjoidDItcG9zdGhvZy01Nzg0NyIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjExOTRiOWJhLTBhMmMtNDA5Ny1hYzlkLTg5NzRkNGU0NzU5ZCIsImVuY3J5cHRpb25LZXkiOiJOWk5HTzhXdlNfZ1h4ajRkeU9PdFczb2ljQ195d1ZYQ2lRQ0tVWVhPdXBBIiwiYnJhbmNoIjoidDItcG9zdGhvZy01Nzg0NyIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjY4LCJjb21taXRTaGEiOiIyMjk2OWRhMmJmMzZjNzBmNzRhMTYwMWQ0NGI4ZDQzOWIyNjljMTRmIiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 22969da2bf36c70f74a1601d44b8d439b269c14f. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aToyOGVhN2RlNC00YWJiLTRjMDUtYWMzZS1lZTc0OGVhNmY0ODEiLCJlbmNyeXB0aW9uS2V5IjoiZ2t5NUlGc1dEbW12eHhyV3hvSG1kOVZjVzZSMEdJQWFTRnRIQkFzUG1MayIsImJyYW5jaCI6InQyLXBvc3Rob2ctNTc4NDciLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <!-- /BUGBOT_FIX_ALL --> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN --> <sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END --> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 22969da2bf36c70f74a1601d44b8d439b269c14f. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
valid · impact low
config is an untyped JSONField, so a string entry in config.events reaches .get and raises AttributeError, which surfaces as a 500 rather than a 400. The code is new in this PR. [grounded: tree products/workflows/backend/api/hog_flow.py] [consensus 3/3: valid=3]
valid · impact low
conversion is a JSONField and its events entries are never type-checked, so a non-dict entry raises AttributeError and returns a 500. [grounded: diff] [consensus 3/3: valid=3]
valid · impact high
A grep shows nothing outside the matcher reads eventMatched. ConditionalBranchHandler only re-checks config.condition against the stored filterGlobals, so a woken job re-parks instead of advancing. [grounded: tree nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts] [consensus 3/3: valid=3]
valid · impact high
A grep shows nothing reads conversionMatched, even though the type comment claims shouldExitEarly does. shouldExitEarly only evaluates the legacy conversion filters and bytecode, so a conversion-matched wake never triggers an exit. [grounded: tree nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts] [consensus 3/3: valid=3]
valid · impact low
The matcher treats any flow with conversion.events as actionable and wakes parked jobs on a conversion match without checking exit_condition, which causes needless reschedules. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
Nothing compares the event timestamp with currentAction.startedAtTimestamp, so a lagged event from before the wait step (for example the trigger event, consumed by a separate consumer group) can satisfy the wait. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
Only actions are re-validated on a status-only activation. A draft whose conversion event filters were invalid keeps them with bytecode stripped, and it activates without error with a goal that can never match. [grounded: tree products/workflows/backend/api/hog_flow.py] [consensus 3/3: valid=3]
valid · impact low
The FOR UPDATE select and the UPDATE filter only on id and status, not action_id. If a worker advances the job to a different parked step between the lookup and the wake, the stale match is applied to the new step. [grounded: diff] [consensus 3/3: valid=3]
raw comments (8)
products/workflows/backend/api/hog_flow.py:239
**Non-object wait events entry causes a 500** `config.events` is never type-checked, so a non-dict entry such as a string, or a non-list `events`, reaches `event_config.get` and raises AttributeError. The client gets a 500 instead of a validation error. Raise a ValidationError when `events` isn't a list of dicts. ``` products/workflows/backend/api/hog_flow.py:236 if data.get("type") == "wait_until_condition": products/workflows/backend/api/hog_flow.py:237 wait_events = data.get("config", {}).get("events") or [] products/workflows/backend/api/hog_flow.py:238 for event_config in wait_events: products/workflows/backend/api/hog_flow.py:239 filters = event_config.get("filters") ```
products/workflows/backend/api/hog_flow.py:531
**Non-object conversion events entry causes a 500** `conversion.events` entries aren't type-checked before `event_config.get`. A string entry, or an `events` value that's a string, raises AttributeError and returns 500 instead of 400. Raise a ValidationError when `events` isn't a list of dicts. ``` products/workflows/backend/api/hog_flow.py:530 for event_config in conversion.get("events") or []: products/workflows/backend/api/hog_flow.py:531 event_filters = event_config.get("filters") products/workflows/backend/api/hog_flow.py:532 if event_filters is not None: products/workflows/backend/api/hog_flow.py:533 event_serializer = HogFunctionFiltersSerializer(data=event_filters, context=self.context) ```
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:556
**Event-matched wake never advances the wait step** The matcher sets `currentAction.eventMatched` and reschedules the job now, but nothing in the executor reads that flag. `ConditionalBranchHandler` re-checks the condition against the original trigger event, misses, and parks the job again until its timeout. Make `ConditionalBranchHandler` take the matched branch when `currentAction.eventMatched` is set, and clear the flag afterwards. ``` nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:553 let applied = false nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:554 if (req.stepMatched) { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:555 if (updatedState.currentAction) { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:556 updatedState.currentAction = { nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts:20 const conditionResult = await checkConditions( nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts:21 invocation, nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts:22 action.type === 'conditional_branch' nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts:23 ? action nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts:24 : { nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts:25 ...action, ```
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:572
**Conversion wake is ignored, workflow never exits** The matcher sets `state.conversionMatched` and wakes the job, but `shouldExitEarly` never reads it. It only re-checks legacy `conversion.bytecode` against the trigger event, so the flow continues. Have `shouldExitEarly` treat `state.conversionMatched` as a conversion match and clear it. ``` nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:571 if (req.conversionMatched) { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:572 updatedState.conversionMatched = true nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:573 applied = true nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:574 } nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:269 if (hogFlow.conversion?.filters?.length && person) { nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:270 if (hogFlow.conversion.bytecode?.length) { nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:271 const filterResult = await filterFunctionInstrumented({ nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:272 fn: hogFlow, nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:273 filters: { nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:274 bytecode: hogFlow.conversion.bytecode || [], ```
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:444
**Conversion goals wake jobs even without exit-on-conversion** Any flow with `conversion.events` is treated as actionable, and conversion matches wake every parked job in it, even when `exit_condition` ignores conversion. Those jobs get rewritten and rerun for nothing. Only evaluate conversion events when `exit_condition` includes conversion. ``` nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:436 // conversion goal — nothing for the matcher to evaluate against. nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:437 function hasWaitUntilOrConversion(hogflow: HogFlow): boolean { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:438 if (hogflow.actions.some((a: HogFlowAction) => a.type === 'wait_until_condition')) { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:439 return true nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:288 switch (hogFlow.exit_condition) { nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:289 case 'exit_on_trigger_not_matched': nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:290 if (triggerMatch === false) { nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:291 shouldExit = true nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:292 exitReason = `[Person:${invocation.person?.id ?? 'unknown'}|${invocation.person?.name ?? 'unknown'}] no longer matches trigger filters` nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:293 } ```
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:178
**Events from before the wait step wake it** The event timestamp is never compared with the step's `startedAtTimestamp`, so a lagged older event, or the trigger event itself, counts as the awaited event. Skip events older than the parked step's `startedAtTimestamp`. ``` nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:176 for (const globals of candidateGlobals) { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:177 const filterGlobals = filterGlobalsFor(globals) nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:178 if (!stepMatched && action?.type === 'wait_until_condition') { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:179 if (await this.evaluateWaitUntilCondition(action, filterGlobals, hogflow.id)) { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:252 // Two index-friendly branches with UNION (dedupes rows that match both keys). nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:253 // A single OR across distinct_id and person_id often forces Postgres into a nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:254 // sequential scan; splitting lets each branch hit its own composite index. nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:255 // Each branch correlates (team_id, id) as a tuple via `unnest(teams, ids)`, which nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:256 // zips the parallel arrays row-wise — a job only matches when its team and its id nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:257 // came from the SAME event. Filtering team_id and distinct_id independently with ```
products/workflows/backend/api/hog_flow.py:542
**Invalid draft conversion events activate silently** Invalid conversion event filters in a draft are saved with no bytecode. A status-only activation doesn't re-check `conversion`, so the flow goes active with a conversion goal that can never match. When activating a draft, re-check the stored conversion the same way the actions are re-checked. ``` products/workflows/backend/api/hog_flow.py:534 if self.context.get("is_draft"): products/workflows/backend/api/hog_flow.py:535 if event_serializer.is_valid(): products/workflows/backend/api/hog_flow.py:536 event_config["filters"] = event_serializer.validated_data products/workflows/backend/api/hog_flow.py:537 elif isinstance(event_filters, dict): products/workflows/backend/api/hog_flow.py:490 # When activating a draft, re-validate actions from the instance with full (non-draft) checks products/workflows/backend/api/hog_flow.py:491 status = data.get("status", instance.status if instance else "draft") products/workflows/backend/api/hog_flow.py:492 if status == "active" and instance and instance.status != "active" and "actions" not in data: products/workflows/backend/api/hog_flow.py:493 action_serializer = HogFlowActionSerializer(data=instance.actions, many=True, context=self.context) products/workflows/backend/api/hog_flow.py:494 action_serializer.is_valid(raise_exception=True) products/workflows/backend/api/hog_flow.py:495 actions = action_serializer.validated_data ```
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:309
**Stale match applied to a different wait step** `wakeJobs` locks rows by id and status only. If a worker moves the job to another action after `findParkedJobs`, the old step's match is written onto the new `currentAction`. Also require `action_id` to equal the candidate's action id when locking and updating. ``` nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:309 try { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:310 await client.query('BEGIN') nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:312 const stateRows = await client.query( nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:313 `SELECT id, state FROM cyclotron_jobs nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:553 let applied = false nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:554 if (req.stepMatched) { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:555 if (updatedState.currentAction) { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:556 updatedState.currentAction = { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:557 ...updatedState.currentAction, nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:558 eventMatched: true, ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
valid · impact high
Searching nodejs/src for eventMatched/conversionMatched finds them only in types.ts, the matcher and its test. The executor never reads them, and the wait handler only evaluates config.condition, so a woken job re-evaluates the old condition and parks again. [grounded: tree nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts] [consensus 3/3: valid=3]
valid · impact low
config and conversion are free-form JSONFields. A string or a list of non-dicts in events makes event_config.get raise AttributeError, which surfaces as a 500 instead of a validation error. [grounded: tree products/workflows/backend/api/hog_flow.py] [consensus 3/3: valid=3]
valid · impact low
The code's own comment says conversion is not revalidated on a status-only activation. A draft with invalid conversion-event filters can therefore be activated without any error, and its conversion events can never match. The comment shows the stripping is deliberate (fail closed), but activation still succeeds silently. [grounded: diff-section products/workflows/backend/api/hog_flow.py] [consensus 3/3: valid=3]
valid · impact medium
The locking SELECT and the UPDATE only check id and status. A job that a worker advanced and parked again at a different step (for example a delay) between lookup and wake would still get scheduled=NOW() and be flagged. [grounded: tree nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts] [consensus 3/3: valid=3]
valid · impact low
The conversion match is evaluated, and the job woken, regardless of exit_condition. A flow with exit_only_at_end or exit_on_trigger_not_matched has its parked jobs (including delays) rescheduled to NOW() for no purpose. [grounded: tree nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts] [consensus 3/3: valid=3]
raw comments (5)
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:556
**Woken jobs never read the match flags** The matcher writes `eventMatched` and `conversionMatched` into job state and reschedules to now, but nothing in the executor reads them. The wait handler only checks `config.condition`, not `events`, so the woken job re-parks. Add the executor side: read `eventMatched` and `config.events` in the wait handler, and clear `conversionMatched` in `shouldExitEarly`. ``` nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:548 function applyWakeFlags(stateBuffer: Buffer, req: WakeRequest): Buffer | null { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:549 try { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:550 const parsed = parseJSON(stateBuffer.toString('utf-8')) nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:551 const updatedState: HogFlowInvocationContext = { ...parsed.state } nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts:26 type: 'conditional_branch', nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts:27 config: { nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts:28 conditions: [action.config.condition], nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts:29 delay_duration: action.config.max_wait_duration, nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts:30 }, ```
products/workflows/backend/api/hog_flow.py:238
**Malformed events or conversion events cause a 500** `events` is assumed to be a list of dicts. A non-list value or a string entry makes `.get` raise AttributeError instead of a validation error. The same applies to `conversion.events`. Check that events is a list of dicts and raise a ValidationError otherwise. ``` products/workflows/backend/api/hog_flow.py:236 if data.get("type") == "wait_until_condition": products/workflows/backend/api/hog_flow.py:237 wait_events = data.get("config", {}).get("events") or [] products/workflows/backend/api/hog_flow.py:238 for event_config in wait_events: products/workflows/backend/api/hog_flow.py:239 filters = event_config.get("filters") ```
products/workflows/backend/api/hog_flow.py:530
**Invalid draft conversion events activate silently** A draft with invalid conversion `events` filters is saved with its bytecode stripped, and a status-only activation does not revalidate conversion. The flow goes live with conversion events that can never match, and no error is raised. Revalidate conversion events when activating a draft, as is done for actions. ``` products/workflows/backend/api/hog_flow.py:530 for event_config in conversion.get("events") or []: products/workflows/backend/api/hog_flow.py:531 event_filters = event_config.get("filters") products/workflows/backend/api/hog_flow.py:532 if event_filters is not None: products/workflows/backend/api/hog_flow.py:533 event_serializer = HogFunctionFiltersSerializer(data=event_filters, context=self.context) ```
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:310
**Wake can hit a job that moved on** `wakeJobs` locks rows by id and `status = 'available'` only. It does not recheck `action_id` or `scheduled > NOW()`, so a job re-parked at another step between lookup and wake still gets flagged. Carry the candidate's `action_id` in WakeRequest and require it, plus `scheduled > NOW()`, in the locking SELECT. ``` nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:310 await client.query('BEGIN') nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:312 const stateRows = await client.query( nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:313 `SELECT id, state FROM cyclotron_jobs nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:314 WHERE id = ANY($1::uuid[]) AND status = 'available' ```
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:186
**Conversion wake ignores the workflow's exit_condition** `evaluateConversionEvents` marks a parked job for wake whenever a conversion event matches. It never checks `hogflow.exit_condition`, so flows set to `exit_on_trigger_not_matched`, or with no exit condition, are also woken. Only evaluate conversion events when exit_condition includes conversion. ``` nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:185 if (!conversionMatched) { nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:186 conversionMatched = await this.evaluateConversionEvents(hogflow, filterGlobals) nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:187 } nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:222 // `events` and the property-based `condition` are OR'd: a step can wait on either, nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:288 switch (hogFlow.exit_condition) { nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:289 case 'exit_on_trigger_not_matched': nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:290 if (triggerMatch === false) { nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:291 shouldExit = true nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:292 exitReason = `[Person:${invocation.person?.id ?? 'unknown'}|${invocation.person?.name ?? 'unknown'}] no longer matches trigger filters` nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts:293 } ```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
valid · impact medium
getHogFlowsForTeam and getTeam are awaited inside the per-message try/catch in _parseKafkaBatch. If either rejects, the error is logged as a parse error and the event is silently dropped. processBatch then succeeds, so the offset advances and that event's wakeup is lost. This contradicts the stated replay-on-failure design. [grounded: tree nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts] [consensus 3/3: valid=3]
uncertain
evaluateConversionEvents does skip window_minutes. However, a grep of nodejs/src/cdp found no Node code that reads conversionMatched or window_minutes, so the claimed early termination is not shown. Whether the window should be enforced here, and what effect ignoring it has, cannot be confirmed from the code. [uncertain: no evidence quoted] [consensus 3/3: uncertain=3]
raw comments (3)
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:391
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Transient failures lose events** If `getHogFlowsForTeam` or `getTeam` rejects during a transient database or cache failure, this catch-all handler treats the failure as a parse error and skips the event. The batch can then complete successfully and advance its Kafka offset, permanently losing any workflow wakeup associated with that event. Restrict this catch to malformed event data or propagate dependency failures so Kafka can replay the batch.
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:243
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Conversion window is ignored** Event-based conversion matching evaluates only the filter bytecode and never checks the configured `conversion.window_minutes`. A matching event outside that window therefore sets `conversionMatched`, wakes the parked job, and can terminate a workflow configured to exit on conversion.
PR-level
<h3>Greptile Summary</h3> This PR introduces an event-driven HogFlow subscription matcher that consumes event batches, evaluates wait-step and conversion bytecode, and atomically wakes matching Cyclotron jobs. It also wires the new service mode and capability, extends HogFlow schemas and API compilation, and adds matcher and serializer tests. - Adds identity-correlated parked-job lookup and transactional state updates. - Adds event-based wait and conversion filter schemas and bytecode compilation. - Persists matched-event metadata for resumed workflow logging. - Two correctness gaps remain around replaying transient lookup failures and enforcing conversion windows. <h3>Confidence Score: 3/5</h3> The PR is not yet safe to merge because transient dependency failures can permanently lose wakeups and event conversions can be accepted outside their configured window. The matcher acknowledges batches after swallowing retriable flow or team lookup failures, and its newly introduced event-conversion path ignores `window_minutes` before setting the early-exit flag. **Files Needing Attention:** nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts <details><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts | Implements the matcher and atomic wake flow, but can permanently drop events on transient lookup failures and does not enforce configured conversion windows. | | products/workflows/backend/api/hog_flow.py | Compiles wait-step and conversion event filters while stripping invalid draft conversion bytecode. | | nodejs/src/schema/hogflow.ts | Extends runtime schemas with optional wait-step and conversion event filters. | | nodejs/src/server.ts | Registers and starts the new matcher when its capability is enabled. | | nodejs/src/capabilities.ts | Adds composite-development and dedicated-mode capability selection for the matcher. | </details> <details open><summary><h3>Sequence Diagram</h3></summary> ```mermaid sequenceDiagram participant K as Kafka events participant M as Subscription matcher participant H as HogFlow cache participant C as Cyclotron jobs participant W as HogFlow worker K->>M: Event batch M->>H: Load actionable flows M->>C: Find future jobs by team and identity M->>M: Evaluate wait/conversion bytecode M->>C: Lock jobs and set match flags M->>C: "Set scheduled = NOW()" C->>W: Resume workflow W->>W: Advance matched wait or exit on conversion ``` </details> <!-- greptile_other_comments_section --> <sub>Reviews (1): Last reviewed commit: ["Update nodejs/src/capabilities.ts and 10..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/20780625e6cc81ea9519577ffeb35def45659887) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284742)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
valid · impact medium
The new matcher runs as its own consumer group and evaluates every event in the batch against parked candidates. Nothing compares the event timestamp with currentAction.startedAtTimestamp, and neither findParkedJobs nor applyWakeFlags checks it. So a lagging matcher can wake a job using an event from before the wait started, including the trigger event. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
Same gap as finding 0. Neither the step evaluation nor the conversion evaluation filters events by timestamp against the step start or the workflow start, so events from before the wait, including the triggering event, can set eventMatched or conversionMatched. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
createKafkaConsumer uses the v1 KafkaConsumer unless CONSUMER_USE_V2 is set, and that flag defaults to false. v1 calls storeOffsetsForMessages inside backgroundTask.finally whether the task resolved or rejected. So a failed processBatch still stores its offsets, which contradicts the new code's claim that a failed batch is replayed, and the wakes for that batch are lost. [grounded: tree nodejs/src/kafka/consumer/consumer-v1.ts] [consensus 3/3: valid=3]
raw comments (3)
PR-level
[P2] Events that happened before the job started waiting can still wake it `nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:205-229` The matcher has its own consumer group on `events_json`. It wakes any job whose distinct_id or person_id matches an event in the current batch. Nothing compares the event's timestamp with the time the job reached its wait step. The query in `findParkedJobs` does not load state, and `applyWakeFlags` sets the flags without checking `currentAction.startedAtTimestamp`. Whenever this consumer lags behind the `cdp-events` consumer and the hogflow worker, older events are processed after the job has parked. That includes the trigger event and anything earlier, even when the lag is only a few seconds. Those events can then set `eventMatched` or `conversionMatched` and send the workflow down the "matched" or "converted" branch for activity that came before the wait. This is most likely with property-based `condition` waits, which are evaluated on every event, and with conversion goals. During consumer backlog it can affect a large share of parked jobs. Skip any event whose timestamp is earlier than `currentAction.startedAtTimestamp` (or the job's invocation start, for conversion), for example inside `applyWakeFlags`, where the state is already available.
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:176
[P2] Events from before the wait started can wake the job, including the trigger event itself The matcher checks every event in the batch against every parked candidate. It never compares the event's timestamp with the time the job reached its current step (`state.currentAction.startedAtTimestamp`), or with the time the workflow started. This consumer has its own consumer group on `events_json`, so it can lag behind `cdp-events` and the hogflow worker. Example: a workflow is triggered by `$pageview` and then has "wait until `$pageview`" or a conversion goal on `$pageview`. The worker can park the job before the matcher has read the triggering event. When the matcher does read it, the event matches, and the job is woken (`eventMatched` / `conversionMatched` set) by an event that happened before the wait began. The same thing happens with any older event for that person that is still in the consumer backlog, and with batches that are replayed after a rebalance or restart. Skip any event whose timestamp is earlier than the start of the candidate's current step, or the start of the workflow for conversion goals.
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:403
[P2] A failed match/wake batch still commits its offsets, so those wakes are lost The comment says that returning `processBatch` as `backgroundTask` keeps the offset from moving past a failed batch, so that the batch is replayed. `KafkaConsumer` does not work that way. In `nodejs/src/kafka/consumer/consumer-v1.ts:721-746`, it attaches `backgroundTask.finally(...)`, and that callback calls `storeOffsetsForMessages` whether the task resolved or rejected. If `findParkedJobs` or `wakeJobs` throws (for example a cyclotron connection error or a lock timeout), the batch's offsets are stored anyway. The rejection then reaches the `unhandledRejection` handler, which stops the server and commits the stored offsets during shutdown. The events in that batch are never matched again, and their parked jobs fall through to the timeout branch. If replay matters here, process the batch inside `eachBatch` (await it before returning), or retry inside the task. Otherwise, remove the claim that the batch is replayed.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
invalid
Activating a draft with a status-only PATCH re-validates all of the instance's actions. `HogFlowSerializer.validate` re-runs `HogFlowActionSerializer` with `is_draft` unset, because `to_internal_value` only sets it when status != active. That run reaches the new wait_until_condition events branch with `serializer.is_valid(raise_exception=True)`, so invalid filters are rejected and valid ones get freshly compiled bytecode. Unlike the conversion goal, which this path does not re-validate, actions do get re-validated, so the claimed activation of unvalidated bytecode does not happen. [invalid: contradiction] [consensus 3/3: invalid=3]
raw comments (1)
products/workflows/backend/api/hog_flow.py:240
[P2] Draft wait_until_condition events keep client-supplied bytecode when filters are invalid For a draft, if `HogFunctionFiltersSerializer` rejects `config.events[].filters`, the code leaves `event_config["filters"]` as the client sent it, including any client-supplied `bytecode`. The conversion-events branch in the same PR strips `bytecode` in this case. Its comment explains why: a status-only activation doesn't revalidate the stored data, so stale or forged bytecode would go live unvalidated and the matcher would run it. That reasoning applies equally to wait events. The matcher's `runBytecode` runs `filters.bytecode` for each `config.events[]` entry via `execHog`. A client can save a draft with deliberately invalid filters plus hand-written bytecode, then PATCH `{status: "active"}`. `to_internal_value` only validates the fields in that request, so the actions are not revalidated and the unvalidated bytecode is used. The same drop of `bytecode` on invalid draft filters should be applied here. Severity depends on a user crafting the draft payload and activating it by status alone. Related guidance: [CLAUDE.md security guidance](CLAUDE.md#L68).
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
valid · impact high
A grep shows eventMatched is used only in the matcher, its test and types.ts. ConditionalBranchHandler re-runs checkConditions against the original invocation and returns scheduledAt again, so a job woken by a matching event just gets parked again until its timeout. [grounded: tree nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts] [consensus 3/3: valid=3]
valid · impact high
shouldExitEarly in hogflow-executor.service.ts sets conversionMatch only from conversion bytecode and never reads state.conversionMatched, even though the types.ts comment says it does. So event-based conversion goals cannot trigger a conversion exit. [grounded: tree nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts] [consensus 3/3: valid=3]
valid · impact medium
The try/catch wraps getHogFlowsForTeam and getTeam, so a lookup failure is logged as a parse error and the event is dropped. The batch then resolves successfully, which contradicts the stated goal of replaying on failure. [grounded: tree nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts] [consensus 3/3: valid=3]
valid · impact low
config and conversion are unrestricted JSONFields, so an input like events: [null] reaches .get() on None. That raises AttributeError, which produces a 500 instead of a validation error. [grounded: diff] [consensus 3/3: valid=3]
uncertain
The matcher does ignore window_minutes. However, the existing executor conversion check never enforces window_minutes either, so it is unclear whether the window is meant to apply here. Whether this is a real defect cannot be confirmed. [uncertain: no evidence quoted] [consensus 3/3: uncertain=3]
raw comments (7)
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:558
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 1\. Matching events leave waits parked <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>applyWakeFlags</i></b> stores <b><i>currentAction.eventMatched</i></b>, but no executor path reads that flag or the matching event metadata. When a matching event wakes a future-scheduled wait, <b><i>ConditionalBranchHandler</i></b> evaluates only the original condition against the original invocation globals and schedules the same wait again until its timeout. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description The matcher persists `currentAction.eventMatched`, but wait-step execution never consumes it, so event-matched waits remain parked until timeout. ## Fix Focus Areas - nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[548-580] - nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts[13-40] - nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts[333-398] ## Recommended Fix When executing a `wait_until_condition` action, detect and clear the persisted event-match fields before evaluating the original condition. Route an event match through the wait action's successful branch and preserve the matching event name and UUID for logging, then add an executor-level test proving a parked workflow advances immediately after the matcher wakes it. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:573
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 2\. Conversion events cannot end workflows <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>applyWakeFlags</i></b> writes <b><i>state.conversionMatched</i></b>, but <b><i>shouldExitEarly</i></b> derives <b><i>conversionMatch</i></b> only from the legacy top-level conversion bytecode and never reads the persisted value. Event-based conversions consequently reschedule jobs without satisfying either conversion-based exit condition, including event-only conversions whose top-level filters are empty. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description The matcher persists `conversionMatched`, but the executor ignores it, so event-based conversion goals cannot trigger conversion-based workflow exits. ## Fix Focus Areas - nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[571-580] - nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts[249-310] - nodejs/src/cdp/types.ts[345-347] ## Recommended Fix Initialize the executor's conversion result from `invocation.state.conversionMatched`, clear the persisted marker after consuming it, and apply it through the existing conversion-based exit-condition switch. Add executor tests for both conversion exit modes and for a non-conversion exit mode that must not retain a stale marker. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:391
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 3\. Lookup outages silently drop events <code>🐞 Bug</code> <code>☼ Reliability</code> <pre> <b><i>_parseKafkaBatch</i></b> catches failures from workflow-cache lookup, team lookup, and globals conversion together with malformed-message errors, then returns only the surviving events. A transient database or cache failure therefore resolves the Kafka callback successfully for an incomplete batch, allowing its offset to advance without replaying the lost wakeups. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description The batch parser swallows dependency failures as parse errors, so Kafka commits batches whose workflow wakeups were only partially evaluated. ## Fix Focus Areas - nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[364-395] - nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[398-408] ## Recommended Fix Limit per-message swallowing to confirmed malformed or non-convertible event payloads. Allow workflow-cache and team-manager failures to reject the batch callback so Kafka replay occurs, and add tests showing malformed payloads are skipped while dependency failures reject `backgroundTask` or the callback. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
products/workflows/backend/api/hog_flow.py:240
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 4\. Malformed event lists cause server errors <code>🐞 Bug</code> <code>☼ Reliability</code> <pre> <b><i>HogFlowActionSerializer.validate</i></b> and <b><i>HogFlowSerializer.validate</i></b> iterate unrestricted JSON arrays and call <b><i>.get()</i></b> on each member without verifying that it is an object. Requests containing <b><i>events: [null]</i></b> or <b><i>events: [&quot;bad&quot;]</i></b> therefore raise an attribute error instead of returning a validation response, across both wait-step and conversion event lists. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description The new serializer loops assume every event-list member is a dictionary, allowing malformed JSON input to raise an unhandled server error. ## Fix Focus Areas - products/workflows/backend/api/hog_flow.py[236-247] - products/workflows/backend/api/hog_flow.py[530-545] - products/workflows/backend/api/test/test_hog_flow.py[534-693] ## Recommended Fix Validate that `events` is a list and that every entry is a dictionary with a valid `filters` value before calling `.get()`. Raise field-scoped `serializers.ValidationError` responses for malformed wait and conversion lists, with active and draft request tests covering null, scalar, and non-object members. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts:239
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 5\. Expired conversions wake workflows <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>evaluateConversionEvents</i></b> accepts a conversion solely from event bytecode and never checks <b><i>conversion.window_minutes</i></b>. Any matching event associated with a parked job can consequently set its schedule to the current time even when the incoming event falls outside the workflow&#x27;s configured conversion window. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Event-based conversion matching ignores the configured conversion window and wakes workflows for expired conversion events. ## Fix Focus Areas - nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[171-200] - nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[234-243] - nodejs/src/cdp/types.ts[327-347] - nodejs/src/schema/hogflow.ts[228-241] ## Recommended Fix Before treating a conversion event as matched, compare its event timestamp with the workflow's original trigger timestamp stored in invocation state and enforce `window_minutes`, while preserving the existing unlimited behavior for a null window. Add boundary tests for events just inside, exactly at, and outside the window, including delayed Kafka delivery. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
PR-level
<h3>PR Summary by Qodo</h3> Add event-driven HogFlow subscription matcher <code>✨ Enhancement</code> <code>🧪 Tests</code> <code>⚙️ Configuration changes</code> <code>🕐 40+ Minutes</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <details> <summary>AI Description</summary> <dl> <dd> <br/> ><pre> >• Wake parked workflows when events match wait conditions or conversion goals. >• Compile and validate event filters across Python and Node.js HogFlow schemas. >• Add isolated consumer wiring, metrics, transactional updates, and comprehensive regression > coverage. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid sequenceDiagram participant KE as Kafka Events participant MC as Matcher participant HC as Flow Cache participant DB as Cyclotron DB participant BE as Bytecode Engine participant HW as HogFlow Worker KE->>MC: Event batch MC->>HC: Load actionable flows HC-->>MC: Compiled filters MC->>DB: Find parked jobs DB-->>MC: Candidate projections MC->>BE: Evaluate filters BE-->>MC: Match flags MC->>DB: Lock and wake jobs DB-->>HW: Jobs become runnable ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The following are alternative approaches to this PR: <details> <summary><b>1. Integrate matching into the existing CDP events consumer</b></summary> <dl> <dd> - ➕ Avoids another consumer reading and converting the full events topic. - ➕ Can reuse event parsing and team lookup already performed by CDP processing. - ➖ Couples workflow wakeup failures and offset handling to unrelated CDP event processing. - ➖ Reduces deployment and rollout isolation for a database-intensive feature. </dd> </dl> </details> <details> <summary><b>2. Maintain an indexed event-to-workflow subscription registry</b></summary> <dl> <dd> - ➕ Routes events directly to relevant flows instead of querying parked jobs for each batch. - ➕ Could substantially reduce Cyclotron read pressure at high workflow volume. - ➖ Requires synchronized subscription lifecycle management and an additional durable index. - ➖ Adds consistency and migration complexity before usage patterns and scale are established. </dd> </dl> </details> >**Recommendation:** Keep the dedicated matcher consumer for the initial rollout. It provides clear failure boundaries, independent scaling, idempotent replay, cached flow prefiltering, and transactional wakeups; monitor the added query metrics and consider a durable subscription index if Cyclotron lookup pressure becomes significant. </dd> </dl> </details> <details> <summary> Files changed (11) <code> +1678 / -1 </code> </summary> <dl> <dd> <br/> <details> <summary>Enhancement (4) <code> +644 / -1 </code></summary> <dl> <dd> <details> <summary>cdp-hogflow-subscription-matcher.consumer.ts<code>Implement the HogFlow subscription matcher consumer</code> <code>+585/-0</code></summary> <br/> >Implement the HogFlow subscription matcher consumer > ><pre> >• Introduces a Kafka consumer that identifies parked HogFlow jobs by correlated team and person identifiers, evaluates compiled wait and conversion filters, and atomically reschedules matches. It includes fail-closed bytecode handling, idempotent replay behavior, lifecycle management, tracing, logs, counters, and query latency metrics. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-da9f90ed3573b0c82840594f71dc30ede2f17654e4afef87eebfaae30f017487'>nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts</a> </details> <details> <summary>types.ts<code>Track event and conversion wake reasons in workflow state</code> <code>+12/-0</code></summary> <br/> >Track event and conversion wake reasons in workflow state > ><pre> >• Extends invocation state with wait-event match metadata and a top-level conversion match flag. The event name and UUID preserve the exact reason a parked workflow was resumed. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-adb9e5ad4fa526cbe62a1ed8fd5aaac3ce8ffa3434283198fc5869126f420c9c'>nodejs/src/cdp/types.ts</a> </details> <details> <summary>hogflow.ts<code>Extend HogFlow schemas with event filters</code> <code>+17/-1</code></summary> <br/> >Extend HogFlow schemas with event filters > ><pre> >• Exports the action schema for direct validation and adds optional event filter collections to wait-until actions and conversion goals. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-61b78c0365b5bd6d3a4f6efc8af6facaaf470ae71ca2ca3d4b15572d17da084a'>nodejs/src/schema/hogflow.ts</a> </details> <details> <summary>hog_flow.py<code>Validate and compile workflow event filters</code> <code>+30/-0</code></summary> <br/> >Validate and compile workflow event filters > ><pre> >• Validates wait-step and conversion event filters through the existing Hog function filter serializer so executable bytecode is generated before matching. Invalid draft conversion filters have client-supplied bytecode removed to prevent later execution of unvalidated instructions. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-95b4f260330f9f9dcbcd4949bad36231f01838616124a0858c5230d7e90e8e76'>products/workflows/backend/api/hog_flow.py</a> </details> </dd> </dl> </details> <details> <summary>Tests (3) <code> +1017 / -0 </code></summary> <dl> <dd> <details> <summary>cdp-hogflow-subscription-matcher.consumer.test.ts<code>Cover event-driven workflow matching and wakeups</code> <code>+781/-0</code></summary> <br/> >Cover event-driven workflow matching and wakeups > ><pre> >• Adds extensive tests for identifier correlation, flow scoping, bytecode matching, conversion flags, transactional wakeups, malformed state, error propagation, and Kafka batch filtering. The suite also guards against cross-team matches and unnecessary state loading. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-5d8d5da9513f59a3ac998bbd7c810d6be84d6f60ffcf0fc8c7a657b95f51b181'>nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts</a> </details> <details> <summary>hogflow.test.ts<code>Validate optional HogFlow event filter collections</code> <code>+76/-0</code></summary> <br/> >Validate optional HogFlow event filter collections > ><pre> >• Adds schema tests confirming wait-until actions and conversion goals accept optional event filter lists while remaining backward compatible when omitted. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-3a5e4641d44e0d20953a673e1cfe299cd7b747fe4b6547a8021361c0af72f764'>nodejs/src/schema/hogflow.test.ts</a> </details> <details> <summary>test_hog_flow.py<code>Test event filter compilation and draft safety</code> <code>+160/-0</code></summary> <br/> >Test event filter compilation and draft safety > ><pre> >• Adds API tests verifying bytecode generation for wait and conversion event filters. It also confirms invalid draft conversion filters cannot persist injected bytecode. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-bcc7afab6ed6069e5f3096462ea4287cd2c6a8ede73ec86c9b7d97b73c057ef3'>products/workflows/backend/api/test/test_hog_flow.py</a> </details> </dd> </dl> </details> <details> <summary>Other (4) <code> +17 / -0 </code></summary> <dl> <dd> <details> <summary>capabilities.ts<code>Enable the HogFlow matcher capability</code> <code>+5/-0</code></summary> <br/> >Enable the HogFlow matcher capability > ><pre> >• Adds the matcher to the development workflows capability group and maps its dedicated server mode to the new capability flag. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-c30a1ecfc0137a1b006c1b44b4650feba5af94275988118b51f80c744cee88a0'>nodejs/src/capabilities.ts</a> </details> <details> <summary>config.ts<code>Define a dedicated matcher server mode</code> <code>+1/-0</code></summary> <br/> >Define a dedicated matcher server mode > ><pre> >• Adds the &#x27;cdp-hogflow-subscription-matcher&#x27; plugin server mode for independently deploying and scaling the consumer. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-4bc7cf31623d3a986de0a37a13a6cd9e2f3420c3bacbb3839157a84e3978af5e'>nodejs/src/common/config.ts</a> </details> <details> <summary>server.ts<code>Start the matcher through plugin server capabilities</code> <code>+10/-0</code></summary> <br/> >Start the matcher through plugin server capabilities > ><pre> >• Includes the matcher in CDP dependency initialization and starts it through the standard service loader when its capability is enabled. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-cf5ac11ea38c04baff9bf084e1dc3c956974cbfaf90530c6a5df49922a91bc48'>nodejs/src/server.ts</a> </details> <details> <summary>types.ts<code>Add the matcher capability flag</code> <code>+1/-0</code></summary> <br/> >Add the matcher capability flag > ><pre> >• Extends plugin server capabilities with the optional HogFlow subscription matcher flag. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-eaef2a7062e7c0f9e2a8b4090c404dc476530839abb0642b2513a289e5cbf1a1'>nodejs/src/types.ts</a> </details> </dd> </dl> </details> </dd> </dl> </details>
PR-level
<h3>Code Review by Qodo</h3> <code>🐞 Bugs (5)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <br/> <img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> <details> <summary> 1. Matching events leave waits parked <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>applyWakeFlags</i></b> stores <b><i>currentAction.eventMatched</i></b>, but no executor path reads that flag or the >matching event metadata. When a matching event wakes a future-scheduled wait, ><b><i>ConditionalBranchHandler</i></b> evaluates only the original condition against the original invocation >globals and schedules the same wait again until its timeout. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[R554-558]](https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-da9f90ed3573b0c82840594f71dc30ede2f17654e4afef87eebfaae30f017487R554-R558)</code> > >```diff >+ if (req.stepMatched) { >+ if (updatedState.currentAction) { >+ updatedState.currentAction = { >+ ...updatedState.currentAction, >+ eventMatched: true, >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The matcher only adds the event-match fields to persisted state, while the wait handler exclusively >calls <b><i>checkConditions</i></b> with <b><i>action.config.condition</i></b>; repository-wide references show no >production reader for any of the new event-match fields. A false condition therefore reaches ><b><i>calculatedScheduledAt</i></b> and parks the action again. ></pre> > > <code>[nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[548-580]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts/#L548-L580)</code> > <code>[nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts[13-40]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts/#L13-L40)</code> > <code>[nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts[44-81]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts/#L44-L81)</code> > <code>[nodejs/src/cdp/types.ts[331-347]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/types.ts/#L331-L347)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The matcher persists `currentAction.eventMatched`, but wait-step execution never consumes it, so event-matched waits remain parked until timeout. > >## Fix Focus Areas >- nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[548-580] >- nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts[13-40] >- nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts[333-398] > >## Recommended Fix >When executing a `wait_until_condition` action, detect and clear the persisted event-match fields before evaluating the original condition. Route an event match through the wait action's successful branch and preserve the matching event name and UUID for logging, then add an executor-level test proving a parked workflow advances immediately after the matcher wakes it. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 2. Conversion events cannot end workflows <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>applyWakeFlags</i></b> writes <b><i>state.conversionMatched</i></b>, but <b><i>shouldExitEarly</i></b> derives <b><i>conversionMatch</i></b> >only from the legacy top-level conversion bytecode and never reads the persisted value. Event-based >conversions consequently reschedule jobs without satisfying either conversion-based exit condition, >including event-only conversions whose top-level filters are empty. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[R571-573]](https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-da9f90ed3573b0c82840594f71dc30ede2f17654e4afef87eebfaae30f017487R571-R573)</code> > >```diff >+ if (req.conversionMatched) { >+ updatedState.conversionMatched = true >+ applied = true >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The new state type explicitly says <b><i>shouldExitEarly</i></b> reads and clears the marker, but that method >only invokes legacy filter bytecode and its exit switch sees no persisted event match. The matcher >nevertheless wakes every job whose conversion event bytecode matches. ></pre> > > <code>[nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[185-200]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts/#L185-L200)</code> > <code>[nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[571-580]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts/#L571-L580)</code> > <code>[nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts[249-280]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts/#L249-L280)</code> > <code>[nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts[288-310]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts/#L288-L310)</code> > <code>[nodejs/src/cdp/types.ts[345-347]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/types.ts/#L345-L347)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The matcher persists `conversionMatched`, but the executor ignores it, so event-based conversion goals cannot trigger conversion-based workflow exits. > >## Fix Focus Areas >- nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[571-580] >- nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts[249-310] >- nodejs/src/cdp/types.ts[345-347] > >## Recommended Fix >Initialize the executor's conversion result from `invocation.state.conversionMatched`, clear the persisted marker after consuming it, and apply it through the existing conversion-based exit-condition switch. Add executor tests for both conversion exit modes and for a non-conversion exit mode that must not retain a stale marker. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 3. Lookup outages silently drop events <code>🐞 Bug</code> <code>☼ Reliability</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>_parseKafkaBatch</i></b> catches failures from workflow-cache lookup, team lookup, and globals conversion >together with malformed-message errors, then returns only the surviving events. A transient database >or cache failure therefore resolves the Kafka callback successfully for an incomplete batch, >allowing its offset to advance without replaying the lost wakeups. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[R388-391]](https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-da9f90ed3573b0c82840594f71dc30ede2f17654e4afef87eebfaae30f017487R388-R391)</code> > >```diff >+ } catch (e) { >+ logger.error('Error parsing message', e) >+ counterParseError.labels({ error: e.message }).inc() >+ } >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The broad try block includes both calls to <b><i>hogFlowManager</i></b> and <b><i>teamManager</i></b>, but its catch merely >logs and increments a parse metric. <b><i>start</i></b> then submits <b><i>processBatch</i></b> for the reduced array, >unlike processing failures that reject <b><i>backgroundTask</i></b> and prevent normal offset advancement. ></pre> > > <code>[nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[364-395]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts/#L364-L395)</code> > <code>[nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[398-408]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts/#L398-L408)</code> > <code>[nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts[642-666]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts/#L642-L666)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The batch parser swallows dependency failures as parse errors, so Kafka commits batches whose workflow wakeups were only partially evaluated. > >## Fix Focus Areas >- nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[364-395] >- nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[398-408] > >## Recommended Fix >Limit per-message swallowing to confirmed malformed or non-convertible event payloads. Allow workflow-cache and team-manager failures to reject the batch callback so Kafka replay occurs, and add tests showing malformed payloads are skipped while dependency failures reject `backgroundTask` or the callback. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <br/> <img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> <details> <summary> 4. Malformed event lists cause server errors <code>🐞 Bug</code> <code>☼ Reliability</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>HogFlowActionSerializer.validate</i></b> and <b><i>HogFlowSerializer.validate</i></b> iterate unrestricted JSON arrays >and call <b><i>.get()</i></b> on each member without verifying that it is an object. Requests containing ><b><i>events: [null]</i></b> or <b><i>events: [&quot;bad&quot;]</i></b> therefore raise an attribute error instead of returning a >validation response, across both wait-step and conversion event lists. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[products/workflows/backend/api/hog_flow.py[R237-240]](https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-95b4f260330f9f9dcbcd4949bad36231f01838616124a0858c5230d7e90e8e76R237-R240)</code> > >```diff >+ wait_events = data.get("config", {}).get("events") or [] >+ for event_config in wait_events: >+ filters = event_config.get("filters") >+ if filters is not None: >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >Both <b><i>config</i></b> and <b><i>conversion</i></b> are declared as unrestricted <b><i>JSONField</i></b> values, so DRF does not >constrain nested list members before these new loops execute. Each loop immediately invokes ><b><i>event_config.get</i></b>, which is invalid for nulls, strings, arrays, and numbers. ></pre> > > <code>[products/workflows/backend/api/hog_flow.py[122-138]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/products/workflows/backend/api/hog_flow.py/#L122-L138)</code> > <code>[products/workflows/backend/api/hog_flow.py[236-247]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/products/workflows/backend/api/hog_flow.py/#L236-L247)</code> > <code>[products/workflows/backend/api/hog_flow.py[410-417]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/products/workflows/backend/api/hog_flow.py/#L410-L417)</code> > <code>[products/workflows/backend/api/hog_flow.py[530-545]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/products/workflows/backend/api/hog_flow.py/#L530-L545)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The new serializer loops assume every event-list member is a dictionary, allowing malformed JSON input to raise an unhandled server error. > >## Fix Focus Areas >- products/workflows/backend/api/hog_flow.py[236-247] >- products/workflows/backend/api/hog_flow.py[530-545] >- products/workflows/backend/api/test/test_hog_flow.py[534-693] > >## Recommended Fix >Validate that `events` is a list and that every entry is a dictionary with a valid `filters` value before calling `.get()`. Raise field-scoped `serializers.ValidationError` responses for malformed wait and conversion lists, with active and draft request tests covering null, scalar, and non-object members. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 5. Expired conversions wake workflows <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>evaluateConversionEvents</i></b> accepts a conversion solely from event bytecode and never checks ><b><i>conversion.window_minutes</i></b>. Any matching event associated with a parked job can consequently set >its schedule to the current time even when the incoming event falls outside the workflow&#x27;s >configured conversion window. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[R234-239]](https://github.com/drape-io/crbench-qodo-2026-09/pull/62/files#diff-da9f90ed3573b0c82840594f71dc30ede2f17654e4afef87eebfaae30f017487R234-R239)</code> > >```diff >+ private async evaluateConversionEvents(hogflow: HogFlow, filterGlobals: FilterGlobals): Promise<boolean> { >+ const conversionEvents = hogflow.conversion?.events ?? [] >+ const context = { hogFlowId: hogflow.id } >+ for (const eventConfig of conversionEvents) { >+ if (await runBytecode(eventConfig.filters?.bytecode, filterGlobals, context)) { >+ return true >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The shared schema retains <b><i>window_minutes</i></b>, and persisted workflow state retains the original >trigger event timestamp, but conversion evaluation receives only the flow and incoming filter >globals and checks bytecode alone. The subsequent wake path updates every matched parked job to ><b><i>scheduled = NOW()</i></b>. ></pre> > > <code>[nodejs/src/schema/hogflow.ts[228-241]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/schema/hogflow.ts/#L228-L241)</code> > <code>[nodejs/src/cdp/types.ts[327-347]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/types.ts/#L327-L347)</code> > <code>[nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[234-243]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts/#L234-L243)</code> > <code>[nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[341-349]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts/#L341-L349)</code> > <code>[products/workflows/backend/api/hog_flow.py[410-417]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3206f7f72507a6ac99a960b37b037078c89763df/products/workflows/backend/api/hog_flow.py/#L410-L417)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Event-based conversion matching ignores the configured conversion window and wakes workflows for expired conversion events. > >## Fix Focus Areas >- nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[171-200] >- nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts[234-243] >- nodejs/src/cdp/types.ts[327-347] >- nodejs/src/schema/hogflow.ts[228-241] > >## Recommended Fix >Before treating a conversion event as matched, compare its event timestamp with the workflow's original trigger timestamp stored in invocation state and enforce `window_minutes`, while preserving the existing unlimited behavior for a null window. Add boundary tests for events just inside, exactly at, and outside the window, including delayed Kafka delivery. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-context:start --> <details><summary><strong>Context sources</strong></summary> <div>Review mode: <code>⚖️ Balanced</code>: Downgraded extended -&gt; standard: change is below the extended eligibility bar (hunks 17/18, lines 1679/200; both must reach the floor). Router rationale: This introduces a substantial new event-driven consumer spanning Kafka, PostgreSQL transactions, workflow filter execution, schema/API validation, server wiring, and concurrency-sensitive wake-up logic, with many independent paths where redundant review is materially valuable.</div> <!-- qodo-context:end --> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:start --> <details> <summary><strong>Tip of the day</strong></summary> <br/> <pre>💡 Did you know, you can reply &#x27;qodo&#x27; on any finding to push back, ask questions, or dig deeper</pre> <a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:end --> <!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/3206f7f72507a6ac99a960b37b037078c89763df --> <a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>