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): incident replay banner for failed email sends (#85156)

Meikel Ratz06fafa11950b
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index e8eec149edbb..c9c7b1f18611 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -557,6 +557,7 @@ export const FEATURE_FLAGS = {
WEB_ANALYTICS_TOOLTIP_COMPARISON_LABELS: 'web-analytics-tooltip-comparison-labels', // owner: @lricoy #team-web-analytics
WORKFLOWS_EMAIL_REPUTATION: 'workflows-email-reputation', // owner: #team-workflows
WORKFLOWS_EMAIL_SENDER_ROTATION: 'workflows-email-sender-rotation', // owner: @arthurdedeus #team-workflows
+ WORKFLOWS_INCIDENT_REPLAY: 'workflows-incident-replay', // owner: #team-workflows
WORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflows
WORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflows
XAA_AUTHENTICATION: 'xaa-authentication', // owner: @reecejones #team-platform-features
diff --git a/nodejs/src/cdp/rerun/rerun-job.types.ts b/nodejs/src/cdp/rerun/rerun-job.types.ts
index 68a808abb606..98e1ffc215cc 100644
--- a/nodejs/src/cdp/rerun/rerun-job.types.ts
+++ b/nodejs/src/cdp/rerun/rerun-job.types.ts
@@ -55,6 +55,12 @@ export interface RerunFilter {
window_end: string
status?: RerunStatusValue[]
error_kind?: string[]
+ /**
+ * Case-insensitive substring match on the latest error_message. Isolates one
+ * failure mode where error_kind is too coarse — most app-level errors share
+ * the generic 'hog_error' kind.
+ */
+ error_message_contains?: string
max_attempts?: number
max_count?: number
invocation_ids?: string[]
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts
index 312c22ad01fb..c381ad32d156 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts
@@ -21,9 +21,16 @@ describe('RerunPaginatorService replay fidelity (hog_flow)', () => {
const teamId = 42
const functionId = 'flow-1'
- function fakeClickhouse(rows: unknown[]): ClickHouseClient {
+ function fakeClickhouse(rows: Array<Record<string, unknown>>): ClickHouseClient {
return {
- query: jest.fn().mockResolvedValue({ json: () => Promise.resolve(rows) }),
+ // The paginator runs two queries per page: the windowed page fetch and a
+ // cross-partition stale-status check on the page's ids. The stale check
+ // returns the ids that should be SKIPPED, so answer it with an empty set
+ // and these tests keep exercising rehydration rather than the stale skip.
+ query: jest.fn().mockImplementation(({ query }: { query: string }) => {
+ const payload = query.includes('hog_invocation_rerun_stale_status') ? [] : rows
+ return Promise.resolve({ json: () => Promise.resolve(payload) })
+ }),
} as unknown as ClickHouseClient
}
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
index a12d6969408d..d7c41f920978 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
@@ -456,6 +456,83 @@ describe('RerunPaginatorService integration', () => {
expect(next.progress.queued).toBe(1)
})
+ it('honours error_message_contains filter, case-insensitively', async () => {
+ await seedRows([
+ {
+ invocation_id: 'inv-sender',
+ status: 'failed',
+ error: new Error(
+ 'The custom sender address "[email protected]" is not a valid email address.'
+ ),
+ },
+ { invocation_id: 'inv-other', status: 'failed', error: new Error('Some unrelated hog error') },
+ ])
+
+ const state = buildState({
+ request: {
+ filter: {
+ window_start: '2026-01-01T00:00:00Z',
+ window_end: '2027-01-01T00:00:00Z',
+ // Deliberately lower-cased vs the stored message: a needle copied
+ // from logs must match regardless of capitalization.
+ error_message_contains: 'the custom sender address',
+ },
+ },
+ })
+
+ const { state: next } = await paginator.processPage(team.id, state, {
+ jobId: 'test-rerun-job',
+ createdAt: DateTime.now(),
+ })
+ const enqueued = hogQueue.queueInvocations.mock.calls[0]?.[0] as
+ | CyclotronJobInvocationHogFunction[]
+ | undefined
+ expect(enqueued?.map((i) => i.id)).toEqual(['inv-sender'])
+ expect(next.progress.queued).toBe(1)
+ })
+
+ it('skips invocations whose latest status outside the window no longer matches', async () => {
+ // Original failures inside a historical window...
+ await seedRows([
+ {
+ invocation_id: 'inv-replayed',
+ status: 'failed',
+ error: new Error('boom'),
+ scheduledAt: new Date('2026-02-01T10:00:00Z'),
+ },
+ {
+ invocation_id: 'inv-still-failed',
+ status: 'failed',
+ error: new Error('boom'),
+ scheduledAt: new Date('2026-02-01T11:00:00Z'),
+ },
+ ])
+ // ...then a successful replay of one of them lands its lifecycle row in the
+ // partition of its own scheduled_at, outside the window. The windowed page
+ // query still sees the old failed row, so without the cross-partition status
+ // check a second rerun would re-enqueue it and re-fire its side effects.
+ await seedRows([
+ { invocation_id: 'inv-replayed', status: 'succeeded', scheduledAt: new Date('2026-06-01T10:00:00Z') },
+ ])
+
+ const state = buildState({
+ request: {
+ filter: { window_start: '2026-02-01T00:00:00Z', window_end: '2026-02-02T00:00:00Z' },
+ },
+ })
+
+ const { state: next } = await paginator.processPage(team.id, state, {
+ jobId: 'test-rerun-job',
+ createdAt: DateTime.now(),
+ })
+ const enqueued = hogQueue.queueInvocations.mock.calls[0]?.[0] as
+ | CyclotronJobInvocationHogFunction[]
+ | undefined
+ expect(enqueued?.map((i) => i.id)).toEqual(['inv-still-failed'])
+ expect(next.progress.queued).toBe(1)
+ expect(next.progress.skipped).toBe(1)
+ })
+
it('honours max_count by capping queued+skipped at the user-provided limit', async () => {
await seedRows([
{ invocation_id: 'a', status: 'failed', error: new Error('5xx') },
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
index 4f508201d153..95ebfe320fb7 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.service.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
@@ -140,7 +140,26 @@ export class RerunPaginatorService {
const remainingBudget = this.remainingBudget(state)
const toProcess = rows.slice(0, remainingBudget)
- const { queued, skipped, queuedInvocations } = await this.rehydrateBatch(teamId, state, toProcess)
+ // A historical window can't see the newer lifecycle rows a prior replay wrote —
+ // they land in the partition of their own scheduled_at, outside the window — so
+ // the in-window collapse can report 'failed' for an invocation that has since
+ // succeeded. Re-check the page against each invocation's latest status across
+ // all partitions; without this, replaying the same window twice re-fires side
+ // effects (emails, webhooks) for already-recovered runs.
+ const staleStatusIds = await this.fetchStaleStatusInvocationIds(
+ teamId,
+ function_kind,
+ function_id,
+ toProcess.map((row) => row.invocation_id),
+ this.requestedStatus(state)
+ )
+
+ const { queued, skipped, queuedInvocations } = await this.rehydrateBatch(
+ teamId,
+ state,
+ toProcess,
+ staleStatusIds
+ )
let conflictSkipped = 0
if (queuedInvocations.length > 0) {
@@ -457,9 +476,54 @@ export class RerunPaginatorService {
return new Set(rows.map((r) => r.invocation_id))
}
+ private requestedStatus(state: RerunJobState): string[] {
+ const status = state.request.filter.status
+ return status?.length ? status : ['failed']
+ }
+
+ /**
+ * Of the given invocation ids, return those whose latest lifecycle row —
+ * across ALL partitions, not just the request window — no longer matches
+ * the requested statuses (or is deleted). Same primary-prefix keying as
+ * `fetchRunningInvocationIds`, so it stays cheap without a partition bound.
+ */
+ private async fetchStaleStatusInvocationIds(
+ teamId: number,
+ functionKind: RerunFunctionKind,
+ functionId: string,
+ invocationIds: string[],
+ requestedStatus: string[]
+ ): Promise<Set<string>> {
+ if (invocationIds.length === 0) {
+ return new Set()
+ }
+ const result = await this.clickhouse.query({
+ query: `/* team_id:${teamId} query_type:hog_invocation_rerun_stale_status */
+ SELECT invocation_id
+ FROM hog_invocation_results
+ WHERE team_id = {team_id:Int64}
+ AND function_kind = {function_kind:String}
+ AND function_id = {function_id:String}
+ AND invocation_id IN {invocation_ids:Array(String)}
+ GROUP BY invocation_id
+ HAVING argMax(is_deleted, version) = 1
+ OR argMax(status, version) NOT IN {requested_status:Array(String)}`,
+ query_params: {
+ team_id: teamId,
+ function_kind: functionKind,
+ function_id: functionId,
+ invocation_ids: invocationIds,
+ requested_status: requestedStatus,
+ },
+ format: 'JSONEachRow',
+ })
+ const rows = (await result.json()) as { invocation_id: string }[]
+ return new Set(rows.map((r) => r.invocation_id))
+ }
+
private async fetchPage(teamId: number, state: RerunJobState): Promise<InvocationRow[]> {
const filter = state.request.filter
- const requestedStatus = filter.status?.length ? filter.status : ['failed']
+ const requestedStatus = this.requestedStatus(state)
// The Django serializer accepts ISO 8601 ('2026-05-01T00:00:00Z'), but
// ClickHouse `DateTime64` only parses 'YYYY-MM-DD HH:MM:SS[.fff]'. Convert
// before passing as a query parameter. The bound params below are typed
@@ -483,6 +547,11 @@ export class RerunPaginatorService {
const errorKindClause = filter.error_kind?.length
? 'AND argMax(error_kind, version) IN {error_kind:Array(String)}'
: ''
+ // position() instead of LIKE so the needle requires no %/_ escaping. Case-insensitive so a
+ // needle copied from logs matches regardless of capitalization.
+ const errorMessageClause = filter.error_message_contains
+ ? 'AND positionCaseInsensitive(argMax(error_message, version), {error_message_contains:String}) > 0'
+ : ''
const maxAttemptsClause =
filter.max_attempts !== undefined ? 'AND argMax(attempts, version) < {max_attempts:UInt8}' : ''
// `invocation_ids` is an OPTIONAL additional restriction layered on top
@@ -518,6 +587,7 @@ export class RerunPaginatorService {
HAVING argMax(is_deleted, version) = 0
AND argMax(status, version) IN {status:Array(String)}
${errorKindClause}
+ ${errorMessageClause}
${maxAttemptsClause}
ORDER BY last_scheduled_at DESC, invocation_id DESC
LIMIT {limit:UInt32}`,
@@ -529,6 +599,7 @@ export class RerunPaginatorService {
window_end: windowEnd,
status: requestedStatus,
error_kind: filter.error_kind ?? [],
+ error_message_contains: filter.error_message_contains ?? '',
max_attempts: filter.max_attempts ?? 255,
invocation_ids: filter.invocation_ids ?? [],
cursor_scheduled_at: cursorScheduledAt,
@@ -544,7 +615,8 @@ export class RerunPaginatorService {
private async rehydrateBatch(
teamId: number,
state: RerunJobState,
- rows: InvocationRow[]
+ rows: InvocationRow[],
+ staleStatusIds: Set<string>
): Promise<{ queued: number; skipped: number; queuedInvocations: CyclotronJobInvocation[] }> {
const maxAttempts = state.request.filter.max_attempts
@@ -553,6 +625,12 @@ export class RerunPaginatorService {
// across concurrent callers, so a sequential loop would defeat that.
const rehydrated = await Promise.all(
rows.map(async (row): Promise<CyclotronJobInvocation | null> => {
+ // Stale rows stay in the page (the cursor advances over them) and count
+ // as skipped, so pagination never re-fetches them.
+ if (staleStatusIds.has(row.invocation_id)) {
+ counterRerunInvocationsSkipped.labels(state.function_kind, 'stale_status').inc()
+ return null
+ }
if (maxAttempts !== undefined && row.latest_attempts >= maxAttempts) {
counterRerunInvocationsSkipped.labels(state.function_kind, 'over_max_attempts').inc()
return null
diff --git a/posthog/api/hog_invocation_rerun.py b/posthog/api/hog_invocation_rerun.py
index 44858cc3b21f..c4384a9f3dbc 100644
--- a/posthog/api/hog_invocation_rerun.py
+++ b/posthog/api/hog_invocation_rerun.py
@@ -40,6 +40,15 @@ class HogInvocationRerunFilterSerializer(serializers.Serializer):
required=False,
help_text="Restrict to invocations whose error_kind matches one of these (e.g. 'http_5xx', 'timeout').",
)
+ error_message_contains = serializers.CharField(
+ required=False,
+ max_length=200,
+ help_text=(
+ "Restrict to invocations whose error_message contains this substring (case-insensitive). "
+ "Use to isolate one failure mode when error_kind is too coarse (most app-level errors "
+ "share the 'hog_error' kind)."
+ ),
+ )
max_attempts = serializers.IntegerField(
required=False,
min_value=1,
diff --git a/posthog/api/hog_invocation_results.py b/posthog/api/hog_invocation_results.py
index 3b208ba4e7ca..d32c1d58e7b3 100644
--- a/posthog/api/hog_invocation_results.py
+++ b/posthog/api/hog_invocation_results.py
@@ -14,6 +14,7 @@ from posthog.schema import ProductKey
from posthog.clickhouse.client.execute import sync_execute
from posthog.clickhouse.query_tagging import Feature, tag_queries
+from posthog.dataclasses import frozen
FUNCTION_KIND_TO_PRODUCT_KEY: dict[str, ProductKey] = {
"hog_function": ProductKey.PIPELINE_DESTINATIONS,
@@ -128,7 +129,9 @@ class HogInvocationResultDetailSerializer(DataclassSerializer):
dataclass = HogInvocationResultDetail
-class HogInvocationResultsRequestSerializer(serializers.Serializer):
+class HogInvocationResultsFiltersSerializer(serializers.Serializer):
+ """Filters shared by the invocation results list and count endpoints."""
+
status = serializers.CharField(
required=False,
help_text="Comma-separated invocation statuses to include, e.g. 'failed' or 'success,failed'.",
@@ -137,6 +140,14 @@ class HogInvocationResultsRequestSerializer(serializers.Serializer):
required=False,
help_text="Only return invocations triggered for this distinct_id (the person the run executed for).",
)
+ error_message_contains = serializers.CharField(
+ required=False,
+ max_length=200,
+ help_text=(
+ "Only return invocations whose latest error_message contains this substring (case-insensitive). "
+ "Matches the rerun endpoint's filter of the same name, so callers can check what a rerun would target."
+ ),
+ )
after = serializers.CharField(
required=False,
default="-7d",
@@ -147,6 +158,9 @@ class HogInvocationResultsRequestSerializer(serializers.Serializer):
required=False,
help_text="End of the time range, matched on scheduled time. Same format as 'after'. Defaults to now.",
)
+
+
+class HogInvocationResultsRequestSerializer(HogInvocationResultsFiltersSerializer):
limit = serializers.IntegerField(
required=False,
default=50,
@@ -156,6 +170,12 @@ class HogInvocationResultsRequestSerializer(serializers.Serializer):
)
+class HogInvocationResultsCountSerializer(serializers.Serializer):
+ count = serializers.IntegerField(
+ help_text="Number of invocations matching the filters, without the list endpoint's 500-row cap."
+ )
+
+
def _build_invocation(row: tuple, detail: bool) -> Any:
common = {
"invocation_id": row[0],
@@ -176,17 +196,25 @@ def _build_invocation(row: tuple, detail: bool) -> Any:
return HogInvocationResult(**common)
-def fetch_hog_invocation_results(
+@frozen
+class _InvocationResultsFilters:
+ """Shared WHERE clauses for the list and count queries, so their filters can't drift."""
+
+ where: list[str]
+ outer_where: list[str]
+ kwargs: dict[str, Any]
+
+
+def _build_invocation_results_filters(
team_id: int,
function_kind: str,
function_id: str,
- limit: int,
status: Optional[list[str]] = None,
distinct_id: Optional[str] = None,
+ error_message_contains: Optional[str] = None,
after: Optional[datetime] = None,
before: Optional[datetime] = None,
-) -> list[HogInvocationResult]:
- """List a function's invocations, each collapsed to its latest lifecycle state."""
+) -> _InvocationResultsFilters:
where = [
"team_id = %(team_id)s",
"function_kind = %(function_kind)s",
@@ -196,7 +224,6 @@ def fetch_hog_invocation_results(
"team_id": team_id,
"function_kind": function_kind,
"function_id": function_id,
- "limit": limit,
}
# distinct_id is invocation identity — stable across lifecycle rows — so filter
@@ -219,24 +246,94 @@ def fetch_hog_invocation_results(
if status:
outer_where.append("latest_status IN %(statuses)s")
kwargs["statuses"] = status
+ # Post-collapse like status: the message changes across lifecycle rows, so only the
+ # latest one reflects what the invocation actually failed with. positionCaseInsensitive
+ # instead of LIKE so the needle needs no %/_ escaping — mirrors the rerun paginator.
+ if error_message_contains:
+ outer_where.append("positionCaseInsensitive(latest_error_message, %(error_message_contains)s) > 0")
+ kwargs["error_message_contains"] = error_message_contains
+
+ return _InvocationResultsFilters(where=where, outer_where=outer_where, kwargs=kwargs)
+
+
+def fetch_hog_invocation_results(
+ team_id: int,
+ function_kind: str,
+ function_id: str,
+ limit: int,
+ status: Optional[list[str]] = None,
+ distinct_id: Optional[str] = None,
+ error_message_contains: Optional[str] = None,
+ after: Optional[datetime] = None,
+ before: Optional[datetime] = None,
+) -> list[HogInvocationResult]:
+ """List a function's invocations, each collapsed to its latest lifecycle state."""
+ filters = _build_invocation_results_filters(
+ team_id=team_id,
+ function_kind=function_kind,
+ function_id=function_id,
+ status=status,
+ distinct_id=distinct_id,
+ error_message_contains=error_message_contains,
+ after=after,
+ before=before,
+ )
+ filters.kwargs["limit"] = limit
query = f"""
SELECT {_OUTER_COLUMNS}
FROM (
SELECT {_COLLAPSED_AGGREGATES}
FROM hog_invocation_results
- WHERE {" AND ".join(where)}
+ WHERE {" AND ".join(filters.where)}
GROUP BY invocation_id
)
- WHERE {" AND ".join(outer_where)}
+ WHERE {" AND ".join(filters.outer_where)}
ORDER BY latest_scheduled_at DESC
LIMIT %(limit)s
"""
- results = cast(list, sync_execute(query, kwargs))
+ results = cast(list, sync_execute(query, filters.kwargs))
return [_build_invocation(row, detail=False) for row in results]
+def fetch_hog_invocation_results_count(
+ team_id: int,
+ function_kind: str,
+ function_id: str,
+ status: Optional[list[str]] = None,
+ distinct_id: Optional[str] = None,
+ error_message_contains: Optional[str] = None,
+ after: Optional[datetime] = None,
+ before: Optional[datetime] = None,
+) -> int:
+ """Count invocations matching the same filters as fetch_hog_invocation_results, without the row cap."""
+ filters = _build_invocation_results_filters(
+ team_id=team_id,
+ function_kind=function_kind,
+ function_id=function_id,
+ status=status,
+ distinct_id=distinct_id,
+ error_message_contains=error_message_contains,
+ after=after,
+ before=before,
+ )
+
+ query = f"""
+ SELECT count()
+ FROM (
+ SELECT {_COLLAPSED_AGGREGATES}
+ FROM hog_invocation_results
+ WHERE {" AND ".join(filters.where)}
+ GROUP BY invocation_id
+ )
+ WHERE {" AND ".join(filters.outer_where)}
+ """
+
+ results = cast(list, sync_execute(query, filters.kwargs))
+ return int(results[0][0]) if results else 0
+
+
def fetch_hog_invocation_result(
team_id: int,
function_kind: str,
diff --git a/products/cdp/frontend/generated/api.schemas.ts b/products/cdp/frontend/generated/api.schemas.ts
index c21e2e0c5838..8f8a7cae01b0 100644
--- a/products/cdp/frontend/generated/api.schemas.ts
+++ b/products/cdp/frontend/generated/api.schemas.ts
@@ -664,6 +664,11 @@ export interface HogInvocationRerunFilterApi {
status?: HogInvocationRerunFilterStatusEnumApi[]
/** Restrict to invocations whose error_kind matches one of these (e.g. 'http_5xx', 'timeout'). */
error_kind?: string[]
+ /**
+ * Restrict to invocations whose error_message contains this substring (case-insensitive). Use to isolate one failure mode when error_kind is too coarse (most app-level errors share the 'hog_error' kind).
+ * @maxLength 200
+ */
+ error_message_contains?: string
/**
* Skip invocations that have already been attempted this many times or more.
* @minimum 1
diff --git a/products/cdp/frontend/generated/api.zod.ts b/products/cdp/frontend/generated/api.zod.ts
index c39b76f74b97..febe2618e4c4 100644
--- a/products/cdp/frontend/generated/api.zod.ts
+++ b/products/cdp/frontend/generated/api.zod.ts
@@ -1539,6 +1539,8 @@ export const HogFunctionsPublishCreateBody = /* @__PURE__ */ zod.object({
* Because rerun replays historical event/person/group data, it requires
* `person:read` and `group:read` on top of `hog_function:write`.
*/
+export const hogFunctionsRerunCreateBodyFilterOneErrorMessageContainsMax = 200
+
export const hogFunctionsRerunCreateBodyFilterOneMaxAttemptsMax = 255
export const hogFunctionsRerunCreateBodyFilterOneMaxCountMax = 10000
@@ -1571,6 +1573,13 @@ export const HogFunctionsRerunCreateBody = /* @__PURE__ */ zod
.describe(
"Restrict to invocations whose error_kind matches one of these (e.g. 'http_5xx', 'timeout')."
),
+ error_message_contains: zod
+ .string()
+ .max(hogFunctionsRerunCreateBodyFilterOneErrorMessageContainsMax)
+ .optional()
+ .describe(
+ "Restrict to invocations whose error_message contains this substring (case-insensitive). Use to isolate one failure mode when error_kind is too coarse (most app-level errors share the 'hog_error' kind)."
+ ),
max_attempts: zod
.number()
.min(1)
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 011ea0a98d40..774475332bb5 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -41,10 +41,13 @@ from posthog.api.hog_invocation_cancel import (
from posthog.api.hog_invocation_rerun import HogInvocationRerunRequestSerializer, HogInvocationRerunResponseSerializer
from posthog.api.hog_invocation_results import (
HogInvocationResultDetailSerializer,
+ HogInvocationResultsCountSerializer,
HogInvocationResultSerializer,
+ HogInvocationResultsFiltersSerializer,
HogInvocationResultsRequestSerializer,
fetch_hog_invocation_result,
fetch_hog_invocation_results,
+ fetch_hog_invocation_results_count,
tag_invocation_results_query,
)
from posthog.api.log_entries import LogEntryMixin
@@ -2767,8 +2770,9 @@ class HogFlowViewSet(
# Invocation inspection returns distinct_id / person_id and the raw triggering payload
# (invocation_globals: event/person/groups), so it's person-data access — require person:read
# on top of workflow read, same as user_blast_radius. A hog_flow:read-only token must not be
- # able to enumerate who a workflow ran for.
- if self.action in ("invocation_results", "invocation_result"):
+ # able to enumerate who a workflow ran for. The count endpoint returns no person data but
+ # accepts a distinct_id filter, so without person:read it would be a person-existence oracle.
+ if self.action in ("invocation_results", "invocation_result", "invocation_results_count"):
return ["hog_flow:read", "person:read"]
# Assets expose recipient/distinct_id/person_id and the message bytes — require
# person:read so a hog_flow:read-only token can't enumerate who got emailed.
@@ -3864,11 +3868,49 @@ class HogFlowViewSet(
limit=params["limit"],
status=params["status"].split(",") if params.get("status") else None,
distinct_id=params.get("distinct_id"),
+ error_message_contains=params.get("error_message_contains"),
after=after_date,
before=before_date,
)
return Response(HogInvocationResultSerializer(data, many=True).data)
+ @extend_schema(
+ operation_id="hog_flows_invocation_results_count_retrieve",
+ parameters=[HogInvocationResultsFiltersSerializer],
+ responses=HogInvocationResultsCountSerializer,
+ )
+ @action(detail=True, methods=["GET"], pagination_class=None, filter_backends=[])
+ def invocation_results_count(self, request: Request, *args, **kwargs):
+ """
+ Count invocations matching the same filters as the list endpoint,
+ without its 500-row cap.
+ """
+ obj = self.get_object()
+ tag_invocation_results_query(self.function_kind)
+
+ param_serializer = HogInvocationResultsFiltersSerializer(data=request.query_params)
+ param_serializer.is_valid(raise_exception=True)
+ params = param_serializer.validated_data
+
+ after_date = None
+ before_date = None
+ if params.get("after"):
+ after_date, _, _ = relative_date_parse_with_delta_mapping(params["after"], self.team.timezone_info)
+ if params.get("before"):
+ before_date, _, _ = relative_date_parse_with_delta_mapping(params["before"], self.team.timezone_info)
+
+ count = fetch_hog_invocation_results_count(
+ team_id=self.team_id,
+ function_kind=self.function_kind,
+ function_id=str(obj.id),
+ status=params["status"].split(",") if params.get("status") else None,
+ distinct_id=params.get("distinct_id"),
+ error_message_contains=params.get("error_message_contains"),
+ after=after_date,
+ before=before_date,
+ )
+ return Response(HogInvocationResultsCountSerializer({"count": count}).data)
+
@extend_schema(
operation_id="hog_flows_invocation_result_retrieve",
parameters=[OpenApiParameter("invocation_id", str, OpenApiParameter.PATH)],
diff --git a/products/workflows/backend/api/test/test_hog_flow_invocation_results.py b/products/workflows/backend/api/test/test_hog_flow_invocation_results.py
index 8c79a4f3e06a..07b670378d38 100644
--- a/products/workflows/backend/api/test/test_hog_flow_invocation_results.py
+++ b/products/workflows/backend/api/test/test_hog_flow_invocation_results.py
@@ -147,6 +147,29 @@ class TestHogFlowInvocationResults(ClickhouseTestMixin, APIBaseTest):
results = self._list({"distinct_id": "user-a"}).json()
assert {r["invocation_id"] for r in results} == {"inv-1"}
+ def test_filters_by_error_message_contains_case_insensitively(self):
+ self._seed("inv-match", invocation_status="failed", error_message="The custom sender address is invalid")
+ self._seed("inv-match-case", invocation_status="failed", error_message="the CUSTOM sender address is bad")
+ self._seed("inv-other", invocation_status="failed", error_message="Some unrelated error")
+ results = self._list({"error_message_contains": "The custom sender"}).json()
+ assert {r["invocation_id"] for r in results} == {"inv-match", "inv-match-case"}
+
+ def test_count_matches_list_filters(self):
+ # The count endpoint must apply the same filters as the list endpoint, on the
+ # collapsed latest state - drifting filters would make the incident banner show
+ # a count the rerun wouldn't actually target.
+ self._seed("inv-match", invocation_status="failed", error_message="The custom sender address is invalid")
+ # Replayed since: latest status succeeded, must not count.
+ self._seed("inv-replayed", invocation_status="failed", error_message="The custom sender address is invalid")
+ self._seed("inv-replayed", invocation_status="success", version=2)
+ self._seed("inv-other", invocation_status="failed", error_message="Some unrelated error")
+ res = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow.id}/invocation_results_count/",
+ {"status": "failed", "error_message_contains": "the custom sender"},
+ )
+ assert res.status_code == status.HTTP_200_OK
+ assert res.json() == {"count": 1}
+
@parameterized.expand(
[
({"after": "-15d"}, {"inv-mid", "inv-late"}),
diff --git a/products/workflows/frontend/WorkflowsIncidentReplayBanner.tsx b/products/workflows/frontend/WorkflowsIncidentReplayBanner.tsx
new file mode 100644
index 000000000000..7c2bf4c30af7
--- /dev/null
+++ b/products/workflows/frontend/WorkflowsIncidentReplayBanner.tsx
@@ -0,0 +1,86 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+
+import { AccessControlAction } from 'lib/components/AccessControlAction'
+import { urls } from 'scenes/urls'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import { workflowsIncidentReplayLogic } from './workflowsIncidentReplayLogic'
+
+// Mirrors the server-side HOG_INVOCATION_RERUN_MAX_COUNT default: one rerun request
+// queues at most this many invocations, so larger workflows need a second pass.
+const RERUN_MAX_COUNT_PER_REQUEST = 10000
+
+export function WorkflowsIncidentReplayBanner(): JSX.Element | null {
+ const { showBanner, affectedWorkflows, replayStatusById, currentProjectId } =
+ useValues(workflowsIncidentReplayLogic)
+ const { replayWorkflow } = useActions(workflowsIncidentReplayLogic)
+
+ if (!showBanner) {
+ return null
+ }
+
+ const hasLargeWorkflow = affectedWorkflows.some((workflow) => workflow.failedCount > RERUN_MAX_COUNT_PER_REQUEST)
+
+ return (
+ <LemonBanner
+ type="warning"
+ // Per project: without the suffix, dismissing in one project hides the recovery
+ // path in every other project this browser visits.
+ dismissKey={`workflows-incident-replay-2026-08-17-${currentProjectId}`}
+ data-attr="workflows-incident-replay-banner"
+ >
+ <div className="flex flex-col gap-2">
+ <div>
+ Some of your workflow emails failed to send between August 17 and August 18 (UTC) because of an
+ incident on our side. You can replay the failed sends for each affected workflow below. Replaying
+ only re-runs what failed during that period.
+ {hasLargeWorkflow ? (
+ <>
+ {' '}
+ A replay covers up to 10,000 failed sends per run. For workflows with more, replay again
+ after the first run finishes to send the rest.
+ </>
+ ) : null}
+ </div>
+ <ul className="flex flex-col gap-1">
+ {affectedWorkflows.map((workflow) => {
+ const status = replayStatusById[workflow.id]
+ return (
+ <li key={workflow.id} className="flex items-center gap-2">
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Workflow}
+ minAccessLevel={AccessControlLevel.Editor}
+ userAccessLevel={workflow.userAccessLevel ?? undefined}
+ >
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ data-attr="workflows-incident-replay-button"
+ loading={status === 'pending'}
+ disabledReason={
+ status === 'queued'
+ ? 'Replay queued. Failed sends are being retried. Refresh the page to replay again once it finishes.'
+ : undefined
+ }
+ onClick={() => replayWorkflow(workflow.id)}
+ >
+ {status === 'queued' ? 'Replay queued' : 'Replay failed sends'}
+ </LemonButton>
+ </AccessControlAction>
+ <LemonButton size="xsmall" to={urls.workflow(workflow.id, 'workflow')}>
+ {workflow.name}
+ </LemonButton>
+ <span className="text-secondary">
+ {workflow.failedCount} failed {workflow.failedCount === 1 ? 'send' : 'sends'}
+ </span>
+ </li>
+ )
+ })}
+ </ul>
+ </div>
+ </LemonBanner>
+ )
+}
diff --git a/products/workflows/frontend/WorkflowsScene.tsx b/products/workflows/frontend/WorkflowsScene.tsx
index db6a3f3c618a..c952c112cb14 100644
--- a/products/workflows/frontend/WorkflowsScene.tsx
+++ b/products/workflows/frontend/WorkflowsScene.tsx
@@ -35,6 +35,7 @@ import { NewWorkflowModal } from './Workflows/NewWorkflowModal'
import { WorkflowsReputation } from './Workflows/Reputation/WorkflowsReputation'
import { WorkflowsTable } from './Workflows/WorkflowsTable'
import { workflowsEmailSuspensionLogic } from './workflowsEmailSuspensionLogic'
+import { WorkflowsIncidentReplayBanner } from './WorkflowsIncidentReplayBanner'
const WORKFLOW_SCENE_TABS = ['workflows', 'library', 'channels', 'opt-outs', 'suppression', 'reputation'] as const
export type WorkflowsSceneTab = (typeof WORKFLOW_SCENE_TABS)[number]
@@ -340,6 +341,7 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {
support to get sending re-enabled.
</LemonBanner>
)}
+ <WorkflowsIncidentReplayBanner />
<LemonTabs activeKey={currentTab} tabs={tabs} sceneInset data-attr="workflows-scene-tabs" />
<NewWorkflowModal />
</SceneContent>
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index b72ef88f06fd..bc7142f28c3e 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -911,6 +911,11 @@ export interface HogInvocationResultDetailApi {
is_retry: boolean
}
+export interface HogInvocationResultsCountApi {
+ /** Number of invocations matching the filters, without the list endpoint's 500-row cap. */
+ count: number
+}
+
/**
* Test trigger payload, typically {event, person, groups}.
*/
@@ -1088,6 +1093,11 @@ export interface HogInvocationRerunFilterApi {
status?: HogInvocationRerunFilterStatusEnumApi[]
/** Restrict to invocations whose error_kind matches one of these (e.g. 'http_5xx', 'timeout'). */
error_kind?: string[]
+ /**
+ * Restrict to invocations whose error_message contains this substring (case-insensitive). Use to isolate one failure mode when error_kind is too coarse (most app-level errors share the 'hog_error' kind).
+ * @maxLength 200
+ */
+ error_message_contains?: string
/**
* Skip invocations that have already been attempted this many times or more.
* @minimum 1
@@ -1574,6 +1584,12 @@ export type HogFlowsInvocationResultsRetrieveParams = {
* @minLength 1
*/
distinct_id?: string
+ /**
+ * Only return invocations whose latest error_message contains this substring (case-insensitive). Matches the rerun endpoint's filter of the same name, so callers can check what a rerun would target.
+ * @minLength 1
+ * @maxLength 200
+ */
+ error_message_contains?: string
/**
* Maximum number of invocations to return (1-500, default 50).
* @minimum 1
@@ -1587,6 +1603,35 @@ export type HogFlowsInvocationResultsRetrieveParams = {
status?: string
}
+export type HogFlowsInvocationResultsCountRetrieveParams = {
+ /**
+ * Start of the time range, matched on scheduled time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d — bounds the ClickHouse partition scan, so widen it explicitly for older runs.
+ * @minLength 1
+ */
+ after?: string
+ /**
+ * End of the time range, matched on scheduled time. Same format as 'after'. Defaults to now.
+ * @minLength 1
+ */
+ before?: string
+ /**
+ * Only return invocations triggered for this distinct_id (the person the run executed for).
+ * @minLength 1
+ */
+ distinct_id?: string
+ /**
+ * Only return invocations whose latest error_message contains this substring (case-insensitive). Matches the rerun endpoint's filter of the same name, so callers can check what a rerun would target.
+ * @minLength 1
+ * @maxLength 200
+ */
+ error_message_contains?: string
+ /**
+ * Comma-separated invocation statuses to include, e.g. 'failed' or 'success,failed'.
+ * @minLength 1
+ */
+ status?: string
+}
+
export type HogFlowsLogsRetrieveParams = {
/**
* Only return entries after this ISO 8601 timestamp. Defaults to 7 days ago; pass an explicit value to read further back.
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 885b46394ab5..9b5d5a7526cb 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -28,6 +28,7 @@ import type {
HogFlowTemplatesLogsRetrieveParams,
HogFlowsAssetContentRetrieveParams,
HogFlowsAssetsRetrieveParams,
+ HogFlowsInvocationResultsCountRetrieveParams,
HogFlowsInvocationResultsRetrieveParams,
HogFlowsListParams,
HogFlowsLogsRetrieveParams,
@@ -42,6 +43,7 @@ import type {
HogInvocationRerunResponseApi,
HogInvocationResultApi,
HogInvocationResultDetailApi,
+ HogInvocationResultsCountApi,
MessageAssetApi,
PaginatedHogFlowMinimalListApi,
PaginatedHogFlowRevisionBasicListApi,
@@ -557,6 +559,45 @@ export const hogFlowsInvocationResultRetrieve = async (
)
}
+export const getHogFlowsInvocationResultsCountRetrieveUrl = (
+ projectId: string,
+ id: string,
+ params?: HogFlowsInvocationResultsCountRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/hog_flows/${id}/invocation_results_count/?${stringifiedParams}`
+ : `/api/projects/${projectId}/hog_flows/${id}/invocation_results_count/`
+}
+
+/**
+ * Count invocations matching the same filters as the list endpoint,
+ * without its 500-row cap.
+ */
+export const hogFlowsInvocationResultsCountRetrieve = async (
+ projectId: string,
+ id: string,
+ params?: HogFlowsInvocationResultsCountRetrieveParams,
+ options?: RequestInit
+): Promise<HogInvocationResultsCountApi> => {
+ return apiMutator<HogInvocationResultsCountApi>(
+ getHogFlowsInvocationResultsCountRetrieveUrl(projectId, id, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
export const getHogFlowsInvocationsCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/hog_flows/${id}/invocations/`
}
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index deee26b9adee..0d9fa0b522cc 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -2164,6 +2164,8 @@ export const HogFlowsPublishCreateBody = /* @__PURE__ */ zod.object({
* Because rerun replays historical event/person/group data, it requires
* `person:read` and `group:read` on top of `hog_flow:write`.
*/
+export const hogFlowsRerunCreateBodyFilterOneErrorMessageContainsMax = 200
+
export const hogFlowsRerunCreateBodyFilterOneMaxAttemptsMax = 255
export const hogFlowsRerunCreateBodyFilterOneMaxCountMax = 10000
@@ -2196,6 +2198,13 @@ export const HogFlowsRerunCreateBody = /* @__PURE__ */ zod
.describe(
"Restrict to invocations whose error_kind matches one of these (e.g. 'http_5xx', 'timeout')."
),
+ error_message_contains: zod
+ .string()
+ .max(hogFlowsRerunCreateBodyFilterOneErrorMessageContainsMax)
+ .optional()
+ .describe(
+ "Restrict to invocations whose error_message contains this substring (case-insensitive). Use to isolate one failure mode when error_kind is too coarse (most app-level errors share the 'hog_error' kind)."
+ ),
max_attempts: zod
.number()
.min(1)
diff --git a/products/workflows/frontend/workflowsIncidentReplayLogic.ts b/products/workflows/frontend/workflowsIncidentReplayLogic.ts
new file mode 100644
index 000000000000..313690cae3d2
--- /dev/null
+++ b/products/workflows/frontend/workflowsIncidentReplayLogic.ts
@@ -0,0 +1,249 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
+
+import { loadAppMetricsTotals } from 'lib/components/AppMetrics/appMetricsLogic'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { projectLogic } from 'scenes/projectLogic'
+
+import { AccessControlLevel } from '~/types'
+
+import {
+ hogFlowsInvocationResultsCountRetrieve,
+ hogFlowsList,
+ hogFlowsRerunCreate,
+} from 'products/workflows/frontend/generated/api'
+
+// The window of the 2026-08-17 email send incident (UTC), padded around the first and last
+// observed failures. Both the affected-workflow lookup and the rerun filter use it, so a
+// replay only re-enqueues invocations that failed during the incident.
+const INCIDENT_WINDOW_START = '2026-08-17T13:00:00.000Z'
+const INCIDENT_WINDOW_END = '2026-08-18T22:00:00.000Z'
+
+// Both messages the regression threw start with this, and no other failure mode does, so the
+// rerun skips failures unrelated to the incident (e.g. a genuinely broken integration) even
+// inside the window. Matches the pre-fix messages in email.service.ts (resolveFromEmailAddress).
+const INCIDENT_ERROR_MESSAGE_PREFIX = 'The custom sender address'
+
+export interface AffectedWorkflow {
+ id: string
+ name: string
+ failedCount: number
+ userAccessLevel: AccessControlLevel | null
+}
+
+export type ReplayStatus = 'pending' | 'queued'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workflowsIncidentReplayLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ currentProjectId: number | null // projectLogic
+ affectedWorkflows: AffectedWorkflow[]
+ affectedWorkflowsLoading: boolean
+ replayStatusById: Record<string, ReplayStatus>
+ showBanner: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workflowsIncidentReplayLogicActions {
+ loadAffectedWorkflows: () => any
+ loadAffectedWorkflowsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAffectedWorkflowsSuccess: (
+ affectedWorkflows: {
+ failedCount: number
+ id: string
+ name: string
+ userAccessLevel: AccessControlLevel | null
+ }[],
+ payload?: any
+ ) => {
+ affectedWorkflows: {
+ failedCount: number
+ id: string
+ name: string
+ userAccessLevel: AccessControlLevel | null
+ }[]
+ payload?: any
+ }
+ replayWorkflow: (id: string) => {
+ id: string
+ }
+ replayWorkflowFailure: (id: string) => {
+ id: string
+ }
+ replayWorkflowSuccess: (id: string) => {
+ id: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workflowsIncidentReplayLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ showBanner: (featureFlags: FeatureFlagsSet, affectedWorkflows: AffectedWorkflow[]) => boolean
+ }
+}
+
+export type workflowsIncidentReplayLogicType = MakeLogicType<
+ workflowsIncidentReplayLogicValues,
+ workflowsIncidentReplayLogicActions,
+ Record<string, any>,
+ workflowsIncidentReplayLogicMeta
+>
+
+export const workflowsIncidentReplayLogic = kea<workflowsIncidentReplayLogicType>([
+ path(['products', 'workflows', 'frontend', 'workflowsIncidentReplayLogic']),
+ connect(() => ({
+ values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags']],
+ })),
+ actions({
+ replayWorkflow: (id: string) => ({ id }),
+ replayWorkflowSuccess: (id: string) => ({ id }),
+ replayWorkflowFailure: (id: string) => ({ id }),
+ }),
+ loaders(({ values }) => ({
+ affectedWorkflows: [
+ [] as AffectedWorkflow[],
+ {
+ loadAffectedWorkflows: async () => {
+ if (!values.currentProjectId) {
+ return []
+ }
+
+ const totals = await loadAppMetricsTotals(
+ {
+ appSource: 'hog_flow',
+ metricName: 'email_failed',
+ breakdownBy: ['app_source_id'],
+ dateFrom: INCIDENT_WINDOW_START,
+ dateTo: INCIDENT_WINDOW_END,
+ limit: 100,
+ },
+ 'UTC'
+ )
+
+ const affected = Object.values(totals)
+ .map((row) => ({ id: row.breakdowns[0], failedCount: row.total }))
+ .filter((row) => row.id && row.failedCount > 0)
+
+ if (affected.length === 0) {
+ return []
+ }
+
+ // Keep only workflows the list endpoint returns: it applies object-level
+ // access control, so this never names a workflow the user can't see, and it
+ // drops deleted workflows, which can't be replayed anyway.
+ const projectId = String(values.currentProjectId)
+ const flows = await hogFlowsList(projectId, { limit: 300 })
+ const flowsById = new Map((flows.results ?? []).map((flow) => [flow.id, flow]))
+ const visible = affected.filter((row) => flowsById.has(row.id))
+
+ if (visible.length === 0) {
+ return []
+ }
+
+ // App metrics are historical counters, so a fully replayed workflow would sit in
+ // the banner forever, and their counts can't be narrowed to the incident's error.
+ // Count the still-failing invocations that carry the incident message instead -
+ // the same server-side filter the rerun uses - so the displayed number is what a
+ // replay would actually target, it shrinks as a replay drains, and the workflow
+ // drops off at zero. A count that errors falls back to the metric total and keeps
+ // the row (never hide the recovery path on a transient failure).
+ //
+ // No `before`: replay lifecycle rows land in the partition of their own
+ // scheduled_at (replay time), so capping at the window end would hide them and
+ // a replayed invocation would read as failed forever. `after` alone bounds the
+ // partition scan; the failed-status collapse then reflects the true latest state.
+ const remainingCounts = await Promise.all(
+ visible.map(async (row) => {
+ try {
+ const response = await hogFlowsInvocationResultsCountRetrieve(projectId, row.id, {
+ status: 'failed',
+ error_message_contains: INCIDENT_ERROR_MESSAGE_PREFIX,
+ after: INCIDENT_WINDOW_START,
+ })
+ return response.count
+ } catch {
+ return row.failedCount
+ }
+ })
+ )
+
+ return visible
+ .map((row, index) => {
+ const flow = flowsById.get(row.id)
+ return {
+ id: row.id,
+ name: flow?.name ?? '',
+ failedCount: remainingCounts[index],
+ userAccessLevel: (flow?.user_access_level ?? null) as AccessControlLevel | null,
+ }
+ })
+ .filter((row) => row.failedCount > 0)
+ .sort((a, b) => b.failedCount - a.failedCount)
+ },
+ },
+ ],
+ })),
+ reducers({
+ replayStatusById: [
+ {} as Record<string, ReplayStatus>,
+ {
+ replayWorkflow: (state, { id }) => ({ ...state, [id]: 'pending' }),
+ replayWorkflowSuccess: (state, { id }) => ({ ...state, [id]: 'queued' }),
+ replayWorkflowFailure: (state, { id }) => {
+ const { [id]: _discarded, ...rest } = state
+ return rest
+ },
+ },
+ ],
+ }),
+ selectors({
+ showBanner: [
+ (s) => [s.featureFlags, s.affectedWorkflows],
+ (featureFlags: FeatureFlagsSet, affectedWorkflows: AffectedWorkflow[]): boolean =>
+ !!featureFlags[FEATURE_FLAGS.WORKFLOWS_INCIDENT_REPLAY] && affectedWorkflows.length > 0,
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ replayWorkflow: async ({ id }) => {
+ if (!values.currentProjectId) {
+ actions.replayWorkflowFailure(id)
+ return
+ }
+ try {
+ await hogFlowsRerunCreate(String(values.currentProjectId), id, {
+ filter: {
+ window_start: INCIDENT_WINDOW_START,
+ window_end: INCIDENT_WINDOW_END,
+ error_message_contains: INCIDENT_ERROR_MESSAGE_PREFIX,
+ },
+ })
+ actions.replayWorkflowSuccess(id)
+ lemonToast.success('Replay queued. Failed sends will be retried shortly.')
+ } catch {
+ actions.replayWorkflowFailure(id)
+ lemonToast.error("Couldn't queue the replay. Try again, and contact support if it keeps happening.")
+ }
+ },
+ })),
+ // A subscription instead of afterMount: flags can resolve after the logic mounts, and a
+ // one-time mount check would then never load. This fires with the value at mount and again
+ // when the flag flips on, so only flagged (affected) teams pay for the lookup query.
+ subscriptions(({ actions }) => ({
+ featureFlags: (featureFlags: FeatureFlagsSet, oldFeatureFlags: FeatureFlagsSet | undefined) => {
+ const isOn = !!featureFlags[FEATURE_FLAGS.WORKFLOWS_INCIDENT_REPLAY]
+ const wasOn = !!oldFeatureFlags?.[FEATURE_FLAGS.WORKFLOWS_INCIDENT_REPLAY]
+ if (isOn && !wasOn) {
+ actions.loadAffectedWorkflows()
+ }
+ },
+ })),
+])
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index d400329d44c3..9dd3b9ac1611 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -63,6 +63,9 @@ tools:
hog-flows-email-sending-suspension-retrieve:
operation: hog_flows_email_sending_suspension_retrieve
enabled: false
+ hog-flows-invocation-results-count-retrieve:
+ operation: hog_flows_invocation_results_count_retrieve
+ enabled: false
hog-flows-invocations-cancel-create:
operation: hog_flows_invocations_cancel_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6e2b79a10fa7..26ed93ebef04 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -40429,6 +40429,11 @@ export namespace Schemas {
status?: HogInvocationRerunFilterStatusEnum[];
/** Restrict to invocations whose error_kind matches one of these (e.g. 'http_5xx', 'timeout'). */
error_kind?: string[];
+ /**
+ * Restrict to invocations whose error_message contains this substring (case-insensitive). Use to isolate one failure mode when error_kind is too coarse (most app-level errors share the 'hog_error' kind).
+ * @maxLength 200
+ */
+ error_message_contains?: string;
/**
* Skip invocations that have already been attempted this many times or more.
* @minimum 1
@@ -40514,6 +40519,11 @@ export namespace Schemas {
is_retry: boolean;
}
+ export interface HogInvocationResultsCount {
+ /** Number of invocations matching the filters, without the list endpoint's 500-row cap. */
+ count: number;
+ }
+
export type HogLanguage = typeof HogLanguage[keyof typeof HogLanguage];
@@ -88414,6 +88424,12 @@ export namespace Schemas {
* @minLength 1
*/
distinct_id?: string;
+ /**
+ * Only return invocations whose latest error_message contains this substring (case-insensitive). Matches the rerun endpoint's filter of the same name, so callers can check what a rerun would target.
+ * @minLength 1
+ * @maxLength 200
+ */
+ error_message_contains?: string;
/**
* Maximum number of invocations to return (1-500, default 50).
* @minimum 1
@@ -88427,6 +88443,35 @@ export namespace Schemas {
status?: string;
};
+ export type HogFlowsInvocationResultsCountRetrieveParams = {
+ /**
+ * Start of the time range, matched on scheduled time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d — bounds the ClickHouse partition scan, so widen it explicitly for older runs.
+ * @minLength 1
+ */
+ after?: string;
+ /**
+ * End of the time range, matched on scheduled time. Same format as 'after'. Defaults to now.
+ * @minLength 1
+ */
+ before?: string;
+ /**
+ * Only return invocations triggered for this distinct_id (the person the run executed for).
+ * @minLength 1
+ */
+ distinct_id?: string;
+ /**
+ * Only return invocations whose latest error_message contains this substring (case-insensitive). Matches the rerun endpoint's filter of the same name, so callers can check what a rerun would target.
+ * @minLength 1
+ * @maxLength 200
+ */
+ error_message_contains?: string;
+ /**
+ * Comma-separated invocation statuses to include, e.g. 'failed' or 'success,failed'.
+ * @minLength 1
+ */
+ status?: string;
+ };
+
export type HogFlowsLogsRetrieveParams = {
/**
* Only return entries after this ISO 8601 timestamp. Defaults to 7 days ago; pass an explicit value to read further back.
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index d1a42f1f5a41..778431970b00 100644
--- a/services/mcp/src/generated/workflows/api.ts
+++ b/services/mcp/src/generated/workflows/api.ts
@@ -734,6 +734,8 @@ export const HogFlowsInvocationResultsRetrieveParams = /* @__PURE__ */ zod.objec
export const hogFlowsInvocationResultsRetrieveQueryAfterDefault = `-7d`
+export const hogFlowsInvocationResultsRetrieveQueryErrorMessageContainsMax = 200
+
export const hogFlowsInvocationResultsRetrieveQueryLimitDefault = 50
export const hogFlowsInvocationResultsRetrieveQueryLimitMax = 500
@@ -755,6 +757,14 @@ export const HogFlowsInvocationResultsRetrieveQueryParams = /* @__PURE__ */ zod.
.min(1)
.optional()
.describe('Only return invocations triggered for this distinct_id (the person the run executed for).'),
+ error_message_contains: zod
+ .string()
+ .min(1)
+ .max(hogFlowsInvocationResultsRetrieveQueryErrorMessageContainsMax)
+ .optional()
+ .describe(
+ "Only return invocations whose latest error_message contains this substring (case-insensitive). Matches the rerun endpoint's filter of the same name, so callers can check what a rerun would target."
+ ),
limit: zod
.number()
.min(1)
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index 1c6b0c3e3abf..53a50cbca55c 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -230,6 +230,7 @@ const workflowsListInvocations = (): ToolBase<
after: params.after,
before: params.before,
distinct_id: params.distinct_id,
+ error_message_contains: params.error_message_contains,
limit: params.limit,
status: params.status,
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-invocations.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-invocations.json
index 80a052e43489..c8d1bb7ccc75 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-invocations.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-invocations.json
@@ -17,6 +17,12 @@
"minLength": 1,
"type": "string"
},
+ "error_message_contains": {
+ "description": "Only return invocations whose latest error_message contains this substring (case-insensitive). Matches the rerun endpoint's filter of the same name, so callers can check what a rerun would target.",
+ "maxLength": 200,
+ "minLength": 1,
+ "type": "string"
+ },
"id": {
"description": "A UUID string identifying this hog flow.",
"type": "string"