Skip to content

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

feat(workflows): always link email metrics to the invocations tab (#70676)

Daniel Marchuka7652c01f091
diff --git a/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx b/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx
index 01b357761812..a5804f3ea4a1 100644
--- a/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx
+++ b/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx
@@ -480,10 +480,12 @@ export function HogInvocations({ id, functionKind, renderLogMessage }: HogInvoca
<LemonInput
type="search"
size="small"
- placeholder="Search by invocation, event, distinct, or person ID…"
+ placeholder="Search by ID or log message…"
fullWidth
value={filters.search ?? ''}
- onChange={(value) => setFilters({ search: value || undefined })}
+ // Clear the drill-down's level narrowing on manual typing — a hand-typed
+ // search matches log messages at any level, not just WARN/ERROR.
+ onChange={(value) => setFilters({ search: value || undefined, log_levels: undefined })}
prefix={<IconSearch />}
allowClear
/>
diff --git a/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.test.ts b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.test.ts
new file mode 100644
index 000000000000..aa0aa65ea512
--- /dev/null
+++ b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.test.ts
@@ -0,0 +1,47 @@
+import { buildSearchClause } from './hogInvocationsLogic'
+
+describe('buildSearchClause', () => {
+ const props = { id: 'flow-1', functionKind: 'hog_flow' as const }
+
+ it('returns an empty clause when no search is set', () => {
+ // An empty clause when a search IS set (covered below) would silently show every run — the
+ // failure mode worth locking.
+ expect(buildSearchClause(props, { date_from: '-24h' }).raw).toBe('')
+ })
+
+ it('matches the typed term as an exact id OR a log-message substring', () => {
+ // One typed term goes into every arm: it's compared for equality against each id column (paste
+ // an id to find that run) and, via a log_entries subquery, as a substring of the message (type
+ // words to find a run that logged them). So the same term appears in all arms below.
+ const clause = buildSearchClause(props, { date_from: '-24h', search: 'run-42' }).raw
+ expect(clause).toContain("invocation_id = 'run-42'")
+ expect(clause).toContain("event_uuid = 'run-42'")
+ expect(clause).toContain("distinct_id = 'run-42'")
+ expect(clause).toContain("person_id = 'run-42'")
+ expect(clause).toContain('FROM log_entries')
+ expect(clause).toContain("message ILIKE concat('%', 'run-42', '%')")
+ // No level narrowing for a manual search — it matches any level.
+ expect(clause).not.toContain('lower(level)')
+ })
+
+ it('narrows the message match to log_levels when a drill-down sets them', () => {
+ // Drill-downs carry levels so "Bounced" (WARN/ERROR) does not also match the INFO
+ // "Email sent to bounce@…" log.
+ const clause = buildSearchClause(props, {
+ date_from: '-24h',
+ search: 'bounce',
+ log_levels: ['WARN', 'ERROR'],
+ }).raw
+ expect(clause).toContain("message ILIKE concat('%', 'bounce', '%')")
+ expect(clause).toContain("lower(level) IN ('warn','error')")
+ })
+
+ it('escapes ILIKE wildcards in the message arm but not the id arms', () => {
+ // Typing "a%b" must match that literal text in messages, not "a<anything>b". The % is
+ // backslash-escaped only for the ILIKE arm (then doubled by escapeHogQLString for the SQL
+ // literal); the exact-id arms keep the raw term.
+ const clause = buildSearchClause(props, { date_from: '-24h', search: 'a%b' }).raw
+ expect(clause).toContain("invocation_id = 'a%b'")
+ expect(clause).toContain("message ILIKE concat('%', 'a\\\\%b', '%')")
+ })
+})
diff --git a/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx
index 4816b8e2bf54..783ceb4d98f9 100644
--- a/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx
+++ b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx
@@ -10,7 +10,7 @@ import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { teamLogic } from 'scenes/teamLogic'
import { escapeHogQLString, hogql } from '~/queries/utils'
-import { PersonType } from '~/types'
+import { LogEntryLevel, PersonType } from '~/types'
import { hogFunctionsRerunCreate } from 'products/cdp/frontend/generated/api'
import type { HogInvocationRerunFilterStatusEnumApi } from 'products/cdp/frontend/generated/api.schemas'
@@ -89,6 +89,7 @@ export interface HogInvocationsFilters {
* no cross-shard subquery against `persons`.
*/
person_uuid?: string
+ log_levels?: LogEntryLevel[]
}
export interface HogInvocationsLogicProps {
@@ -129,6 +130,7 @@ const URL_PARAMS = {
order_by: `${URL_PARAM_PREFIX}order`,
problem_only: `${URL_PARAM_PREFIX}problems`,
person_uuid: `${URL_PARAM_PREFIX}person`,
+ log_levels: `${URL_PARAM_PREFIX}log_levels`,
} as const
const filtersToSearchParams = (filters: HogInvocationsFilters): Record<string, string | undefined> => ({
@@ -141,6 +143,7 @@ const filtersToSearchParams = (filters: HogInvocationsFilters): Record<string, s
[URL_PARAMS.order_by]: filters.order_by === 'first_scheduled' ? undefined : filters.order_by,
[URL_PARAMS.problem_only]: filters.problem_only ? '1' : undefined,
[URL_PARAMS.person_uuid]: filters.person_uuid,
+ [URL_PARAMS.log_levels]: filters.log_levels?.length ? filters.log_levels.join(',') : undefined,
})
const searchParamsToFilters = (searchParams: Record<string, string | undefined>): Partial<HogInvocationsFilters> => {
@@ -177,6 +180,10 @@ const searchParamsToFilters = (searchParams: Record<string, string | undefined>)
if (searchParams[URL_PARAMS.person_uuid]) {
next.person_uuid = searchParams[URL_PARAMS.person_uuid]
}
+ const logLevels = searchParams[URL_PARAMS.log_levels]
+ if (logLevels) {
+ next.log_levels = logLevels.split(',').filter(Boolean) as LogEntryLevel[]
+ }
return next
}
@@ -191,6 +198,18 @@ const DEFAULT_FILTERS: HogInvocationsFilters = {
person_uuid: undefined,
}
+/**
+ * Build the `inv_`-prefixed router search params that deep-link the Invocations tab to a filter
+ * subset. Lets callers outside the tab (e.g. the workflow metrics tiles) point at it without
+ * duplicating the URL param scheme. Unset keys fall back to defaults and are dropped from the URL.
+ */
+export function buildHogInvocationsSearchParams(filters: Partial<HogInvocationsFilters>): Record<string, string> {
+ const params = filtersToSearchParams({ ...DEFAULT_FILTERS, ...filters })
+ return Object.fromEntries(
+ Object.entries(params).filter((entry): entry is [string, string] => entry[1] !== undefined)
+ )
+}
+
const AUTO_REFRESH_INTERVAL_MS = 10000
// After a rerun is enqueued the matching rows aren't `running` yet (the worker
// drains asynchronously), so the `hasRunningRows` guard alone wouldn't restart
@@ -332,6 +351,45 @@ export const problemClauseFor = (
)
}
+/**
+ * The main search box: one term matches an exact invocation / event / distinct / person id, OR — like
+ * the old Logs tab — a run that logged an entry whose message contains it (case-insensitive
+ * substring). `log_levels` narrows only the message match and is set solely by metric drill-downs
+ * (e.g. the "Bounced" tile carries WARN/ERROR so it doesn't also match the INFO "Email sent to
+ * bounce@…" log); manual searches leave it unset and match any level. The message subquery is
+ * deliberately not date-scoped — a bounce/complaint can land after the run's scheduled window, and
+ * the outer `scheduled_at` filter already bounds which invocations appear. Empty when no search.
+ */
+export const buildSearchClause = (
+ props: HogInvocationsLogicProps,
+ filters: HogInvocationsFilters
+): ReturnType<typeof hogql.raw> => {
+ const search = filters.search?.trim()
+ if (!search) {
+ return hogql.raw('')
+ }
+ const levels = filters.log_levels ?? []
+ const levelClause = levels.length
+ ? `AND lower(level) IN (${levels.map((level) => escapeHogQLString(level.toLowerCase())).join(',')})`
+ : ''
+ // Escape ILIKE wildcards for the message arm so a term with % or _ (e.g. "50%") matches literally
+ // (ClickHouse ILIKE uses backslash as its escape char); the exact-id arms use the raw term.
+ const likeTerm = search.replace(/[\\%_]/g, '\\$&')
+ return hogql.raw(
+ `AND (` +
+ `invocation_id = ${escapeHogQLString(search)} ` +
+ `OR event_uuid = ${escapeHogQLString(search)} ` +
+ `OR distinct_id = ${escapeHogQLString(search)} ` +
+ `OR person_id = ${escapeHogQLString(search)} ` +
+ `OR invocation_id IN (` +
+ `SELECT instance_id FROM log_entries ` +
+ `WHERE log_source = ${escapeHogQLString(props.functionKind)} ` +
+ `AND log_source_id = ${escapeHogQLString(props.id)} ` +
+ `AND message ILIKE concat('%', ${escapeHogQLString(likeTerm)}, '%') ` +
+ `${levelClause}))`
+ )
+}
+
/**
* Tier selection for the sparkline. Each tier carries both the HogQL bucket
* expression and the equivalent client-side interval (in ms) so we can
@@ -398,17 +456,6 @@ async function fetchSparkline(props: HogInvocationsLogicProps, filters: HogInvoc
const optionalErrorKindClause = filters.error_kind?.length
? hogql.raw(`AND error_kind IN (${filters.error_kind.map(escapeHogQLString).join(',')})`)
: hogql.raw('')
- const trimmedSearch = filters.search?.trim()
- const optionalSearchClause = trimmedSearch
- ? hogql.raw(
- `AND (
- invocation_id = ${escapeHogQLString(trimmedSearch)}
- OR event_uuid = ${escapeHogQLString(trimmedSearch)}
- OR distinct_id = ${escapeHogQLString(trimmedSearch)}
- OR person_id = ${escapeHogQLString(trimmedSearch)}
- )`
- )
- : hogql.raw('')
// Person filter is applied as a hard equality on `person_id`. The UUID is resolved
// client-side via `api.persons.list` (Django/Postgres) — we can't join `persons` in
// the invocations query itself because the two tables live on different CH clusters.
@@ -440,7 +487,7 @@ async function fetchSparkline(props: HogInvocationsLogicProps, filters: HogInvoc
HAVING argMax(is_deleted, version) = 0
${optionalStatusClause}
${optionalErrorKindClause}
- ${optionalSearchClause}
+ ${buildSearchClause(props, filters)}
${optionalPersonClause}
${problemClauseFor(props, filters)}
)
@@ -496,17 +543,6 @@ async function fetchRunsPage(
const optionalErrorKindClause = filters.error_kind?.length
? hogql.raw(`AND error_kind IN (${filters.error_kind.map(escapeHogQLString).join(', ')})`)
: hogql.raw('')
- const trimmedSearch = filters.search?.trim()
- const optionalSearchClause = trimmedSearch
- ? hogql.raw(
- `AND (
- invocation_id = ${escapeHogQLString(trimmedSearch)}
- OR event_uuid = ${escapeHogQLString(trimmedSearch)}
- OR distinct_id = ${escapeHogQLString(trimmedSearch)}
- OR person_id = ${escapeHogQLString(trimmedSearch)}
- )`
- )
- : hogql.raw('')
// Person filter is applied as a hard equality on `person_id`. The UUID is resolved
// client-side via `api.persons.list` (Django/Postgres) — we can't join `persons` in
// the invocations query itself because the two tables live on different CH clusters.
@@ -549,7 +585,7 @@ async function fetchRunsPage(
HAVING argMax(is_deleted, version) = 0
${optionalStatusClause}
${optionalErrorKindClause}
- ${optionalSearchClause}
+ ${buildSearchClause(props, filters)}
${optionalPersonClause}
${problemClauseFor(props, filters)}
${orderClause}
diff --git a/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx b/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx
index 22be591b6810..34d91d52f585 100644
--- a/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx
+++ b/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx
@@ -6,7 +6,7 @@ import { appMetricsLogic } from 'lib/components/AppMetrics/appMetricsLogic'
import { AppMetricsTrends } from 'lib/components/AppMetrics/AppMetricsTrends'
import { AppMetricSummary } from 'lib/components/AppMetrics/AppMetricSummary'
-import { EMAIL_METRIC_LOG_FILTERS, EmailMetric, WORKFLOW_EMAIL_METRICS } from './workflowMetricsSummaryLogic'
+import { EMAIL_METRIC_INVOCATION_FILTERS, EmailMetric, WORKFLOW_EMAIL_METRICS } from './workflowMetricsSummaryLogic'
const EMAIL_METRIC_KEYS = Object.keys(WORKFLOW_EMAIL_METRICS) as (keyof typeof WORKFLOW_EMAIL_METRICS)[]
@@ -43,7 +43,7 @@ export function EmailMetricsSummary({
<div className="flex flex-row gap-2 flex-wrap justify-center">
{EMAIL_METRIC_KEYS.map((key) => {
const metric = WORKFLOW_EMAIL_METRICS[key]
- const canDrillDown = !!onMetricClick && !!EMAIL_METRIC_LOG_FILTERS[key]
+ const canDrillDown = !!onMetricClick && !!EMAIL_METRIC_INVOCATION_FILTERS[key]
return (
<AppMetricSummary
key={key}
diff --git a/products/workflows/frontend/Workflows/WorkflowMetrics.tsx b/products/workflows/frontend/Workflows/WorkflowMetrics.tsx
index 33c312036c32..902c6533493e 100644
--- a/products/workflows/frontend/Workflows/WorkflowMetrics.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowMetrics.tsx
@@ -23,7 +23,7 @@ import { HogFlowBatchJob } from './hogflows/types'
import { PushMetricsSummary } from './PushMetricsSummary'
import { WorkflowLogicProps, workflowLogic } from './workflowLogic'
import { WorkflowMetricsSummary } from './WorkflowMetricsSummary'
-import { type EmailMetric, buildEmailMetricLogSearchParams } from './workflowMetricsSummaryLogic'
+import { type EmailMetric, buildEmailMetricInvocationSearchParams } from './workflowMetricsSummaryLogic'
const HedgehogGreek = pngHoggie(greekPng)
@@ -106,12 +106,19 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {
[workflow.actions, hogFunctionTemplatesById]
)
- // Drill an email metric into the logs tab filtered to its log entries over the current window.
+ // Drill an email metric into the invocations behind it over the current window.
const onEmailMetricClick = (metricKey: EmailMetric): void => {
+ if (!props.id) {
+ return
+ }
const { dateFrom, dateTo } = getDateRangeAbsolute()
- const searchParams = buildEmailMetricLogSearchParams(metricKey, dateFrom.toISOString(), dateTo.toISOString())
- if (searchParams && props.id) {
- router.actions.push(urls.workflow(props.id, 'logs'), searchParams)
+ const searchParams = buildEmailMetricInvocationSearchParams(
+ metricKey,
+ dateFrom.toISOString(),
+ dateTo.toISOString()
+ )
+ if (searchParams) {
+ router.actions.push(urls.workflow(props.id, 'invocations'), searchParams)
}
}
diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts
index ad83d15025d4..562ae4a1b571 100644
--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts
+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts
@@ -1,6 +1,11 @@
import { AppMetricsTimeSeriesResponse } from 'lib/components/AppMetrics/appMetricsLogic'
-import { subtractSeries, withDisplayName } from './workflowMetricsSummaryLogic'
+import {
+ type EmailMetric,
+ buildEmailMetricInvocationSearchParams,
+ subtractSeries,
+ withDisplayName,
+} from './workflowMetricsSummaryLogic'
const series = (labels: string[], ...namedValues: [string, number[]][]): AppMetricsTimeSeriesResponse => ({
labels,
@@ -73,3 +78,35 @@ describe('subtractSeries', () => {
expect(subtractSeries(minuend, subtrahend, displayName)).toEqual(expected)
})
})
+
+describe('buildEmailMetricInvocationSearchParams', () => {
+ const dateFrom = '2026-07-01T00:00:00.000Z'
+ const dateTo = '2026-07-13T00:00:00.000Z'
+
+ // Each metric drills into the Invocations tab via the unified search box (`inv_search`), narrowed
+ // to the level that distinguishes it: bounced/blocked at WARN/ERROR, bounce prevented
+ // ("Skipping send") at INFO.
+ it.each<[EmailMetric, Record<string, string>]>([
+ [
+ 'email_bounced',
+ { inv_date_from: dateFrom, inv_date_to: dateTo, inv_search: 'bounce', inv_log_levels: 'WARN,ERROR' },
+ ],
+ [
+ 'email_blocked',
+ { inv_date_from: dateFrom, inv_date_to: dateTo, inv_search: 'Complaint', inv_log_levels: 'WARN,ERROR' },
+ ],
+ [
+ 'email_bounce_prevented',
+ { inv_date_from: dateFrom, inv_date_to: dateTo, inv_search: 'Skipping send', inv_log_levels: 'INFO' },
+ ],
+ ])('maps %s to the expected Invocations-tab params', (metricKey, expected) => {
+ expect(buildEmailMetricInvocationSearchParams(metricKey, dateFrom, dateTo)).toEqual(expected)
+ })
+
+ it.each<EmailMetric>(['email_sent', 'email_delivered', 'email_opened', 'email_failed'])(
+ 'returns null for the non-drillable metric %s',
+ (metricKey) => {
+ expect(buildEmailMetricInvocationSearchParams(metricKey, dateFrom, dateTo)).toBeNull()
+ }
+ )
+})
diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
index 334300d62fc7..cf184062f24f 100644
--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
@@ -11,6 +11,7 @@ import {
type AppMetricsTotalsResponse,
} from 'lib/components/AppMetrics/appMetricsLogic'
import { dayjs } from 'lib/dayjs'
+import { buildHogInvocationsSearchParams } from 'scenes/hog-functions/invocations/hogInvocationsLogic'
import { urls } from 'scenes/urls'
import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'
@@ -201,38 +202,40 @@ export const WORKFLOW_PUSH_METRICS: Record<
},
}
-// Email metrics whose SES events also write per-invocation log entries (see the SES webhook
-// handler). Clicking the tile drills into the Invocations tab filtered to those log entries.
-// The `search` term matches the start of the log message the handler emits (e.g. "Permanent
-// bounce to …"), so it surfaces every invocation that logged that failure in the timeframe.
-export const EMAIL_METRIC_LOG_FILTERS: Partial<Record<EmailMetric, { search: string; levels: LogEntryLevel[] }>> = {
+// How each drillable email metric maps onto the Invocations tab. Each SES event also writes a
+// per-invocation log entry (see the SES webhook handler); the drill-down filters the tab to runs
+// that logged that entry by matching the message text at the right level. The `search` term matches
+// the start of the handler's message (e.g. "Permanent bounce to …"). email_failed is left out: its
+// two SES events emit differently-worded messages ("Rendering failure …" vs "Message rejected by
+// SES …") with no shared substring to match on.
+export const EMAIL_METRIC_INVOCATION_FILTERS: Partial<
+ Record<EmailMetric, { search: string; levels: LogEntryLevel[] }>
+> = {
email_bounced: { search: 'bounce', levels: ['WARN', 'ERROR'] },
// MX-validation skips log "Skipping send: …" at INFO (see HogFunctionHandler in the plugin server).
email_bounce_prevented: { search: 'Skipping send', levels: ['INFO'] },
email_blocked: { search: 'Complaint', levels: ['WARN', 'ERROR'] },
- // email_failed (RenderingFailure + Reject) is intentionally omitted: its two SES events emit
- // differently-worded messages ("Rendering failure …" vs "Message rejected by SES …") with no
- // shared substring, and filtering by ERROR level alone would also catch permanent bounces.
- // A reliable drill-down would need the log writer to emit a stable machine token to match on.
}
-// Build the router search params that point the Invocations (logs) tab at the invocations whose
-// log entries match the given email metric over the metrics view's current timeframe.
-export function buildEmailMetricLogSearchParams(
+// Build the router search params that point the Invocations tab at the runs behind the given email
+// metric over the metrics view's current timeframe.
+export function buildEmailMetricInvocationSearchParams(
metricKey: EmailMetric,
dateFrom: string,
dateTo: string
-): Record<string, string | string[]> | null {
- const filter = EMAIL_METRIC_LOG_FILTERS[metricKey]
+): Record<string, string> | null {
+ const filter = EMAIL_METRIC_INVOCATION_FILTERS[metricKey]
if (!filter) {
return null
}
- return {
- search: filter.search,
- levels: filter.levels,
+ return buildHogInvocationsSearchParams({
date_from: dateFrom,
date_to: dateTo,
- }
+ // Drives the unified Invocations search box: the message term goes in `search`, and
+ // `log_levels` narrows the message match to the levels that distinguish this outcome.
+ search: filter.search,
+ log_levels: filter.levels,
+ })
}
const SUMMARY_METRIC_KEYS = (Object.keys(WORKFLOW_SUMMARY_METRICS) as WorkflowSummaryMetric[]).filter(