: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cdp): rerun invocations API and Runs tab (#65748)
Daniel Marchukdbd5796621c3
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 44eaa78225b4..12aa3f7b9dba 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -320,6 +320,7 @@ export const FEATURE_FLAGS = {FUNNEL_INSIGHT_ALERTS: 'funnel-insight-alerts', // owner: @vdekrijger, gates alerts on funnel insights (conversion rate)GROUP_PROFILE_EXPERIMENT: 'group-profile-experiment', // owner: @arthurdedeus #team-customer-analyticsHEALTH_ASK_AI: 'health-ask-ai', // owner: @jordanm-posthog #team-web-analytics, gates the "Ask PostHog AI" buttons on the Health overview+ HOG_INVOCATION_RESULTS_RUNS_TAB: 'hog-invocation-results-runs-tab', // owner: #team-workflowsHOGQL_INSIGHT_ALERTS: 'hogql-insight-alerts', // owner: @vdekrijger, gates alerts on SQL-backed (HogQL) insightsHOGQL_WAREHOUSE_ACCESS_CONTROL: 'hogql-warehouse-access-control', // owner: @a-lider #team-platform-features, gates per-object access control for warehouse tables and viewsIDENTITY_MATCHING: 'identity-matching', // owner: @fercgomes #team-growth, gates new identity matching scene on marketing analyticsdiff --git a/frontend/src/scenes/hog-functions/HogFunctionScene.tsx b/frontend/src/scenes/hog-functions/HogFunctionScene.tsxindex 207aae7e1d58..c4fde5684f44 100644--- a/frontend/src/scenes/hog-functions/HogFunctionScene.tsx+++ b/frontend/src/scenes/hog-functions/HogFunctionScene.tsx@@ -42,11 +42,21 @@ import {} from './configuration/components/HogFunctionConfigurationButtons'import { HogFunctionIconEditable } from './configuration/HogFunctionIcon'import type { hogFunctionSceneLogicType } from './HogFunctionSceneType'+import { HogInvocations } from './invocations/HogInvocations'import { HogFunctionMetrics } from './metrics/HogFunctionMetrics'import { HogFunctionSkeleton } from './misc/HogFunctionSkeleton'import { HogFunctionRuns } from './runs/HogFunctionRuns'-const HOG_FUNCTION_SCENE_TABS = ['configuration', 'metrics', 'logs', 'testing', 'runs', 'backfills', 'history'] as const+const HOG_FUNCTION_SCENE_TABS = [+ 'configuration',+ 'metrics',+ 'logs',+ 'testing',+ 'runs',+ 'invocations',+ 'backfills',+ 'history',+] as constexport type HogFunctionSceneTab = (typeof HOG_FUNCTION_SCENE_TABS)[number]const HogFunctionSceneMapping: Partial<Record<HogFunctionTypeType, { scene: Scene; url: () => string }>> = {@@ -435,6 +445,25 @@ export function HogFunctionScene(): JSX.Element {key: 'logs',content: <HogFunctionLogs />,},+ // New runs view backed by hog_invocation_results. Behind a flag while+ // the underlying ClickHouse producer ramps; subsumes the legacy+ // logs tab once it's GA.+ type === 'site_app' ||+ type === 'site_destination' ||+ !featureFlags[FEATURE_FLAGS.HOG_INVOCATION_RESULTS_RUNS_TAB]+ ? null+ : {+ label: (+ <div className="flex flex-row">+ <div>Invocations</div>+ <LemonTag className="ml-2 uppercase" type="warning">+ Beta+ </LemonTag>+ </div>+ ),+ key: 'invocations',+ content: <HogInvocations id={id} functionKind="hog_function" />,+ },type === 'site_app' || type === 'site_destination' || type === 'internal_destination'? null: {diff --git a/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx b/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsxnew file mode 100644index 000000000000..92b931538655--- /dev/null+++ b/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx@@ -0,0 +1,1013 @@+import { useActions, useValues } from 'kea'+import { ReactNode, useEffect, useState } from 'react'++import { IconChevronDown, IconRefresh, IconRevert, IconSearch, IconWarning } from '@posthog/icons'+import {+ LemonButton,+ LemonCheckbox,+ LemonDialog,+ LemonDropdown,+ LemonInput,+ LemonInputSelect,+ LemonModal,+ LemonSelect,+ LemonTable,+ LemonTableColumns,+ LemonTag,+ LemonTagProps,+ Tooltip,+} from '@posthog/lemon-ui'++import api from 'lib/api'+import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'+import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'+import { TZLabel } from 'lib/components/TZLabel'+import { dayjs } from 'lib/dayjs'+import { Link } from 'lib/lemon-ui/Link'+import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils/datetime'+import { PersonDisplay } from 'scenes/persons/PersonDisplay'+import { urls } from 'scenes/urls'++import { escapeHogQLString, hogql } from '~/queries/utils'+import { DateMappingOption } from '~/types'++import { LogsViewer } from '../logs/LogsViewer'+import { LogsViewerLogicProps } from '../logs/logsViewerLogic'+import { renderHogFunctionMessage } from '../logs/renderHogFunctionMessage'+import {+ BulkRerunParams,+ HOG_INVOCATIONS_RERUN_MAX_COUNT,+ HogInvocationRow,+ HogInvocationsFilters,+ HogInvocationsFunctionKind,+ HogInvocationsLogicProps,+ RunStatus,+ dateClauseFor,+ hogInvocationsLogic,+ isRerunWrapperKind,+} from './hogInvocationsLogic'+import { InvocationsSparkline } from './InvocationsSparkline'+import { InvocationsBetaBanner } from './InvocationsTabBanners'++const STATUS_OPTIONS: { value: RunStatus; label: string }[] = [+ { value: 'running', label: 'Running' },+ { value: 'succeeded', label: 'Succeeded' },+ { value: 'failed', label: 'Failed' },+]++/**+ * Preset windows mirroring the Logs viewer — covers minute-level scoping+ * (5m / 30m / 1h) plus the longer windows the table already supported.+ * Pairs with `allowTimePrecision` + `allowFixedRangeWithTime` so custom+ * ranges accept minute-precision timestamps.+ */+const INVOCATIONS_DATE_OPTIONS: DateMappingOption[] = [+ { key: CUSTOM_OPTION_KEY, values: [] },+ {+ key: 'Last 5 minutes',+ values: ['-5M'],+ getFormattedDate: (date) => date.subtract(5, 'minute').format(DATE_TIME_FORMAT),+ defaultInterval: 'minute',+ },+ {+ key: 'Last 30 minutes',+ values: ['-30M'],+ getFormattedDate: (date) => date.subtract(30, 'minute').format(DATE_TIME_FORMAT),+ defaultInterval: 'minute',+ },+ {+ key: 'Last 1 hour',+ values: ['-1h'],+ getFormattedDate: (date: dayjs.Dayjs) => formatDateRange(date.subtract(1, 'h'), date),+ defaultInterval: 'hour',+ },+ {+ key: 'Last 4 hours',+ values: ['-4h'],+ getFormattedDate: (date: dayjs.Dayjs) => formatDateRange(date.subtract(4, 'h'), date),+ defaultInterval: 'hour',+ },+ {+ key: 'Last 24 hours',+ values: ['-24h'],+ getFormattedDate: (date: dayjs.Dayjs) => formatDateRange(date.subtract(24, 'h'), date.endOf('d')),+ defaultInterval: 'hour',+ },+ {+ key: 'Last 7 days',+ values: ['-7d'],+ getFormattedDate: (date: dayjs.Dayjs) => formatDateRange(date.subtract(7, 'd'), date.endOf('d')),+ defaultInterval: 'day',+ },+ {+ key: 'Last 30 days',+ values: ['-30d'],+ getFormattedDate: (date: dayjs.Dayjs) => formatDateRange(date.subtract(30, 'd'), date.endOf('d')),+ defaultInterval: 'day',+ },+]++const tagTypeForStatus = (status: RunStatus): LemonTagProps['type'] => {+ switch (status) {+ case 'succeeded':+ return 'success'+ case 'failed':+ return 'danger'+ case 'running':+ default:+ return 'warning'+ }+}++const formatDurationMs = (ms: number | null): string => {+ if (ms === null || ms === undefined) {+ return '—'+ }+ if (ms < 1000) {+ return `${ms} ms`+ }+ return `${(ms / 1000).toFixed(2)} s`+}++const shortId = (id: string): string =>+ id+ .split('-')+ .map((p) => p.slice(0, 2))+ .join('')++const UUID_REGEX = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i+const shortPersonDisplay = (row: { person_id: string; distinct_id: string }): string => {+ const candidate = row.distinct_id || row.person_id || ''+ if (UUID_REGEX.test(candidate)) {+ return `${candidate.slice(0, 4)}…${candidate.slice(-4)}`+ }+ return candidate+}++const rowRibbonColorFor = (row: HogInvocationRow): string | null => {+ if (isRerunWrapperKind(row.function_kind)) {+ return 'var(--info)'+ }+ if (row.status === 'failed') {+ return 'var(--danger)'+ }+ if (row.status === 'running') {+ return 'var(--warning)'+ }+ if (row.status === 'succeeded') {+ return 'var(--success)'+ }+ return null+}++/**+ * Live count for the re-run modal — mirrors the worker's predicate shape+ * (window + status + error_kind + max_attempts) but skips `max_count`+ * (server-side ceiling, not a row filter).+ */+async function countRerunMatches(+ props: { id: string; functionKind: HogInvocationsFunctionKind },+ params: BulkRerunParams+): Promise<number> {+ const statusClause = params.status?.length+ ? hogql.raw(`AND status IN (${params.status.map(escapeHogQLString).join(',')})`)+ : hogql.raw('')+ const errorKindClause = params.error_kind?.length+ ? hogql.raw(`AND error_kind IN (${params.error_kind.map(escapeHogQLString).join(',')})`)+ : hogql.raw('')+ const maxAttemptsClause =+ typeof params.max_attempts === 'number' ? hogql.raw(`AND attempts < ${params.max_attempts}`) : hogql.raw('')+ // Reuse the same inline date clause shape the list / sparkline use.+ const dateClause = dateClauseFor({+ date_from: params.date_from,+ date_to: params.date_to,+ } as HogInvocationsFilters)++ const query = hogql`+ SELECT count() FROM (+ SELECT+ invocation_id,+ argMax(status, version) AS status,+ argMax(error_kind, version) AS error_kind,+ max(attempts) AS attempts+ FROM posthog.hog_invocation_results+ WHERE function_kind = ${props.functionKind}+ AND function_id = ${props.id}+ ${dateClause}+ GROUP BY invocation_id+ HAVING argMax(is_deleted, version) = 0+ ${statusClause}+ ${errorKindClause}+ ${maxAttemptsClause}+ )+ `+ const response = await api.queryHogQL(query, {+ scene: 'HogInvocations',+ productKey: 'pipeline_destinations',+ })+ const row = response.results?.[0]+ return Array.isArray(row) ? Number(row[0] ?? 0) : 0+}++export interface HogInvocationsProps extends HogInvocationsLogicProps {+ /**+ * Override how a log message is rendered in the per-row expansion. Workflows+ * pass `renderWorkflowLogMessage` so event/person/action tokens become links,+ * matching the standalone Logs tab. Defaults to the hog-function renderer.+ */+ renderLogMessage?: (message: string) => JSX.Element | string+}++/**+ * Rerun is async — posting to `/rerun` enqueues a cyclotron wrapper job; new+ * lifecycle rows show up here once the worker drains it.+ */+export function HogInvocations({ id, functionKind, renderLogMessage }: HogInvocationsProps): JSX.Element | null {+ const logic = hogInvocationsLogic({ id, functionKind })+ const {+ runs,+ runsLoading,+ filters,+ selectedIds,+ selectedCount,+ expandedIds,+ rerunableSelectedIds,+ hasMore,+ hasLoadedOnce,+ selectableIds,+ selectAllState,+ personPropertiesById,+ sparkline,+ sparklineLoading,+ } = useValues(logic)+ const {+ loadMore,+ refresh,+ setFilters,+ toggleSelected,+ clearSelected,+ setSelectedIds,+ setExpanded,+ rerunInvocations,+ bulkRerun,+ } = useActions(logic)+ const [rerunModalOpen, setRerunModalOpen] = useState(false)++ useEffect(() => {+ refresh()+ }, [refresh])++ if (!id) {+ return null+ }++ const columns: LemonTableColumns<HogInvocationRow> = [+ {+ title: (+ <LemonCheckbox+ checked={selectAllState === 'all' ? true : selectAllState === 'some' ? 'indeterminate' : false}+ disabledReason={selectableIds.length === 0 ? 'Nothing selectable in this view' : undefined}+ onChange={() => {+ if (selectAllState === 'all' || selectAllState === 'some') {+ clearSelected()+ } else {+ setSelectedIds(selectableIds)+ }+ }}+ />+ ),+ key: 'select',+ width: 0,+ render: (_, row) => (+ <LemonCheckbox+ checked={Boolean(selectedIds[row.invocation_id])}+ onChange={() => toggleSelected(row.invocation_id)}+ disabledReason={+ isRerunWrapperKind(row.function_kind)+ ? "Can't re-run a re-run"+ : row.status === 'running'+ ? "Can't rerun a run that's still in flight"+ : undefined+ }+ />+ ),+ },+ {+ title: 'Status',+ key: 'status',+ dataIndex: 'status',+ width: 0,+ render: (_, row) => (+ <div className="flex items-center gap-1">+ <LemonTag type={tagTypeForStatus(row.status)}>{row.status.toUpperCase()}</LemonTag>+ {row.problem_log_level && row.status === 'succeeded' ? (+ <Tooltip+ title={+ row.problem_log_level === 'error'+ ? 'This run finished but logged an error. Expand the row to view it.'+ : 'This run finished but logged a warning. Expand the row to view it.'+ }+ >+ <IconWarning+ className={+ row.problem_log_level === 'error'+ ? 'text-danger text-base'+ : 'text-warning text-base'+ }+ />+ </Tooltip>+ ) : null}+ </div>+ ),+ },+ {+ title: 'Attempts',+ key: 'attempts',+ dataIndex: 'attempts',+ width: 0,+ render: (_, row) => <span className="font-mono">{row.attempts}</span>,+ },+ {+ title: 'First scheduled',+ key: 'first_scheduled_at',+ dataIndex: 'first_scheduled_at',+ sorter: true,+ render: (_, row) => <TZLabel time={row.first_scheduled_at} />,+ },+ {+ title: 'Latest scheduled',+ key: 'scheduled_at',+ dataIndex: 'scheduled_at',+ sorter: true,+ render: (_, row) => <TZLabel time={row.scheduled_at} />,+ },+ {+ title: 'Duration',+ key: 'duration_ms',+ dataIndex: 'duration_ms',+ render: (_, row) => <span className="font-mono">{formatDurationMs(row.duration_ms)}</span>,+ },+ {+ title: 'Event',+ key: 'event_uuid',+ dataIndex: 'event_uuid',+ render: (_, row) => {+ if (isRerunWrapperKind(row.function_kind)) {+ return <LemonTag type="primary">RERUN</LemonTag>+ }+ return row.event_uuid ? (+ <Link+ to={urls.event(row.event_uuid, row.first_scheduled_at)}+ className="font-mono text-xs"+ title={row.event_uuid}+ >+ {shortId(row.event_uuid)}+ </Link>+ ) : (+ <span className="text-muted-alt">—</span>+ )+ },+ },+ {+ title: 'Person',+ key: 'person',+ render: (_, row) => {+ if (!row.person_id && !row.distinct_id) {+ return <span className="text-muted-alt">—</span>+ }+ // Force `/persons/<uuid>` via `href` — default `asLink` prefers+ // distinct_id, which 404s when it's been merged/anonymized.+ const hydrated = row.person_id ? personPropertiesById[row.person_id] : undefined+ return (+ <PersonDisplay+ person={{+ id: row.person_id,+ distinct_ids: row.distinct_id ? [row.distinct_id] : [],+ properties: hydrated?.properties,+ }}+ href={row.person_id ? urls.personByUUID(row.person_id) : undefined}+ displayName={hydrated ? undefined : shortPersonDisplay(row)}+ withIcon="sm"+ noPopover+ />+ )+ },+ },+ {+ title: 'Error',+ key: 'error_kind',+ dataIndex: 'error_kind',+ render: (_, row) =>+ row.status === 'failed' ? (+ <span className="text-xs" title={row.error_message}>+ <code className="text-danger">{row.error_kind || 'error'}</code>+ {row.error_message ? (+ <div className="text-muted-alt truncate max-w-100">+ {row.error_message.slice(0, 80)}+ {row.error_message.length > 80 ? '…' : ''}+ </div>+ ) : null}+ </span>+ ) : (+ <span className="text-muted-alt">—</span>+ ),+ },+ {+ title: 'Invocation',+ key: 'invocation_id',+ dataIndex: 'invocation_id',+ width: 0,+ render: (_, row) => (+ <code className="text-xs">+ <CopyToClipboardInline explicitValue={row.invocation_id} selectable>+ {shortId(row.invocation_id)}+ </CopyToClipboardInline>+ </code>+ ),+ },+ {+ title: '',+ key: 'actions',+ width: 0,+ render: (_, row) => {+ if (isRerunWrapperKind(row.function_kind)) {+ return null+ }+ return (+ <LemonButton+ size="xsmall"+ type="secondary"+ disabledReason={+ row.status === 'running' ? "Can't rerun a run that's still in flight" : undefined+ }+ onClick={() => {+ LemonDialog.open({+ title: 'Rerun this invocation?',+ content:+ "We'll queue a rerun job for this run from its stored payload. " ++ 'Inputs are re-resolved from the current function config, so any secret ' ++ 'rotations will be picked up.',+ primaryButton: {+ children: 'Rerun',+ onClick: () => rerunInvocations([row.invocation_id]),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }}+ >+ Rerun+ </LemonButton>+ )+ },+ },+ ]++ return (+ <div className="flex-1 deprecated-space-y-2 flex flex-col min-w-0">+ <InvocationsBetaBanner />+ <InvocationsSparkline+ data={sparkline}+ loading={sparklineLoading}+ onDateRangeChange={(date_from, date_to) => setFilters({ date_from, date_to })}+ />+ <div className="flex flex-wrap items-center gap-2 justify-between">+ <div className="flex items-center gap-2 flex-1 min-w-100">+ <LemonInput+ type="search"+ size="small"+ placeholder="Search by invocation, event, distinct, or person ID…"+ fullWidth+ value={filters.search ?? ''}+ onChange={(value) => setFilters({ search: value || undefined })}+ prefix={<IconSearch />}+ allowClear+ />+ </div>+ <div className="flex items-center gap-2 flex-wrap">+ <StatusFilterDropdown+ value={filters.status ?? []}+ onChange={(next) =>+ setFilters({+ status: next.length ? next : undefined,+ })+ }+ />+ <LemonSelect<'all' | 'invocations' | 'rerun_jobs'>+ size="small"+ value={filters.kind ?? 'all'}+ onChange={(v) =>+ setFilters({+ kind: v === 'invocations' || v === 'rerun_jobs' ? v : undefined,+ })+ }+ options={[+ { value: 'all', label: 'All rows' },+ { value: 'invocations', label: 'Invocations only' },+ { value: 'rerun_jobs', label: 'Rerun jobs only' },+ ]}+ />+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconWarning />}+ active={!!filters.problem_only}+ onClick={() => setFilters({ problem_only: filters.problem_only ? undefined : true })}+ tooltip="Show only runs that logged an error or warning — e.g. an email bounce or complaint that arrived after the run finished"+ >+ Logged errors+ </LemonButton>+ <DateFilter+ size="small"+ dateTo={filters.date_to ?? undefined}+ dateFrom={filters.date_from}+ onChange={(from, to) =>+ setFilters({+ date_from: from || '-24h',+ date_to: to || undefined,+ })+ }+ dateOptions={INVOCATIONS_DATE_OPTIONS}+ allowTimePrecision+ allowFixedRangeWithTime+ allowedRollingDateOptions={['minutes', 'hours', 'days', 'weeks', 'months']}+ use24HourFormat+ />+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconRefresh />}+ loading={runsLoading || sparklineLoading}+ onClick={() => refresh()}+ >+ Refresh+ </LemonButton>+ <LemonButton+ size="small"+ type="primary"+ icon={<IconRevert />}+ onClick={() => setRerunModalOpen(true)}+ >+ Re-run…+ </LemonButton>+ </div>+ </div>++ <RerunModal+ isOpen={rerunModalOpen}+ onClose={() => setRerunModalOpen(false)}+ initialDateFrom={filters.date_from}+ initialDateTo={filters.date_to}+ countMatches={(params) => countRerunMatches({ id, functionKind }, params)}+ onSubmit={(params) => {+ bulkRerun(params)+ setRerunModalOpen(false)+ }}+ />++ {selectedCount > 0 ? (+ <div className="flex items-center justify-between border rounded p-2 bg-bg-light">+ <div className="text-sm">+ {selectedCount} selected+ {selectedCount > HOG_INVOCATIONS_RERUN_MAX_COUNT ? (+ <span className="text-danger ml-2">+ Maximum is {HOG_INVOCATIONS_RERUN_MAX_COUNT} per request.+ </span>+ ) : null}+ </div>+ <div className="flex items-center gap-2">+ <LemonButton size="small" type="tertiary" onClick={() => clearSelected()}>+ Clear+ </LemonButton>+ <LemonButton+ size="small"+ type="primary"+ disabledReason={+ rerunableSelectedIds.length === 0+ ? 'Selected runs are all still in flight'+ : selectedCount > HOG_INVOCATIONS_RERUN_MAX_COUNT+ ? `Selected ${selectedCount} > limit ${HOG_INVOCATIONS_RERUN_MAX_COUNT}`+ : undefined+ }+ onClick={() => {+ LemonDialog.open({+ title: `Rerun ${rerunableSelectedIds.length} invocations?`,+ content:+ "We'll queue a single rerun job that drains these in the background. " ++ 'Inputs (secrets, integration tokens) are re-resolved per run at execution ' ++ 'time using the current function config.',+ primaryButton: {+ children: `Rerun ${rerunableSelectedIds.length}`,+ onClick: () => rerunInvocations(rerunableSelectedIds),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }}+ >+ Rerun selected+ </LemonButton>+ </div>+ </div>+ ) : null}++ <LemonTable+ dataSource={runs}+ columns={columns}+ loading={runsLoading && !hasLoadedOnce}+ rowKey={(row) => row.invocation_id}+ // `min-w-0` lets the table shrink to its flex parent so its own+ // ScrollableShadows handles horizontal overflow — without it the+ // wide column set pushes the whole page into a horizontal scroll.+ className="ph-no-capture overflow-y-auto min-w-0"+ // `hover:!` modifiers beat LemonTable's default+ // `hover:bg-accent-highlight-secondary` once `onClick` is set.+ rowRibbonColor={(row) => rowRibbonColorFor(row)}+ sorting={{+ columnKey: filters.order_by === 'first_scheduled' ? 'first_scheduled_at' : 'scheduled_at',+ order: -1,+ }}+ onSort={(next) =>+ setFilters({+ order_by: next?.columnKey === 'first_scheduled_at' ? 'first_scheduled' : 'latest_scheduled',+ })+ }+ noSortingCancellation+ onRow={(record) => ({+ onClick: (e) => {+ const target = e.target as HTMLElement | null+ if (+ target &&+ target.closest(+ 'a, button, input, label, .LemonCheckbox, [role="button"], [data-attr="expand-row"]'+ )+ ) {+ return+ }+ setExpanded(record.invocation_id, !expandedIds[record.invocation_id])+ },+ })}+ expandable={{+ noIndent: true,+ isRowExpanded: (record) => expandedIds[record.invocation_id] ?? false,+ onRowExpand: (record) => setExpanded(record.invocation_id, true),+ onRowCollapse: (record) => setExpanded(record.invocation_id, false),+ expandedRowRender: (record) => (+ <RunDetail+ record={record}+ functionKind={functionKind}+ hogFunctionId={id}+ renderLogMessage={renderLogMessage}+ />+ ),+ }}+ emptyState={+ <div className="py-8 text-center text-muted-alt">+ {runsLoading ? 'Loading invocations…' : 'No invocations match these filters.'}+ </div>+ }+ />++ {runs.length > 0 && hasMore ? (+ <div className="flex justify-center py-2">+ <LemonButton size="small" type="secondary" loading={runsLoading} onClick={() => loadMore(null)}>+ Load more+ </LemonButton>+ </div>+ ) : null}+ </div>+ )+}++function RunDetail({+ record,+ functionKind,+ hogFunctionId,+ renderLogMessage,+}: {+ record: HogInvocationRow+ functionKind: HogInvocationsLogicProps['functionKind']+ hogFunctionId: string+ renderLogMessage?: (message: string) => JSX.Element | string+}): JSX.Element {+ const isRerunWrapper = isRerunWrapperKind(record.function_kind)+ const logsLogicProps: LogsViewerLogicProps = {+ sourceType: functionKind,+ sourceId: hogFunctionId,+ logicKey: `invocations-${record.invocation_id}`,+ defaultFilters: { instanceId: record.invocation_id },+ groupByInstanceId: false,+ }++ return (+ <div className="p-3 deprecated-space-y-3 bg-surface-secondary min-w-0">+ <div className="border rounded bg-surface-primary p-3">+ <dl className="grid grid-cols-[minmax(7rem,max-content)_1fr] items-baseline gap-x-4 gap-y-2 text-xs m-0">+ <DetailField label={isRerunWrapper ? 'Re-run job ID' : 'Invocation ID'} mono>+ <CopyToClipboardInline explicitValue={record.invocation_id} selectable>+ {record.invocation_id}+ </CopyToClipboardInline>+ </DetailField>+ {record.started_at ? (+ <DetailField label="Started">+ <TZLabel time={record.started_at} />+ </DetailField>+ ) : null}+ {record.finished_at ? (+ <DetailField label="Finished">+ <TZLabel time={record.finished_at} />+ </DetailField>+ ) : null}+ {record.parent_run_id ? (+ <DetailField label="Parent run" mono>+ <CopyToClipboardInline explicitValue={record.parent_run_id} selectable>+ {record.parent_run_id}+ </CopyToClipboardInline>+ </DetailField>+ ) : null}+ {isRerunWrapper ? null : record.distinct_id ? (+ <DetailField label="Distinct ID" mono>+ <CopyToClipboardInline explicitValue={record.distinct_id} selectable>+ {record.distinct_id}+ </CopyToClipboardInline>+ </DetailField>+ ) : null}+ {isRerunWrapper ? null : record.person_id ? (+ <DetailField label="Person ID" mono>+ <CopyToClipboardInline explicitValue={record.person_id} selectable>+ {record.person_id}+ </CopyToClipboardInline>+ </DetailField>+ ) : null}+ </dl>+ </div>++ {record.status === 'failed' && record.error_message ? (+ <div className="border border-danger rounded p-2 bg-danger-highlight">+ <div className="text-xs text-danger font-semibold mb-1">+ {record.error_kind ? record.error_kind : 'error'}+ </div>+ <pre className="text-xs text-danger whitespace-pre-wrap break-all m-0">{record.error_message}</pre>+ </div>+ ) : null}++ <div className="border rounded bg-surface-primary p-3">+ <LogsViewer+ {...logsLogicProps}+ hideDateFilter+ hideInstanceIdColumn+ defaultAscending+ renderMessage={renderLogMessage ?? ((message) => renderHogFunctionMessage(message))}+ />+ </div>+ </div>+ )+}++function DetailField({+ label,+ value,+ mono,+ children,+}: {+ label: string+ value?: string+ mono?: boolean+ children?: ReactNode+}): JSX.Element {+ return (+ <>+ <dt className="text-muted-alt font-medium">{label}</dt>+ <dd className={`m-0 min-w-0 ${mono ? 'font-mono break-all' : ''}`}>{children ?? value}</dd>+ </>+ )+}++function RerunModal({+ isOpen,+ onClose,+ initialDateFrom,+ initialDateTo,+ countMatches,+ onSubmit,+}: {+ isOpen: boolean+ onClose: () => void+ initialDateFrom: string+ initialDateTo: string | undefined+ countMatches: (params: BulkRerunParams) => Promise<number>+ onSubmit: (params: BulkRerunParams) => void+}): JSX.Element {+ const [status, setStatus] = useState<RunStatus[]>(['failed'])+ const [errorKinds, setErrorKinds] = useState<string[]>([])+ const [maxCount, setMaxCount] = useState<number | undefined>(undefined)+ const [maxAttempts, setMaxAttempts] = useState<number | undefined>(undefined)+ const [dateFrom, setDateFrom] = useState<string>(initialDateFrom)+ const [dateTo, setDateTo] = useState<string | undefined>(initialDateTo)+ const [previewCount, setPreviewCount] = useState<number | null>(null)+ const [previewLoading, setPreviewLoading] = useState(false)++ // Debounced live count of invocations matching the current filter so the+ // user knows how many runs they're about to re-queue before they click.+ // Skip the explicit max_count cap in the preview — that's a client-side+ // ceiling applied at the server, not a filter on matching rows.+ useEffect(() => {+ if (!isOpen || status.length === 0) {+ setPreviewCount(null)+ return+ }+ const params: BulkRerunParams = {+ date_from: dateFrom,+ date_to: dateTo,+ status,+ error_kind: errorKinds.length ? errorKinds : undefined,+ max_attempts: maxAttempts,+ }+ setPreviewLoading(true)+ const handle = setTimeout(() => {+ countMatches(params)+ .then((n) => setPreviewCount(n))+ .catch(() => setPreviewCount(null))+ .finally(() => setPreviewLoading(false))+ }, 400)+ return () => clearTimeout(handle)+ }, [isOpen, dateFrom, dateTo, status, errorKinds, maxAttempts, countMatches])++ return (+ <LemonModal+ isOpen={isOpen}+ onClose={onClose}+ title="Re-run invocations"+ description="Queue a re-run for every invocation that matches this filter within the window. Inputs (secrets, integration tokens) are re-resolved per row at execution time."+ width={520}+ footer={+ <div className="flex items-center justify-between w-full gap-2">+ <div className="text-xs text-muted-alt">+ {status.length === 0+ ? 'Pick at least one status to preview matches'+ : previewLoading && previewCount === null+ ? 'Counting matching invocations…'+ : previewCount !== null+ ? typeof maxCount === 'number' && previewCount > maxCount+ ? `${previewCount.toLocaleString()} match — will re-run the first ${maxCount.toLocaleString()}`+ : `${previewCount.toLocaleString()} invocation${previewCount === 1 ? '' : 's'} match`+ : ''}+ </div>+ <div className="flex items-center gap-2">+ <LemonButton type="secondary" onClick={onClose}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ disabledReason={+ status.length === 0+ ? 'Pick at least one status'+ : previewCount === 0+ ? 'Nothing matches this filter'+ : undefined+ }+ onClick={() =>+ onSubmit({+ date_from: dateFrom,+ date_to: dateTo,+ status,+ error_kind: errorKinds.length ? errorKinds : undefined,+ max_count: maxCount,+ max_attempts: maxAttempts,+ })+ }+ >+ Queue re-run+ </LemonButton>+ </div>+ </div>+ }+ >+ <div className="deprecated-space-y-3">+ <Row label="Window">+ <DateFilter+ size="small"+ dateFrom={dateFrom}+ dateTo={dateTo ?? undefined}+ onChange={(from, to) => {+ setDateFrom(from || '-24h')+ setDateTo(to || undefined)+ }}+ dateOptions={INVOCATIONS_DATE_OPTIONS}+ allowTimePrecision+ allowFixedRangeWithTime+ allowedRollingDateOptions={['minutes', 'hours', 'days', 'weeks', 'months']}+ use24HourFormat+ />+ </Row>+ <Row label="Status">+ <LemonInputSelect+ mode="multiple"+ value={status}+ // 'running' is omitted: in-flight invocations are skipped by the rerun worker's+ // exactly-once guard, so offering it here would queue a rerun that re-fires nothing.+ options={STATUS_OPTIONS.filter((o) => o.value !== 'running').map((o) => ({+ key: o.value,+ label: o.label,+ }))}+ onChange={(values) => setStatus(values as RunStatus[])}+ placeholder="Pick statuses to re-run"+ />+ </Row>+ <Row+ label="Error kinds"+ help="Free-text — only matters when filtering by failed. Match values from the Error column (e.g. http_5xx)."+ >+ <LemonInputSelect+ mode="multiple"+ value={errorKinds}+ options={[]}+ allowCustomValues+ onChange={(values) => setErrorKinds(values)}+ placeholder="Leave empty for all"+ />+ </Row>+ <Row label="Max invocations to re-run" help={`Server caps at ${HOG_INVOCATIONS_RERUN_MAX_COUNT}.`}>+ <LemonInput+ type="number"+ min={1}+ max={HOG_INVOCATIONS_RERUN_MAX_COUNT}+ value={maxCount}+ onChange={(v) => setMaxCount(typeof v === 'number' ? v : undefined)}+ placeholder="Unlimited (up to server cap)"+ />+ </Row>+ <Row+ label="Skip rows with attempts ≥"+ help="Useful to avoid re-running rows that have already retried a lot."+ >+ <LemonInput+ type="number"+ min={1}+ max={255}+ value={maxAttempts}+ onChange={(v) => setMaxAttempts(typeof v === 'number' ? v : undefined)}+ placeholder="No cap"+ />+ </Row>+ </div>+ </LemonModal>+ )+}++function StatusFilterDropdown({+ value,+ onChange,+}: {+ value: RunStatus[]+ onChange: (next: RunStatus[]) => void+}): JSX.Element {+ const label =+ value.length === 0 || value.length === STATUS_OPTIONS.length+ ? 'All statuses'+ : value.length === 1+ ? (STATUS_OPTIONS.find((o) => o.value === value[0])?.label ?? value[0])+ : `${value.length} statuses`+ return (+ <LemonDropdown+ closeOnClickInside={false}+ overlay={+ <div className="deprecated-space-y-px p-1">+ {STATUS_OPTIONS.map((option) => (+ <LemonButton+ key={option.value}+ type="tertiary"+ size="small"+ fullWidth+ icon={+ <LemonCheckbox checked={value.includes(option.value)} className="pointer-events-none" />+ }+ onClick={() =>+ onChange(+ value.includes(option.value)+ ? value.filter((v) => v !== option.value)+ : [...value, option.value]+ )+ }+ >+ {option.label}+ </LemonButton>+ ))}+ </div>+ }+ >+ <LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>+ {label}+ </LemonButton>+ </LemonDropdown>+ )+}++function Row({ label, help, children }: { label: string; help?: string; children: ReactNode }): JSX.Element {+ return (+ <div>+ <div className="text-xs text-muted-alt mb-1">{label}</div>+ {children}+ {help ? <div className="text-xs text-muted-alt mt-1">{help}</div> : null}+ </div>+ )+}diff --git a/frontend/src/scenes/hog-functions/invocations/InvocationsSparkline.tsx b/frontend/src/scenes/hog-functions/invocations/InvocationsSparkline.tsxnew file mode 100644index 000000000000..8b4e4da6523c--- /dev/null+++ b/frontend/src/scenes/hog-functions/invocations/InvocationsSparkline.tsx@@ -0,0 +1,111 @@+import { useCallback, useMemo, useState } from 'react'++import { IconChevronDown } from '@posthog/icons'+import { LemonButton, SpinnerOverlay } from '@posthog/lemon-ui'++import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'+import { dayjs } from 'lib/dayjs'+import { cn } from 'lib/utils/css-classes'++import { SparklineData } from './hogInvocationsLogic'++interface InvocationsSparklineProps {+ data: SparklineData | null+ loading: boolean+ onDateRangeChange: (dateFrom: string, dateTo: string | undefined) => void+}++export function InvocationsSparkline({+ data,+ loading,+ onDateRangeChange,+}: InvocationsSparklineProps): JSX.Element | null {+ const [collapsed, setCollapsed] = useState(false)++ const { timeUnit, tickFormat } = useMemo(() => {+ const dates = data?.dates ?? []+ if (dates.length < 2) {+ return { timeUnit: 'hour' as const, tickFormat: 'HH:mm' }+ }+ const hoursDiff = dayjs(dates[dates.length - 1]).diff(dayjs(dates[0]), 'hour')+ if (hoursDiff <= 6) {+ return { timeUnit: 'minute' as const, tickFormat: 'HH:mm' }+ }+ if (hoursDiff <= 48) {+ return { timeUnit: 'hour' as const, tickFormat: 'HH:mm' }+ }+ return { timeUnit: 'day' as const, tickFormat: 'D MMM' }+ }, [data?.dates])++ const withXScale = useCallback(+ (scale: AnyScaleOptions): AnyScaleOptions =>+ ({+ ...scale,+ type: 'timeseries',+ ticks: {+ display: true,+ maxRotation: 0,+ maxTicksLimit: 6,+ font: { size: 10, lineHeight: 1 },+ callback: (value: string | number) => dayjs(value).format(tickFormat),+ },+ time: { unit: timeUnit },+ }) as AnyScaleOptions,+ [timeUnit, tickFormat]+ )++ const onSelectionChange = useCallback(+ (sel: { startIndex: number; endIndex: number }): void => {+ const dates = data?.dates ?? []+ const from = dates[sel.startIndex]+ // `+1` so the selection end aligns with the *next* bucket boundary,+ // mirroring how the logs sparkline emits ranges. If we hit past+ // the end of the buckets, leave dateTo undefined (= "up to now").+ const to = dates[sel.endIndex + 1]+ if (from) {+ onDateRangeChange(from, to)+ }+ },+ [data?.dates, onDateRangeChange]+ )++ const labels = useMemo(() => (data?.dates ?? []).map((d) => dayjs(d).toISOString()), [data?.dates])+ const hasAnyData = (data?.series ?? []).some((s) => s.values.some((v) => v > 0))++ return (+ <div className="flex flex-col gap-1">+ <div className="flex items-center">+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconChevronDown className={cn('transition-transform', collapsed && '-rotate-90')} />}+ onClick={() => setCollapsed(!collapsed)}+ aria-expanded={!collapsed}+ >+ <span className="text-xs text-muted">Volume over time</span>+ </LemonButton>+ </div>+ {!collapsed && (+ <div className="relative h-24">+ {hasAnyData ? (+ <Sparkline+ labels={labels}+ data={data!.series}+ className="w-full h-full"+ onSelectionChange={onSelectionChange}+ withXScale={withXScale}+ renderLabel={(label) => dayjs(label).format('D MMM YYYY HH:mm')}+ hideZerosInTooltip+ sortTooltipByCount+ />+ ) : !loading ? (+ <div className="h-full text-muted text-xs flex items-center justify-center">+ No invocations in this window+ </div>+ ) : null}+ {loading && <SpinnerOverlay />}+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/hog-functions/invocations/InvocationsTabBanners.tsx b/frontend/src/scenes/hog-functions/invocations/InvocationsTabBanners.tsxnew file mode 100644index 000000000000..89a06348f482--- /dev/null+++ b/frontend/src/scenes/hog-functions/invocations/InvocationsTabBanners.tsx@@ -0,0 +1,33 @@+import { useValues } from 'kea'++import { FEATURE_FLAGS } from 'lib/constants'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++export function InvocationsLegacyTabBanner({+ legacyTab,+}: {+ legacyTab: 'Logs' | 'Testing' | 'Invocations (legacy)'+}): JSX.Element | null {+ const { featureFlags } = useValues(featureFlagLogic)+ if (!featureFlags[FEATURE_FLAGS.HOG_INVOCATION_RESULTS_RUNS_TAB]) {+ return null+ }+ return (+ <LemonBanner+ type="warning"+ dismissKey={`invocations-legacy-${legacyTab.toLowerCase().replace(/\s+/g, '-')}-banner`}+ className="mb-2"+ >+ This {legacyTab} view will be replaced by the new <strong>Invocations</strong> tab soon.+ </LemonBanner>+ )+}++export function InvocationsBetaBanner(): JSX.Element {+ return (+ <LemonBanner type="warning" dismissKey="invocations-beta-banner" className="mb-2">+ Invocations is in beta — it will replace the Logs and Testing tabs.+ </LemonBanner>+ )+}diff --git a/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsxnew file mode 100644index 000000000000..6eb0ec9062f5--- /dev/null+++ b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx@@ -0,0 +1,985 @@+import { actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { actionToUrl, router, urlToAction } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import api, { ApiConfig } from 'lib/api'+import { dayjs } from 'lib/dayjs'+import { dateStringToDayJs } from 'lib/utils/dateFilters'+import { teamLogic } from 'scenes/teamLogic'++import { escapeHogQLString, hogql } from '~/queries/utils'++import { hogFunctionsRerunCreate } from 'products/cdp/frontend/generated/api'+import type { HogInvocationRerunFilterStatusEnumApi } from 'products/cdp/frontend/generated/api.schemas'+import { hogFlowsRerunCreate } from 'products/workflows/frontend/generated/api'++import type { hogInvocationsLogicType } from './hogInvocationsLogicType'++export const HOG_INVOCATIONS_PAGE_SIZE = 200++/** Display-side mirror of the backend cap. Backend enforces the actual limit via the+ * `HOG_INVOCATION_RERUN_MAX_COUNT` env var (Django serializer + Node CDP config). */+export const HOG_INVOCATIONS_RERUN_MAX_COUNT = 10000++export type RunStatus = 'running' | 'succeeded' | 'failed'++export type HogInvocationsFunctionKind = 'hog_function' | 'hog_flow'++export type RunRowKind = 'hog_function' | 'hog_flow' | 'hog_function_rerun' | 'hog_flow_rerun'++export const isRerunWrapperKind = (kind: RunRowKind): boolean =>+ kind === 'hog_function_rerun' || kind === 'hog_flow_rerun'++const rerunWrapperKindFor = (kind: HogInvocationsFunctionKind): RunRowKind =>+ kind === 'hog_flow' ? 'hog_flow_rerun' : 'hog_function_rerun'++export interface HogInvocationRow {+ invocation_id: string+ function_kind: RunRowKind+ status: RunStatus+ attempts: number+ is_retry: boolean+ error_kind: string+ error_message: string+ scheduled_at: string+ first_scheduled_at: string+ started_at: string | null+ finished_at: string | null+ duration_ms: number | null+ event_uuid: string+ distinct_id: string+ person_id: string+ parent_run_id: string+ /**+ * Worst log-entry level for this invocation (`error` > `warn`), or null.+ * Surfaces async problems (e.g. an SES bounce/complaint logged after the+ * invocation already finished `succeeded`) so a run that went wrong doesn't+ * read as a clean success at the row level.+ */+ problem_log_level: 'warn' | 'error' | null+}++export type RunsOrderBy = 'latest_scheduled' | 'first_scheduled'++export interface HogInvocationsFilters {+ date_from: string+ date_to?: string+ status?: RunStatus[]+ error_kind?: string[]+ /**+ * Row-kind filter: scope the list to real invocations (`hog_function` /+ * `hog_flow`), to rerun wrapper jobs (`*_rerun`), or show both.+ */+ kind?: 'invocations' | 'rerun_jobs'+ search?: string+ order_by?: RunsOrderBy+ /**+ * Show only invocations that logged an error or warning entry (e.g. an SES bounce/complaint+ * that arrives after the run already finished `succeeded`). Status is execution-based, so these+ * aren't otherwise findable here without scanning the logs tab.+ */+ problem_only?: boolean+}++export interface HogInvocationsLogicProps {+ /** HogFunction.id or HogFlow.id */+ id: string+ functionKind: HogInvocationsFunctionKind+}++export interface SparklineSeries {+ name: RunStatus+ color: string+ values: number[]+}++export interface SparklineData {+ /** ISO timestamps for each bucket. */+ dates: string[]+ series: SparklineSeries[]+}++export interface BulkRerunParams {+ date_from: string+ date_to?: string+ status?: RunStatus[]+ error_kind?: string[]+ max_count?: number+ max_attempts?: number+}++const URL_PARAM_PREFIX = 'inv_'+const URL_PARAMS = {+ date_from: `${URL_PARAM_PREFIX}date_from`,+ date_to: `${URL_PARAM_PREFIX}date_to`,+ status: `${URL_PARAM_PREFIX}status`,+ error_kind: `${URL_PARAM_PREFIX}error_kind`,+ kind: `${URL_PARAM_PREFIX}kind`,+ search: `${URL_PARAM_PREFIX}search`,+ order_by: `${URL_PARAM_PREFIX}order`,+ problem_only: `${URL_PARAM_PREFIX}problems`,+} as const++const filtersToSearchParams = (filters: HogInvocationsFilters): Record<string, string | undefined> => ({+ [URL_PARAMS.date_from]: filters.date_from === '-24h' ? undefined : filters.date_from,+ [URL_PARAMS.date_to]: filters.date_to,+ [URL_PARAMS.status]: filters.status?.length ? filters.status.join(',') : undefined,+ [URL_PARAMS.error_kind]: filters.error_kind?.length ? filters.error_kind.join(',') : undefined,+ [URL_PARAMS.kind]: filters.kind,+ [URL_PARAMS.search]: filters.search,+ [URL_PARAMS.order_by]: filters.order_by === 'first_scheduled' ? undefined : filters.order_by,+ [URL_PARAMS.problem_only]: filters.problem_only ? '1' : undefined,+})++const searchParamsToFilters = (searchParams: Record<string, string | undefined>): Partial<HogInvocationsFilters> => {+ const next: Partial<HogInvocationsFilters> = {}+ const dateFrom = searchParams[URL_PARAMS.date_from]+ if (dateFrom) {+ next.date_from = dateFrom+ }+ if (searchParams[URL_PARAMS.date_to]) {+ next.date_to = searchParams[URL_PARAMS.date_to]+ }+ const status = searchParams[URL_PARAMS.status]+ if (status) {+ next.status = status.split(',').filter((s): s is RunStatus => ['running', 'succeeded', 'failed'].includes(s))+ }+ const errorKind = searchParams[URL_PARAMS.error_kind]+ if (errorKind) {+ next.error_kind = errorKind.split(',').filter(Boolean)+ }+ const kind = searchParams[URL_PARAMS.kind]+ if (kind === 'invocations' || kind === 'rerun_jobs') {+ next.kind = kind+ }+ if (searchParams[URL_PARAMS.search]) {+ next.search = searchParams[URL_PARAMS.search]+ }+ const orderBy = searchParams[URL_PARAMS.order_by]+ if (orderBy === 'first_scheduled' || orderBy === 'latest_scheduled') {+ next.order_by = orderBy+ }+ if (searchParams[URL_PARAMS.problem_only]) {+ next.problem_only = true+ }+ return next+}++const DEFAULT_FILTERS: HogInvocationsFilters = {+ date_from: '-24h',+ date_to: undefined,+ status: undefined,+ error_kind: undefined,+ kind: undefined,+ search: undefined,+ order_by: 'first_scheduled',+}++const AUTO_REFRESH_INTERVAL_MS = 5000+// After a rerun is enqueued the matching rows aren't `running` yet (the worker+// drains asynchronously), so the `hasRunningRows` guard alone wouldn't restart+// polling. Force a short polling window so the re-run rows surface on their own.+const FORCE_REFRESH_WINDOW_MS = 30000++const scheduleAutoRefresh = (+ // Kea types `cache` as `Record<string, any>` upstream — that's where the+ // `disposables` plugin attaches its handle, but the registration is+ // dynamic so the narrow type isn't visible at this call site.+ cache: Record<string, any>,+ actions: { loadRuns: (payload: null) => void },+ values: { hasRunningRows: boolean }+): void => {+ const forcing = typeof cache.forceRefreshUntil === 'number' && Date.now() < cache.forceRefreshUntil+ if (!values.hasRunningRows && !forcing) {+ return+ }+ cache.disposables.add(() => {+ const timeoutId = setTimeout(() => actions.loadRuns(null), AUTO_REFRESH_INTERVAL_MS)+ return () => clearTimeout(timeoutId)+ }, 'autoRefresh')+}++/**+ * Convert a relative date-picker string (`-1h`, `-7d`, `-3w`) to its duration+ * in hours. Can't reuse `dateStringToDayJs` for this — that one anchors+ * relative strings against `startOf('day')`, so `-1h` resolves to "yesterday+ * 23:00", not "1 hour ago". Returns `null` for absolute / unknown shapes.+ */+const RELATIVE_DATE_REGEX = /^-(\d+)([sMhdwmqy])$/+const parseRelativeHours = (value: string | undefined): number | null => {+ if (!value) {+ return null+ }+ const match = RELATIVE_DATE_REGEX.exec(value)+ if (!match) {+ return null+ }+ const n = parseInt(match[1], 10)+ // PostHog convention: uppercase `M` = minutes (lowercase `m` = month). See+ // `frontend/src/lib/utils.tsx` for the master mapping.+ const hoursPerUnit: Record<string, number> = {+ s: 1 / 3600,+ M: 1 / 60,+ h: 1,+ d: 24,+ w: 24 * 7,+ m: 24 * 30,+ q: 24 * 90,+ y: 24 * 365,+ }+ return n * (hoursPerUnit[match[2]] ?? 0)+}++/**+ * Resolve the filter's date range to concrete dayjs endpoints. Centralizing+ * this so the sparkline's bucket sizing AND its boundary generation see the+ * same window (otherwise the chart's x-axis can drift away from the actual+ * filter the table is using).+ */+export const resolveDateRange = (filters: {+ date_from?: string+ date_to?: string+}): { start: dayjs.Dayjs; end: dayjs.Dayjs } => {+ const end = filters.date_to ? (dateStringToDayJs(filters.date_to) ?? dayjs()) : dayjs()+ const relHours = parseRelativeHours(filters.date_from)+ if (relHours !== null) {+ return { start: end.subtract(relHours, 'hour'), end }+ }+ const start = dateStringToDayJs(filters.date_from ?? null) ?? end.subtract(24, 'hour')+ return { start, end }+}++/**+ * Inline date predicate for the inner subquery's WHERE clause. `filtersOverride`+ * doesn't bind to a timestamp field on `hog_invocation_results` (no marker on+ * the schema), so we apply the window directly. UTC + the CH DateTime64 literal+ * format keeps partition pruning working.+ */+export const dateClauseFor = (filters: HogInvocationsFilters): ReturnType<typeof hogql.raw> => {+ const { start, end } = resolveDateRange(filters)+ // HogQL interprets bare datetime literals in the *team* timezone (DateTime+ // fields are compared as toTimeZone(field, team_tz)), so format the window+ // bounds in the team tz — NOT UTC — or the filter is shifted by the team's+ // offset for any non-UTC project. Mirrors `toAbsoluteClickhouseTimestamp`.+ const teamTimezone = teamLogic.findMounted()?.values.currentTeam?.timezone ?? 'UTC'+ const fmt = (d: dayjs.Dayjs): string => d.tz(teamTimezone).format('YYYY-MM-DD HH:mm:ss.SSS')+ return hogql.raw(`AND scheduled_at >= '${fmt(start)}' AND scheduled_at < '${fmt(end)}'`)+}++/**+ * `function_kind` predicate driven by the kind filter — `invocations` returns+ * only real rows, `rerun_jobs` returns only the wrapper rows, and the default+ * (undefined) returns both kinds for this function id.+ */+export const kindClauseFor = (+ props: HogInvocationsLogicProps,+ filters: HogInvocationsFilters+): ReturnType<typeof hogql.raw> => {+ const wrapperKind = rerunWrapperKindFor(props.functionKind)+ if (filters.kind === 'invocations') {+ return hogql.raw(`function_kind = '${props.functionKind}'`)+ }+ if (filters.kind === 'rerun_jobs') {+ return hogql.raw(`function_kind = '${wrapperKind}'`)+ }+ return hogql.raw(`function_kind IN ('${props.functionKind}', '${wrapperKind}')`)+}++/**+ * Optional predicate restricting to invocations that logged an error/warning entry. Uses a+ * `log_entries` subquery (resolved server-side, so no client-side id list) keyed by the same+ * source the per-row logs use. Deliberately not date-scoped: a bounce/complaint can land after+ * the run's scheduled window, and the outer `scheduled_at` filter already constrains which+ * invocations appear. Returns an empty clause when the filter is off.+ */+export const problemClauseFor = (+ props: HogInvocationsLogicProps,+ filters: HogInvocationsFilters+): ReturnType<typeof hogql.raw> => {+ if (!filters.problem_only) {+ return hogql.raw('')+ }+ return hogql.raw(+ `AND invocation_id IN (` ++ `SELECT instance_id FROM log_entries ` ++ `WHERE log_source = ${escapeHogQLString(props.functionKind)} ` ++ `AND log_source_id = ${escapeHogQLString(props.id)} ` ++ `AND lower(level) IN ('error', 'warn'))`+ )+}++/**+ * Tier selection for the sparkline. Each tier carries both the HogQL bucket+ * expression and the equivalent client-side interval (in ms) so we can+ * generate every bucket boundary in the filter range, not just the ones CH+ * returned data for. Tiers (by total range): <24h minutely, ≤4d 15-min,+ * ≤7d hourly, otherwise daily.+ */+interface SparklineTier {+ intervalMs: number+ bucketExpr: string+}+const pickSparklineTier = (filters: HogInvocationsFilters): SparklineTier => {+ const { start, end } = resolveDateRange(filters)+ const hours = end.diff(start, 'hour')+ if (hours < 24) {+ return { intervalMs: 60_000, bucketExpr: 'toStartOfMinute(first_scheduled)' }+ }+ if (hours <= 4 * 24) {+ return {+ intervalMs: 15 * 60_000,+ bucketExpr: 'toStartOfInterval(first_scheduled, INTERVAL 15 MINUTE)',+ }+ }+ if (hours <= 7 * 24) {+ return { intervalMs: 60 * 60_000, bucketExpr: 'toStartOfHour(first_scheduled)' }+ }+ return { intervalMs: 24 * 60 * 60_000, bucketExpr: 'toStartOfDay(first_scheduled)' }+}++/**+ * Walk the filter range and emit every bucket boundary as an ISO string.+ * Snaps to interval-aligned ms (matching CH's epoch-aligned+ * `toStartOfInterval` / `toStartOfMinute` etc.), so the keys we use to look+ * up CH counts line up regardless of timezone formatting.+ */+const generateSparklineBuckets = (filters: HogInvocationsFilters, intervalMs: number): string[] => {+ const { start, end } = resolveDateRange(filters)+ const snap = (t: dayjs.Dayjs): number => Math.floor(t.valueOf() / intervalMs) * intervalMs+ const out: string[] = []+ for (let ms = snap(start); ms < end.valueOf(); ms += intervalMs) {+ out.push(dayjs(ms).toISOString())+ }+ return out+}++const SPARKLINE_STATUS_COLORS: Record<RunStatus, string> = {+ running: 'warning',+ succeeded: 'success',+ failed: 'danger',+}++async function fetchSparkline(props: HogInvocationsLogicProps, filters: HogInvocationsFilters): Promise<SparklineData> {+ const { intervalMs, bucketExpr } = pickSparklineTier(filters)++ // Filters reference the SELECT aliases (status / error_kind) so we don't+ // re-wrap in argMax inline — that would collide with the alias and+ // produce a nested aggregate error.+ // `escapeHogQLString` handles all special chars (quotes, backslashes, null+ // bytes) using the same path as the `hogql` template tag — a `.replace(/'/g, …)`+ // pass on its own is bypassable (e.g. `\' OR 1=1 --`).+ const optionalStatusClause = filters.status?.length+ ? hogql.raw(`AND status IN (${filters.status.map(escapeHogQLString).join(',')})`)+ : hogql.raw('')+ 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('')++ const kindClause = kindClauseFor(props, filters)+ const dateClause = dateClauseFor(filters)+ const query = hogql`+ SELECT+ ${hogql.raw(bucketExpr)} AS bucket,+ status,+ count() AS n+ FROM (+ SELECT+ invocation_id,+ argMax(status, version) AS status,+ argMax(error_kind, version) AS error_kind,+ argMax(event_uuid, version) AS event_uuid,+ argMax(distinct_id, version) AS distinct_id,+ argMax(person_id, version) AS person_id,+ argMax(first_scheduled_at, version) AS first_scheduled+ FROM posthog.hog_invocation_results+ WHERE ${kindClause}+ AND function_id = ${props.id}+ ${dateClause}+ GROUP BY invocation_id, function_kind+ HAVING argMax(is_deleted, version) = 0+ ${optionalStatusClause}+ ${optionalErrorKindClause}+ ${optionalSearchClause}+ ${problemClauseFor(props, filters)}+ )+ GROUP BY bucket, status+ ORDER BY bucket+ `+ const response = await api.queryHogQL(+ query,+ { scene: 'HogInvocations', productKey: 'pipeline_destinations' },+ {+ refresh: 'force_blocking',+ filtersOverride: { date_from: filters.date_from, date_to: filters.date_to },+ }+ )++ // Pivot CH results keyed on bucket-as-ms so the lookup is tolerant of+ // string-format differences between CH's serialization and dayjs's+ // ISO output.+ const cellsByMs: Record<number, Record<RunStatus, number>> = {}+ for (const row of response.results ?? []) {+ const [bucket, status, n] = row as unknown as [string, RunStatus, number]+ if (!bucket) {+ continue+ }+ const ms = dayjs(bucket).valueOf()+ cellsByMs[ms] = cellsByMs[ms] ?? { running: 0, succeeded: 0, failed: 0 }+ cellsByMs[ms][status] = Number(n ?? 0)+ }+ // Walk every bucket in the filter range — not just the ones CH returned+ // data for — so the chart's x-axis spans the user's selected window even+ // when activity is concentrated in a tiny slice of it.+ const dates = generateSparklineBuckets(filters, intervalMs)+ const buildValues = (status: RunStatus): number[] => dates.map((d) => cellsByMs[dayjs(d).valueOf()]?.[status] ?? 0)+ const series: SparklineSeries[] = (['failed', 'running', 'succeeded'] as RunStatus[]).map((status) => ({+ name: status,+ color: SPARKLINE_STATUS_COLORS[status],+ values: buildValues(status),+ }))+ return { dates, series }+}++async function fetchRunsPage(+ props: HogInvocationsLogicProps,+ filters: HogInvocationsFilters,+ offset: number+): Promise<HogInvocationRow[]> {+ // HAVING clauses reference the SELECT aliases below — wrapping the column+ // again as `argMax(status, version)` makes HogQL substitute `status` for+ // its alias and produce a nested aggregate.+ const optionalStatusClause = filters.status?.length+ ? hogql.raw(`AND status IN (${filters.status.map(escapeHogQLString).join(', ')})`)+ : hogql.raw('')+ 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('')++ // `ORDER BY max(scheduled_at)` is safe only because the SELECT alias isn't+ // named `scheduled_at` — otherwise HogQL substitutes the alias and produces+ // `max(max(scheduled_at))`.+ const orderClause =+ filters.order_by === 'first_scheduled'+ ? hogql.raw('ORDER BY argMax(first_scheduled_at, version) DESC, invocation_id DESC')+ : hogql.raw('ORDER BY max(scheduled_at) DESC, invocation_id DESC')+ const kindClause = kindClauseFor(props, filters)+ const dateClause = dateClauseFor(filters)+ const query = hogql`+ SELECT+ invocation_id,+ function_kind AS function_kind,+ argMax(status, version) AS status,+ argMax(attempts, version) AS attempts,+ argMax(is_retry, version) AS is_retry,+ argMax(error_kind, version) AS error_kind,+ argMax(error_message, version) AS error_message,+ max(scheduled_at) AS latest_scheduled_at,+ argMax(first_scheduled_at, version) AS first_scheduled,+ argMax(started_at, version) AS started_at,+ argMax(finished_at, version) AS finished_at,+ argMax(duration_ms, version) AS duration_ms,+ argMax(event_uuid, version) AS event_uuid,+ argMax(distinct_id, version) AS distinct_id,+ argMax(person_id, version) AS person_id,+ argMax(parent_run_id, version) AS parent_run_id+ FROM posthog.hog_invocation_results+ WHERE ${kindClause}+ AND function_id = ${props.id}+ ${dateClause}+ GROUP BY invocation_id, function_kind+ HAVING argMax(is_deleted, version) = 0+ ${optionalStatusClause}+ ${optionalErrorKindClause}+ ${optionalSearchClause}+ ${problemClauseFor(props, filters)}+ ${orderClause}+ LIMIT ${HOG_INVOCATIONS_PAGE_SIZE}+ OFFSET ${offset}+ `++ const response = await api.queryHogQL(+ query,+ { scene: 'HogInvocations', productKey: 'pipeline_destinations' },+ {+ refresh: 'force_blocking',+ filtersOverride: {+ date_from: filters.date_from,+ date_to: filters.date_to,+ },+ }+ )++ const rows = (response.results ?? []).map((row): HogInvocationRow => {+ const [+ invocation_id,+ function_kind,+ status,+ attempts,+ is_retry,+ error_kind,+ error_message,+ scheduled_at,+ first_scheduled_at,+ started_at,+ finished_at,+ duration_ms,+ event_uuid,+ distinct_id,+ person_id,+ parent_run_id,+ ] = row as unknown as [+ string,+ RunRowKind,+ RunStatus,+ number,+ number,+ string,+ string,+ string,+ string,+ string | null,+ string | null,+ number | null,+ string,+ string,+ string,+ string,+ ]+ return {+ invocation_id,+ function_kind,+ status,+ attempts,+ is_retry: Boolean(is_retry),+ error_kind,+ error_message,+ scheduled_at,+ first_scheduled_at,+ started_at,+ finished_at,+ duration_ms,+ event_uuid,+ distinct_id,+ person_id,+ parent_run_id,+ problem_log_level: null,+ }+ })++ // Enrich the page with the worst log-entry level per invocation. An SES bounce/complaint+ // (and similar async failures) writes an error/warn log entry after the invocation already+ // finished `succeeded`, so without this a delivery failure reads as a clean success here.+ // Best-effort: a failed lookup just leaves the rows without the indicator.+ const ids = rows.map((r) => r.invocation_id)+ if (ids.length > 0) {+ const idClause = hogql.raw(`instance_id IN (${ids.map(escapeHogQLString).join(',')})`)+ const severityQuery = hogql`+ SELECT instance_id, max(multiIf(lower(level) = 'error', 2, lower(level) = 'warn', 1, 0)) AS sev+ FROM log_entries+ WHERE log_source = ${props.functionKind}+ AND log_source_id = ${props.id}+ AND ${idClause}+ GROUP BY instance_id+ HAVING sev > 0+ `+ try {+ const severityResponse = await api.queryHogQL(severityQuery, {+ scene: 'HogInvocations',+ productKey: 'pipeline_destinations',+ })+ const levelByInvocationId: Record<string, 'warn' | 'error'> = {}+ for (const severityRow of severityResponse.results ?? []) {+ const [instanceId, sev] = severityRow as unknown as [string, number]+ levelByInvocationId[instanceId] = Number(sev) >= 2 ? 'error' : 'warn'+ }+ for (const row of rows) {+ row.problem_log_level = levelByInvocationId[row.invocation_id] ?? null+ }+ } catch {+ // Leave problem_log_level as null — the run statuses are still accurate.+ }+ }+ return rows+}++/**+ * Rerun is async — the `/rerun` endpoint enqueues a cyclotron wrapper job;+ * new lifecycle rows show up here once the worker drains it.+ */+export const hogInvocationsLogic = kea<hogInvocationsLogicType>([+ path((id) => ['scenes', 'hog-functions', 'invocations', 'hogInvocationsLogic', id]),+ props({} as HogInvocationsLogicProps),+ key((props) => `${props.functionKind}:${props.id}`),++ actions({+ setFilters: (filters: Partial<HogInvocationsFilters>) => ({ filters }),+ resetFilters: true,+ refresh: true,+ toggleSelected: (invocationId: string) => ({ invocationId }),+ clearSelected: true,+ setSelectedIds: (ids: string[]) => ({ ids }),+ hydratePeople: (personIds: string[]) => ({ personIds }),+ setExpanded: (invocationId: string, expanded: boolean) => ({ invocationId, expanded }),+ rerunInvocations: (invocationIds: string[]) => ({ invocationIds }),+ bulkRerun: (params: BulkRerunParams) => ({ params }),+ setHasMore: (hasMore: boolean) => ({ hasMore }),+ }),++ reducers({+ filters: [+ DEFAULT_FILTERS,+ {+ setFilters: (state, { filters }) => ({ ...state, ...filters }),+ resetFilters: () => DEFAULT_FILTERS,+ },+ ],+ selectedIds: [+ {} as Record<string, boolean>,+ {+ toggleSelected: (state, { invocationId }) => {+ const next = { ...state }+ if (next[invocationId]) {+ delete next[invocationId]+ } else {+ next[invocationId] = true+ }+ return next+ },+ clearSelected: () => ({}),+ setSelectedIds: (_, { ids }) => Object.fromEntries(ids.map((id) => [id, true])),+ },+ ],+ expandedIds: [+ {} as Record<string, boolean>,+ {+ setExpanded: (state, { invocationId, expanded }) => {+ const next = { ...state }+ if (expanded) {+ next[invocationId] = true+ } else {+ delete next[invocationId]+ }+ return next+ },+ },+ ],+ hasMore: [+ false,+ {+ setHasMore: (_, { hasMore }) => hasMore,+ setFilters: () => false,+ resetFilters: () => false,+ },+ ],+ hasLoadedOnce: [+ false,+ {+ setHasMore: () => true,+ },+ ],+ }),++ loaders(({ props, values, actions }) => ({+ runs: [+ [] as HogInvocationRow[],+ {+ loadRuns: async (_, breakpoint) => {+ await breakpoint(100)+ const rows = await fetchRunsPage(props, values.filters, 0)+ breakpoint()+ actions.setHasMore(rows.length >= HOG_INVOCATIONS_PAGE_SIZE)+ return rows+ },+ loadMore: async (_, breakpoint) => {+ await breakpoint(50)+ const offset = values.runs.length+ const newRows = await fetchRunsPage(props, values.filters, offset)+ breakpoint()+ actions.setHasMore(newRows.length >= HOG_INVOCATIONS_PAGE_SIZE)+ return [...values.runs, ...newRows]+ },+ },+ ],+ sparkline: [+ null as SparklineData | null,+ {+ loadSparkline: async (_, breakpoint) => {+ await breakpoint(100)+ const data = await fetchSparkline(props, values.filters)+ breakpoint()+ return data+ },+ },+ ],+ personPropertiesById: [+ {} as Record<string, { properties: Record<string, any>; distinct_ids?: string[] }>,+ {+ hydratePeople: async ({ personIds }, breakpoint) => {+ // person_id comes from CH rows so it _should_ already be a UUID,+ // but the values flow back through user-controlled state (URL+ // params can seed selectedRowIds etc.). Validate as a UUID+ // before interpolation so a malformed entry can't smuggle SQL+ // through `toUUID('…')`.+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i+ const toFetch = personIds.filter(+ (id) => id && UUID_PATTERN.test(id) && !values.personPropertiesById[id]+ )+ if (toFetch.length === 0) {+ return values.personPropertiesById+ }+ await breakpoint(50)+ const idList = hogql.raw(toFetch.map((id) => `toUUID('${id}')`).join(','))+ const query = hogql`+ SELECT id, properties+ FROM persons+ WHERE id IN (${idList})+ `+ const response = await api.queryHogQL(query, {+ scene: 'HogInvocations',+ productKey: 'pipeline_destinations',+ })+ breakpoint()+ const next = { ...values.personPropertiesById }+ for (const row of response.results ?? []) {+ const [id, propsJson] = row as unknown as [string, string]+ let properties: Record<string, any> = {}+ try {+ properties = JSON.parse(propsJson || '{}')+ } catch {+ // Malformed JSON — fall back to empty object.+ }+ next[id] = { properties }+ }+ return next+ },+ },+ ],+ })),++ selectors({+ statusCounts: [+ (s) => [s.runs],+ (runs): Record<RunStatus, number> => {+ const counts: Record<RunStatus, number> = { running: 0, succeeded: 0, failed: 0 }+ for (const r of runs) {+ counts[r.status] = (counts[r.status] ?? 0) + 1+ }+ return counts+ },+ ],+ selectedCount: [(s) => [s.selectedIds], (selectedIds) => Object.keys(selectedIds).length],+ canBulkRerun: [+ (s) => [s.selectedCount],+ (selectedCount) => selectedCount > 0 && selectedCount <= HOG_INVOCATIONS_RERUN_MAX_COUNT,+ ],+ rerunableSelectedIds: [+ (s) => [s.selectedIds, s.runs],+ (selectedIds, runs): string[] => {+ const ids = Object.keys(selectedIds)+ if (ids.length === 0) {+ return []+ }+ const byId = new Map(runs.map((r) => [r.invocation_id, r]))+ return ids.filter((id) => {+ const row = byId.get(id)+ // Allow rerun if row not loaded — the worker enforces its own checks.+ return !row || (row.status !== 'running' && !isRerunWrapperKind(row.function_kind))+ })+ },+ ],+ hasRunningRows: [(s) => [s.runs], (runs): boolean => runs.some((r) => r.status === 'running')],+ selectableIds: [+ (s) => [s.runs],+ (runs): string[] =>+ runs+ .filter((r) => !isRerunWrapperKind(r.function_kind) && r.status !== 'running')+ .map((r) => r.invocation_id),+ ],+ selectAllState: [+ (s) => [s.selectedIds, s.selectableIds],+ (selectedIds, selectableIds): 'all' | 'some' | 'none' => {+ if (selectableIds.length === 0) {+ return 'none'+ }+ const selectedCount = selectableIds.filter((id) => selectedIds[id]).length+ if (selectedCount === 0) {+ return 'none'+ }+ return selectedCount === selectableIds.length ? 'all' : 'some'+ },+ ],+ }),++ listeners(({ props, actions, values, cache }) => ({+ refresh: () => {+ actions.loadRuns(null)+ actions.loadSparkline(null)+ },+ setFilters: () => {+ actions.refresh()+ },+ resetFilters: () => {+ actions.refresh()+ },+ loadRunsSuccess: () => {+ scheduleAutoRefresh(cache, actions, values)+ const personIds = Array.from(new Set(values.runs.map((r) => r.person_id).filter(Boolean)))+ if (personIds.length > 0) {+ actions.hydratePeople(personIds)+ }+ },+ loadMoreSuccess: () => {+ scheduleAutoRefresh(cache, actions, values)+ const personIds = Array.from(new Set(values.runs.map((r) => r.person_id).filter(Boolean)))+ if (personIds.length > 0) {+ actions.hydratePeople(personIds)+ }+ },+ rerunInvocations: async ({ invocationIds }) => {+ if (invocationIds.length === 0) {+ lemonToast.warning('Nothing to rerun')+ return+ }+ if (invocationIds.length > HOG_INVOCATIONS_RERUN_MAX_COUNT) {+ lemonToast.error(`Rerun request capped at ${HOG_INVOCATIONS_RERUN_MAX_COUNT} invocations per request`)+ return+ }++ const { filters } = values+ const teamId = ApiConfig.getCurrentTeamId()+ // `resolveDateRange` handles `-24h`-style relative strings as a+ // duration anchored to "now". Using `dateStringToDayJs` directly+ // anchors relative strings to start-of-day, which would silently+ // widen the rerun window beyond what the user sees in the table.+ const { start: rerunStart, end: rerunEnd } = resolveDateRange(filters)+ const windowStart = rerunStart.toISOString()+ const windowEnd = rerunEnd.toISOString()++ const requestBody = {+ filter: {+ window_start: windowStart,+ window_end: windowEnd,+ invocation_ids: invocationIds,+ // When rerunning specific IDs, don't restrict by status — the worker+ // defaults a missing status to ['failed'], which would silently drop+ // succeeded rows the user explicitly selected. The ID restriction+ // alone determines what gets rerun (the worker still skips in-flight).+ status: ['running', 'succeeded', 'failed'] as HogInvocationRerunFilterStatusEnumApi[],+ },+ }++ try {+ const response =+ props.functionKind === 'hog_function'+ ? await hogFunctionsRerunCreate(String(teamId), props.id, requestBody)+ : await hogFlowsRerunCreate(String(teamId), props.id, requestBody)+ lemonToast.success(+ `Rerun job ${response.rerun_job_id.slice(0, 8)}… queued. Updated rows will appear here as the worker drains the job.`+ )+ actions.clearSelected()+ // Re-run rows aren't `running` yet — force a short polling window so they surface.+ cache.forceRefreshUntil = Date.now() + FORCE_REFRESH_WINDOW_MS+ actions.loadRuns(null)+ } catch (e: any) {+ lemonToast.error(`Failed to enqueue rerun: ${e?.detail ?? e?.message ?? String(e)}`)+ }+ },+ bulkRerun: async ({ params }) => {+ const teamId = ApiConfig.getCurrentTeamId()+ // Resolve via `resolveDateRange` so `-24h` produces "24 hours ago",+ // matching the table/sparkline. Anchoring relative strings to+ // start-of-day here would silently rerun rows outside the visible+ // window.+ const { start: bulkStart, end: bulkEnd } = resolveDateRange(params)+ const windowStart = bulkStart.toISOString()+ const windowEnd = bulkEnd.toISOString()++ const requestBody = {+ filter: {+ window_start: windowStart,+ window_end: windowEnd,+ status: params.status?.length+ ? (params.status as HogInvocationRerunFilterStatusEnumApi[])+ : undefined,+ error_kind: params.error_kind?.length ? params.error_kind : undefined,+ max_count: params.max_count,+ max_attempts: params.max_attempts,+ },+ }++ try {+ const response =+ props.functionKind === 'hog_function'+ ? await hogFunctionsRerunCreate(String(teamId), props.id, requestBody)+ : await hogFlowsRerunCreate(String(teamId), props.id, requestBody)+ lemonToast.success(+ `Re-run job ${response.rerun_job_id.slice(0, 8)}… queued. Matching invocations will be re-run in the background.`+ )+ // Re-run rows aren't `running` yet — force a short polling window so they surface.+ cache.forceRefreshUntil = Date.now() + FORCE_REFRESH_WINDOW_MS+ actions.loadRuns(null)+ } catch (e: any) {+ lemonToast.error(`Failed to enqueue re-run: ${e?.detail ?? e?.message ?? String(e)}`)+ }+ },+ })),++ actionToUrl(({ values }) => {+ const buildUrl = (): [+ string,+ Record<string, string | undefined>,+ Record<string, string>,+ { replace: true },+ ] => [+ router.values.location.pathname,+ { ...router.values.searchParams, ...filtersToSearchParams(values.filters) },+ router.values.hashParams,+ { replace: true },+ ]+ return {+ setFilters: buildUrl,+ resetFilters: buildUrl,+ }+ }),++ urlToAction(({ actions, values }) => {+ const handleSearch = (_: any, searchParams: Record<string, string | undefined>): void => {+ const next = searchParamsToFilters(searchParams)+ // Diff against current state to avoid looping with actionToUrl.+ const changed = Object.entries(next).some(+ ([key, value]) =>+ JSON.stringify(value) !== JSON.stringify(values.filters[key as keyof HogInvocationsFilters])+ )+ if (changed) {+ actions.setFilters(next)+ }+ }+ return {+ '*': handleSearch,+ }+ }),+])diff --git a/frontend/src/scenes/hog-functions/logs/HogFunctionLogs.tsx b/frontend/src/scenes/hog-functions/logs/HogFunctionLogs.tsxindex 28dee2af7ffd..da987cb35708 100644--- a/frontend/src/scenes/hog-functions/logs/HogFunctionLogs.tsx+++ b/frontend/src/scenes/hog-functions/logs/HogFunctionLogs.tsx@@ -11,6 +11,7 @@ import { urls } from 'scenes/urls'import { hogFunctionConfigurationLogic } from '../configuration/hogFunctionConfigurationLogic'import { hogFunctionTestLogic } from '../configuration/hogFunctionTestLogic'+import { InvocationsLegacyTabBanner } from '../invocations/InvocationsTabBanners'import { hogFunctionLogsLogic } from './hogFunctionLogsLogic'import { LogsViewer } from './LogsViewer'import { GroupedLogEntry, LogsViewerLogicProps } from './logsViewerLogic'@@ -34,6 +35,7 @@ export function HogFunctionLogs(): JSX.Element | null {return (<>+ <InvocationsLegacyTabBanner legacyTab="Logs" />{selectingMany ? (<div className="flex gap-2 items-center mb-2 justify-end"><>diff --git a/frontend/src/scenes/hog-functions/logs/LogsViewer.tsx b/frontend/src/scenes/hog-functions/logs/LogsViewer.tsxindex de0984a710b6..dd3fbd122fa0 100644--- a/frontend/src/scenes/hog-functions/logs/LogsViewer.tsx+++ b/frontend/src/scenes/hog-functions/logs/LogsViewer.tsx@@ -1,4 +1,5 @@import { useActions, useValues } from 'kea'+import { useMemo, useState } from 'react'import { IconCalendar, IconEye, IconList, IconRefresh, IconSearch, IconTableOfContents } from '@posthog/icons'import {@@ -16,7 +17,7 @@ import {import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { TZLabel } from 'lib/components/TZLabel'-import { IconWithCount } from 'lib/lemon-ui/icons'+import { IconArrowDown, IconArrowUp, IconWithCount } from 'lib/lemon-ui/icons'import { pluralize } from 'lib/utils/strings'import { LogEntryLevel } from '~/types'@@ -65,6 +66,8 @@ export type LogsViewerProps = LogsViewerLogicProps & {hideDateFilter?: booleanhideLevelsFilter?: booleanhideInstanceIdColumn?: boolean+ /** Initial display order. Defaults to newest-first; pass true for oldest-first. */+ defaultAscending?: boolean}/**@@ -78,6 +81,7 @@ export function LogsViewer({hideDateFilter,hideLevelsFilter,hideInstanceIdColumn,+ defaultAscending = false,...props}: LogsViewerProps): JSX.Element {const logic = logsViewerLogic(props)@@ -95,6 +99,21 @@ export function LogsViewer({} = useValues(logic)const { revealHiddenLogs, loadOlderLogs, setFilters, setRowExpanded, setIsGrouped } = useActions(logic)+ // Display order is a UI-only toggle — the fetch still pulls newest-first+ // (that's what powers "load older" pagination). Ascending puts oldest at+ // the top for following execution order; surfaces opt in via+ // `defaultAscending`. We just reverse the array before handing it to+ // LemonTable.+ const [ascending, setAscending] = useState(defaultAscending)+ const orderedUngroupedLogs = useMemo(+ () => (ascending ? [...unGroupedLogs].reverse() : unGroupedLogs),+ [ascending, unGroupedLogs]+ )+ const orderedGroupedLogs = useMemo(+ () => (ascending ? [...groupedLogs].reverse() : groupedLogs),+ [ascending, groupedLogs]+ )+const groupedLogColumns: LemonTableColumn<GroupedLogEntry, keyof GroupedLogEntry | undefined>[] = renderColumns([{title: 'Timestamp',@@ -266,13 +285,20 @@ export function LogsViewer({}tooltip={`Show ${pluralize(hiddenLogs.length, 'newer entry', 'newer entries')}`}/>+ <LemonButton+ size="small"+ type="secondary"+ icon={ascending ? <IconArrowDown /> : <IconArrowUp />}+ onClick={() => setAscending(!ascending)}+ tooltip={ascending ? 'Oldest first (click to reverse)' : 'Newest first (click to reverse)'}+ /></div></div>{isGrouped ? (<LemonTablekey="grouped"- dataSource={groupedLogs}+ dataSource={orderedGroupedLogs}loading={logsLoading}className="ph-no-capture overflow-y-auto"rowKey={(record) => record.instanceId}@@ -308,7 +334,7 @@ export function LogsViewer({instanceLabel={instanceLabel}renderMessage={renderMessage}key="ungrouped"- dataSource={unGroupedLogs}+ dataSource={orderedUngroupedLogs}loading={logsLoading}className="ph-no-capture overflow-y-auto"rowKey={(record, index) => `${record.timestamp.toISOString()}-${index}`}diff --git a/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx b/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsxindex d76d247e1d50..74a74d830364 100644--- a/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx+++ b/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx@@ -89,18 +89,26 @@ export const toAbsoluteClickhouseTimestamp = (timestamp: Dayjs): string => {return timestamp.tz(teamTimezone).format('YYYY-MM-DD HH:mm:ss.SSS')}+// An empty `levels` selection means "all levels" in the picker (it renders as+// "All levels"), so omit the predicate entirely. Emitting `lower(level) IN ()`+// is invalid HogQL ("empty parentheses are not a valid expression") and fails+// the whole query — which surfaced as a toast when deselecting the last level+// or paging older entries. Values come from a fixed enum, so raw is safe here.+const levelInClause = (levels: LogEntryLevel[]): string =>+ levels.length > 0 ? `AND lower(level) IN (${levels.map((level) => `'${level.toLowerCase()}'`).join(',')})` : ''+const buildBoundaryFilters = (request: LogEntryParams): string => {return hogql`AND log_source = ${request.sourceType}AND log_source_id = ${request.sourceId}AND timestamp > {filters.dateRange.from}AND timestamp < {filters.dateRange.to}- AND lower(level) IN (${hogql.raw(request.levels.map((level) => `'${level.toLowerCase()}'`).join(','))})+ ${hogql.raw(levelInClause(request.levels))}`}const buildSearchFilters = ({ searchGroups, levels, instanceId }: LogEntryParams): string => {- let query = hogql`\nAND lower(level) IN (${hogql.raw(levels.map((level) => `'${level.toLowerCase()}'`).join(','))})`+ let query = hogql`\n${hogql.raw(levelInClause(levels))}`searchGroups.forEach((search) => {query = (query +diff --git a/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx b/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsxindex 1a13fefa9721..12508b6a36f1 100644--- a/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx+++ b/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx@@ -34,6 +34,7 @@ import {} from '../configuration/hogFunctionConfigurationLogic'import { hogFunctionTestLogic } from '../configuration/hogFunctionTestLogic'import { HogFunctionFilters } from '../filters/HogFunctionFilters'+import { InvocationsLegacyTabBanner } from '../invocations/InvocationsTabBanners'import { tagTypeForLevel } from '../logs/LogsViewer'import { CyclotronJobTestInvocationResultWithEventId, hogFunctionTestingLogic } from './hogFunctionTestingLogic'@@ -81,6 +82,7 @@ export function HogFunctionTesting(): JSX.Element | null {return (<BindLogic logic={hogFunctionTestingLogic} props={{ id }}><div className="deprecated-space-y-3">+ <InvocationsLegacyTabBanner legacyTab="Testing" /><LemonBanner type="info"><span>This is a list of all events matching your filters. You can run the function using thesediff --git a/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.routing.test.tsindex 825db9306b18..862de0526723 100644--- a/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts+++ b/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts@@ -63,6 +63,8 @@ describe('RerunPaginatorService queue routing', () => {})// Stub the CH query + rehydration so the test exercises only the routing.+ // `fetchRunningInvocationIds` (the kafka-path in-flight guard) defaults to+ // "nothing in flight" so routing tests aren't affected by it.const stubPage = (ids: string[]): void => {jest.spyOn(paginator as any, 'fetchPage').mockResolvedValue([])jest.spyOn(paginator as any, 'rehydrateBatch').mockResolvedValue({@@ -70,6 +72,7 @@ describe('RerunPaginatorService queue routing', () => {skipped: 0,queuedInvocations: ids.map((id) => ({ id })),})+ jest.spyOn(paginator as any, 'fetchRunningInvocationIds').mockResolvedValue(new Set<string>())}const runPage = (state: RerunJobState) =>@@ -98,6 +101,32 @@ describe('RerunPaginatorService queue routing', () => {expect(hogQueue.queueInvocations).not.toHaveBeenCalled()})+ it('skips hog_function invocations whose latest lifecycle row is still running', async () => {+ stubPage(['inv-running', 'inv-done'])+ // Kafka has no conflict guard, so re-enqueuing an in-flight invocation+ // would double its side effects — skip the one CH reports as running.+ jest.spyOn(paginator as any, 'fetchRunningInvocationIds').mockResolvedValue(new Set(['inv-running']))++ const { state: next } = await runPage(buildState('hog_function'))++ expect(hogQueue.queueInvocations).toHaveBeenCalledTimes(1)+ expect((hogQueue.queueInvocations.mock.calls[0][0] as any[]).map((i) => i.id)).toEqual(['inv-done'])+ expect((paginator as any).invocationResultsRowsService.dropQueuedRowsFor).toHaveBeenCalledWith(['inv-running'])+ expect(next.progress.queued).toBe(1)+ expect(next.progress.skipped).toBe(1)+ })++ it('does not enqueue on the hog path when every invocation is still in-flight', async () => {+ stubPage(['inv-running'])+ jest.spyOn(paginator as any, 'fetchRunningInvocationIds').mockResolvedValue(new Set(['inv-running']))++ const { state: next } = await runPage(buildState('hog_function'))++ expect(hogQueue.queueInvocations).not.toHaveBeenCalled()+ expect(next.progress.queued).toBe(0)+ expect(next.progress.skipped).toBe(1)+ })+it('counts hogflow in-flight conflicts as skipped instead of failing the page', async () => {stubPage(['inv-conflict'])// The postgres-v2 upsert raises a conflict when the existing row is@@ -110,4 +139,49 @@ describe('RerunPaginatorService queue routing', () => {expect(next.progress.skipped).toBe(1)expect(next.progress.last_error).toBeUndefined()})++ const rehydrate = (type: string, headers: Record<string, string>) => {+ const hogFunctionManager = {+ getHogFunction: jest.fn().mockResolvedValue({ id: 'fn-1', team_id: 1, type }),+ } as unknown as HogFunctionManagerService+ const webhookPaginator = new RerunPaginatorService(+ {} as any,+ hogFunctionManager,+ {} as unknown as HogFlowManagerService,+ {} as unknown as HogInvocationResultsService,+ { hog_function: hogQueue, hog_flow: hogflowQueue },+ {} as unknown as HogFunctionMonitoringService,+ 10000+ )+ const row = {+ invocation_id: 'inv-1',+ parent_run_id: '',+ attempts: 0,+ last_scheduled_at: '2026-01-01 00:00:00',+ first_scheduled_at: '2026-01-01 00:00:00',+ invocation_globals: JSON.stringify({+ event: { uuid: 'e1' },+ request: { method: 'POST', headers, query: {}, body: {}, stringBody: '' },+ }),+ }+ return (webhookPaginator as any).rehydrateInvocation(1, 'hog_function', 'fn-1', row)+ }++ it('strips request.headers from rehydrated globals for source-webhook functions', async () => {+ const invocation = await rehydrate('source_webhook', {+ authorization: 'secret',+ 'content-type': 'application/json',+ })+ expect(invocation.state.globals.request.headers).toEqual({})+ })++ it('strips request.headers for warehouse-source-webhook functions too', async () => {+ const invocation = await rehydrate('warehouse_source_webhook', { 'x-api-key': 'secret' })+ expect(invocation.state.globals.request.headers).toEqual({})+ })++ it('leaves request.headers intact for non-webhook functions', async () => {+ const invocation = await rehydrate('destination', { authorization: 'secret' })+ expect(invocation.state.globals.request.headers).toEqual({ authorization: 'secret' })+ })})diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.tsindex 2943707d9cd5..03bc0d6c9d77 100644--- a/nodejs/src/cdp/rerun/rerun-paginator.service.ts+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.ts@@ -25,6 +25,10 @@ import {import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'import { RERUN_PAGE_SIZE, RerunFunctionKind, RerunJobProgress, RerunJobState } from './rerun-job.types'+// Function types whose stored globals carry inbound `request.headers`+// (sender credentials) that must be stripped before a rerun rehydrates them.+const WEBHOOK_SOURCE_TYPES = new Set(['source_webhook', 'warehouse_source_webhook'])+const counterRerunPageProcessed = new Counter({name: 'cdp_hog_invocation_rerun_pages_processed_total',help: 'Rerun paginator pages processed, by function kind and outcome.',@@ -172,9 +176,34 @@ export class RerunPaginatorService {this.invocationResultsRowsService.dropQueuedRowsFor(Array.from(conflictingIds))}} else {- // kafka. No PK, so a re-enqueue with the original- // invocation_id can't conflict — no overwrite path needed.- await this.jobQueues.hog_function.queueInvocations(invocationsToEnqueue)+ // kafka. There's no PK to reject a duplicate the way the+ // postgres-v2 path does, so re-enqueuing an invocation that+ // is still running would fire its side effects (webhook,+ // email) a second time. Skip any whose latest CH lifecycle+ // row is still 'running'. The 'running' rows we queued for+ // this page aren't flushed yet, so this reflects prior state.+ const runningIds = await this.fetchRunningInvocationIds(+ teamId,+ function_kind,+ function_id,+ invocationsToEnqueue.map((i) => i.id)+ )+ if (runningIds.size > 0) {+ logger.warn('Rerun skipping hog invocations that are still in-flight', {+ rerun_function_kind: function_kind,+ rerun_function_id: function_id,+ conflicting_invocation_ids: Array.from(runningIds),+ })+ conflictSkipped = runningIds.size+ for (let i = 0; i < conflictSkipped; i++) {+ counterRerunInvocationsSkipped.labels(function_kind, 'still_in_flight_hog').inc()+ }+ invocationsToEnqueue = queuedInvocations.filter((i) => !runningIds.has(i.id))+ this.invocationResultsRowsService.dropQueuedRowsFor(Array.from(runningIds))+ }+ if (invocationsToEnqueue.length > 0) {+ await this.jobQueues.hog_function.queueInvocations(invocationsToEnqueue)+ }}await this.invocationResultsRowsService.flush()counterRerunInvocationsQueued.labels(function_kind).inc(invocationsToEnqueue.length)@@ -359,12 +388,54 @@ export class RerunPaginatorService {return { scheduled_at: last.last_scheduled_at, invocation_id: last.invocation_id }}+ /**+ * Of the given hog-function invocation ids, return those whose latest+ * lifecycle row is still `running`. The query keys on the table's primary+ * prefix (team_id, function_kind, function_id, invocation_id) so it stays+ * cheap without a partition bound. Used to avoid re-enqueuing an in-flight+ * invocation on the kafka path, which has no conflict guard of its own.+ */+ private async fetchRunningInvocationIds(+ teamId: number,+ functionKind: RerunFunctionKind,+ functionId: string,+ invocationIds: 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_inflight */+ 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) = 0+ AND argMax(status, version) = 'running'`,+ query_params: {+ team_id: teamId,+ function_kind: functionKind,+ function_id: functionId,+ invocation_ids: invocationIds,+ },+ 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.filterconst requestedStatus = filter.status?.length ? filter.status : ['failed']// 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.+ // before passing as a query parameter. The bound params below are typed+ // `DateTime64(6, 'UTC')` so the (tz-stripped) UTC wall-clock string is+ // always interpreted as UTC — an untyped `DateTime64` would be parsed in+ // the CH server timezone, shifting the window on non-UTC servers.const windowStart = toClickhouseDateTime(filter.window_start)const windowEnd = toClickhouseDateTime(filter.window_end)const cursorScheduledAt = state.progress.cursor?.scheduled_at@@ -377,7 +448,7 @@ export class RerunPaginatorService {const cursor = state.progress.cursorconst cursorClause =cursor && cursor.scheduled_at- ? ' AND (scheduled_at, invocation_id) < ({cursor_scheduled_at:DateTime64}, {cursor_invocation_id:String})'+ ? " AND (scheduled_at, invocation_id) < ({cursor_scheduled_at:DateTime64(6, 'UTC')}, {cursor_invocation_id:String})": ''const errorKindClause = filter.error_kind?.length? 'AND argMax(error_kind, version) IN {error_kind:Array(String)}'@@ -404,8 +475,8 @@ export class RerunPaginatorService {WHERE team_id = {team_id:Int64}AND function_kind = {function_kind:String}AND function_id = {function_id:String}- AND scheduled_at >= {window_start:DateTime64}- AND scheduled_at < {window_end:DateTime64}+ AND scheduled_at >= {window_start:DateTime64(6, 'UTC')}+ AND scheduled_at < {window_end:DateTime64(6, 'UTC')}${invocationIdsClause}${cursorClause}GROUP BY invocation_id@@ -517,6 +588,19 @@ export class RerunPaginatorService {// from the current hog function config, so the rerun runs against// the latest config/secrets rather than a stored snapshot.const persistedGlobals = parsedGlobals as HogFunctionInvocationGlobalsWithInputs++ // For source-webhook functions the stored `request.headers` AND+ // `request.query` carry the inbound sender's credentials+ // (Authorization / x-api-key / signing secrets in headers; URL+ // tokens like `?token=` in query). Rerunning feeds those back into+ // the live function, so a write-access user could reconfigure the+ // function to forward them to an attacker endpoint and replay+ // history to exfiltrate past senders' secrets. Drop both on+ // rehydration; non-webhook globals never carry `request` so they're+ // untouched.+ if (WEBHOOK_SOURCE_TYPES.has(hogFunction.type) && persistedGlobals.request) {+ persistedGlobals.request = { ...persistedGlobals.request, headers: {}, query: {} }+ }const invocation: CyclotronJobInvocationHogFunction = {// Preserve invocation_id so lifecycle rows collapse under the// ReplacingMergeTree on the same key.diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.tsindex 8f08e205b9ab..90363545db42 100644--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts@@ -316,7 +316,33 @@ describe('HogInvocationResultsService', () => {})})- // Silence unused import linter noise — DateTime is imported for future tests- // that exercise queueScheduledAt explicitly.- void DateTime+ describe('first_scheduled_at', () => {+ it('stamps the original scheduled time onto invocation state on the first running row', async () => {+ const invocation = createExampleInvocation()+ invocation.queueScheduledAt = DateTime.utc(2026, 1, 1, 0, 0, 0)+ service.queueLifecycleRow(invocation, 'running')+ await service.flush()++ const rows = parseProducedRows(outputs)+ expect(rows[0].first_scheduled_at).toBe(rows[0].scheduled_at)+ expect(invocation.state.firstScheduledAt).toBe(rows[0].scheduled_at)+ })++ it('keeps the original first_scheduled_at on the terminal row after a fetch retry reschedules', async () => {+ const invocation = createExampleInvocation()+ invocation.queueScheduledAt = DateTime.utc(2026, 1, 1, 0, 0, 0)+ service.queueLifecycleRow(invocation, 'running')+ const original = invocation.state.firstScheduledAt++ // Simulate a cyclotron fetch retry: queueScheduledAt is overwritten+ // with a later backoff time before the terminal row is produced.+ invocation.queueScheduledAt = DateTime.utc(2026, 1, 1, 0, 5, 0)+ service.queueLifecycleRow(invocation, 'succeeded')+ await service.flush()++ const terminal = parseProducedRows(outputs).find((r) => r.status === 'succeeded')!+ expect(terminal.first_scheduled_at).toBe(original)+ expect(terminal.scheduled_at).not.toBe(terminal.first_scheduled_at)+ })+ })})diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.tsindex 5d11e6df988f..605ee412c41b 100644--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts@@ -335,15 +335,28 @@ export class HogInvocationResultsService {? (invocation.state?.rerunAttempts ?? 0): 0- // `firstScheduledAt` is set by the rerun paginator on rehydration so- // retries inherit the original's value; for fresh invocations it's- // unset and we fall back to the current `scheduled_at`.- const firstScheduledAtRaw = isHogFunctionInvocation(invocation)+ // `firstScheduledAt` records the original cyclotron-scheduled time. The+ // rerun paginator sets it on rehydration; here we also stamp it onto the+ // state the first time we emit a 'running' row, so it survives cyclotron+ // fetch retries (which overwrite `queueScheduledAt`). The 'running' row+ // fires once at invocation creation, before the invocation is enqueued,+ // so the value carries forward in the serialized state. Without this the+ // terminal row — written after a retry — would record the retry time and+ // win the ReplacingMergeTree argMax, mislabeling the run's start time.+ let firstScheduledAt = isHogFunctionInvocation(invocation)? invocation.state?.firstScheduledAt: isHogFlowInvocation(invocation)? invocation.state?.firstScheduledAt: undefinedconst scheduledAtIso = isoMicroseconds(invocation.queueScheduledAt?.toJSDate() ?? now)+ if (status === 'running' && firstScheduledAt === undefined) {+ firstScheduledAt = scheduledAtIso+ if (isHogFunctionInvocation(invocation)) {+ invocation.state.firstScheduledAt = scheduledAtIso+ } else if (isHogFlowInvocation(invocation) && invocation.state) {+ invocation.state.firstScheduledAt = scheduledAtIso+ }+ }const row: HogInvocationResultRow = {team_id: invocation.teamId,@@ -355,7 +368,7 @@ export class HogInvocationResultsService {attempts: rerunAttempts,is_retry: rerunAttempts > 0 ? 1 : 0,scheduled_at: scheduledAtIso,- first_scheduled_at: firstScheduledAtRaw ?? scheduledAtIso,+ first_scheduled_at: firstScheduledAt ?? scheduledAtIso,started_at: startedAt ? isoMicroseconds(startedAt) : null,finished_at: finishedAt ? isoMicroseconds(finishedAt) : null,duration_ms: durationMs,diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex eaf450944769..b2bf3620fb81 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -306,10 +306,11 @@ export type CyclotronJobInvocationHogFunctionContext = {// lifecycle row producer reads this to drive the `attempts` + `is_retry`// columns in `hog_invocation_results`.rerunAttempts?: number- // ISO timestamp of the *original* cyclotron-scheduled time. Carried through- // reruns so the lifecycle row producer can populate `first_scheduled_at`- // verbatim — ReplacingMergeTree would otherwise collapse retries to the- // latest version and lose the original.+ // ISO timestamp of the *original* cyclotron-scheduled time. Stamped on the+ // first 'running' lifecycle row and carried through both cyclotron fetch+ // retries and reruns so the producer can populate `first_scheduled_at`+ // verbatim — ReplacingMergeTree would otherwise collapse to the latest+ // version (a retry's scheduled time) and lose the original.firstScheduledAt?: stringactionId?: string // The hogflow action node ID, used for metrics instance_id when executing within a workflow}@@ -376,7 +377,8 @@ export type HogFlowInvocationContext = {// the same way it does for hog functions, so the `max_attempts` guard on// the rerun filter actually applies to flows.rerunAttempts?: number- // Carried verbatim through retries so `first_scheduled_at` survives the+ // Stamped on the first 'running' row and carried verbatim through cyclotron+ // fetch retries and reruns so `first_scheduled_at` survives the// ReplacingMergeTree collapse on the hog_invocation_results table.firstScheduledAt?: string}diff --git a/posthog/api/hog_invocation_rerun.py b/posthog/api/hog_invocation_rerun.pynew file mode 100644index 000000000000..5b533b1b3d29--- /dev/null+++ b/posthog/api/hog_invocation_rerun.py@@ -0,0 +1,112 @@+"""+Rerun endpoint serializers shared by `HogFunctionViewSet` and `HogFlowViewSet`.++These define the request/response shape for `POST .../{kind}/{id}/rerun`. The+view validates input, then proxies through to the Node CDP worker via+`rerun_hog_invocations` in `posthog.plugins.plugin_server_api`. The worker+reads matching rows from ClickHouse `hog_invocation_results`, rehydrates from+the stored `invocation_globals`, and re-enqueues onto cyclotron.+"""++from datetime import timedelta++from rest_framework import serializers++from posthog.settings.utils import get_from_env++# Hard cap on how many invocations can be queued for rerun in a single request.+# Configurable via env so on-callers can bump it without a deploy if a batch+# rerun legitimately needs to drain more rows. The Node side reads the same+# env var from its CDP config — keep both in sync if you tweak the default.+HOG_INVOCATION_RERUN_MAX_COUNT = get_from_env("HOG_INVOCATION_RERUN_MAX_COUNT", default=10000, type_cast=int)++# Matches the ClickHouse TTL on `hog_invocation_results` (30 days). A rerun+# window any longer would point at partitions that have already been dropped.+RERUN_MAX_WINDOW_DAYS = 30+++class HogInvocationRerunFilterSerializer(serializers.Serializer):+ """Filter shape for the rerun endpoint. `window_start`/`window_end` are required."""++ window_start = serializers.DateTimeField(required=True, help_text="Inclusive lower bound on `scheduled_at` (UTC).")+ window_end = serializers.DateTimeField(required=True, help_text="Exclusive upper bound on `scheduled_at` (UTC).")+ status = serializers.ListField(+ child=serializers.ChoiceField(choices=["running", "succeeded", "failed"]),+ required=False,+ help_text="Restrict to invocations whose latest status is one of these. Defaults to ['failed'].",+ )+ error_kind = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Restrict to invocations whose error_kind matches one of these (e.g. 'http_5xx', 'timeout').",+ )+ max_attempts = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=255,+ help_text="Skip invocations that have already been attempted this many times or more.",+ )+ max_count = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=HOG_INVOCATION_RERUN_MAX_COUNT,+ help_text=(+ f"Maximum number of invocations to rerun in this request. "+ f"Server-side cap is {HOG_INVOCATION_RERUN_MAX_COUNT}."+ ),+ )+ invocation_ids = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ max_length=HOG_INVOCATION_RERUN_MAX_COUNT,+ help_text=(+ "Optional restriction to specific invocation IDs within the window. "+ f"Capped at {HOG_INVOCATION_RERUN_MAX_COUNT} per request. Always combined with "+ "`window_start`/`window_end` so the ClickHouse query can be partition-pruned."+ ),+ )++ def validate(self, attrs: dict) -> dict:+ start = attrs.get("window_start")+ end = attrs.get("window_end")+ if start and end:+ if end <= start:+ raise serializers.ValidationError("'window_end' must be after 'window_start'.")+ if end - start > timedelta(days=RERUN_MAX_WINDOW_DAYS):+ raise serializers.ValidationError(+ f"Rerun window cannot exceed {RERUN_MAX_WINDOW_DAYS} days "+ f"(ClickHouse TTL on hog_invocation_results)."+ )+ return attrs+++class HogInvocationRerunRequestSerializer(serializers.Serializer):+ """Rerun invocations of a hog function or hog flow from their stored payloads."""++ filter = HogInvocationRerunFilterSerializer(+ required=True,+ help_text=(+ "Required. `window_start` / `window_end` pin the query to a small set of date "+ "partitions on the `hog_invocation_results` table. Optional `invocation_ids` "+ "restricts to specific invocations within that window."+ ),+ )+++class HogInvocationRerunResponseSerializer(serializers.Serializer):+ """+ Response from the rerun endpoint. The endpoint only enqueues a wrapper+ job onto the cyclotron `rerun` queue — the actual ClickHouse paging and+ re-enqueue work happens asynchronously in the `cdp-rerun-worker` service.+ Use `rerun_job_id` to look up progress on the wrapper job later.+ """++ rerun_job_id = serializers.CharField(+ help_text="ID of the cyclotron wrapper job that will run the rerun. Use this to poll status."+ )+ queued_count = serializers.IntegerField(+ help_text="Always 0 — rerun runs asynchronously. Kept for response shape stability.",+ )+ skipped_count = serializers.IntegerField(+ help_text="Always 0 — rerun runs asynchronously. Kept for response shape stability.",+ )diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 6b9428e54f27..88a31e6ff79f 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -90,6 +90,7 @@ from posthog.hogql.database.schema.experiment_metric_events_preaggregated importfrom posthog.hogql.database.schema.groups import GroupsTable, RawGroupsTablefrom posthog.hogql.database.schema.groups_revenue_analytics import GroupsRevenueAnalyticsTablefrom posthog.hogql.database.schema.heatmaps import HeatmapsTable+from posthog.hogql.database.schema.hog_invocation_results import HogInvocationResultsTablefrom posthog.hogql.database.schema.log_entries import (BatchExportLogEntriesTable,LogEntriesTable,@@ -380,6 +381,9 @@ def _construct_database_root_node(*, include_posthog_tables: bool) -> TableNode:"session_replay_features": TableNode(name="session_replay_features", table=SessionReplayFeaturesTable()),+ "hog_invocation_results": TableNode(+ name="hog_invocation_results", table=HogInvocationResultsTable()+ ),"metrics": TableNode(name="metrics", table=MetricsTable()),"metric_samples": TableNode(name="metric_samples", table=MetricSamplesTable()),"metric_series": TableNode(name="metric_series", table=MetricSeriesTable()),diff --git a/posthog/hogql/database/schema/hog_invocation_results.py b/posthog/hogql/database/schema/hog_invocation_results.pynew file mode 100644index 000000000000..a8bbbc588e16--- /dev/null+++ b/posthog/hogql/database/schema/hog_invocation_results.py@@ -0,0 +1,64 @@+from posthog.hogql.database.models import (+ BooleanDatabaseField,+ DateTimeDatabaseField,+ FieldOrTable,+ IntegerDatabaseField,+ StringDatabaseField,+ Table,+)++# One row per CDP invocation lifecycle event (start + finish, plus a row per rerun).+# The underlying ClickHouse table is a sharded ReplacingMergeTree keyed by+# (team_id, function_kind, function_id, invocation_id) with `version` as the+# tie-breaker — when querying, group by invocation_id and use argMax(field, version)+# to get the latest state, the same way persons are read.+#+# Access scope: this table is registered with HogQL under the standard team_id+# guard — same scope as `app_metrics2`, `metrics`, and other operational tables.+# Per-function / per-workflow access controls are NOT enforced here; any user+# with project query access can SELECT lifecycle rows (invocation_id, status,+# error_kind/message, event/person identifiers) for every function and flow+# in the project. Sensitive payload fields are excluded (see next paragraph),+# and the runs UI gates on function/flow access at the parent scene level.+#+# `invocation_globals` is intentionally NOT exposed here. The column carries the+# full rerun payload — for hog functions whose trigger is a source webhook, that+# includes `request.headers` (authorization, x-api-key, etc.). We don't want a+# tenant to be able to SELECT those via /api/projects/:id/query. The rerun path+# reads `invocation_globals` via the internal ClickHouse client (not HogQL) and+# strips `request.headers` for webhook sources at rehydration, so leaving the+# column off the HogQL schema entirely costs nothing for rerun. If the runs UI+# ever wants a "view payload" affordance, that should land as a server-side+# endpoint that gates on the function's write permission, not as a HogQL query.+HOG_INVOCATION_RESULTS_FIELDS: dict[str, FieldOrTable] = {+ "team_id": IntegerDatabaseField(name="team_id", nullable=False),+ "function_kind": StringDatabaseField(name="function_kind", nullable=False),+ "function_id": StringDatabaseField(name="function_id", nullable=False),+ "invocation_id": StringDatabaseField(name="invocation_id", nullable=False),+ "parent_run_id": StringDatabaseField(name="parent_run_id", nullable=False),+ "status": StringDatabaseField(name="status", nullable=False),+ "attempts": IntegerDatabaseField(name="attempts", nullable=False),+ "is_retry": BooleanDatabaseField(name="is_retry", nullable=False),+ "scheduled_at": DateTimeDatabaseField(name="scheduled_at", nullable=False),+ "first_scheduled_at": DateTimeDatabaseField(name="first_scheduled_at", nullable=False),+ "started_at": DateTimeDatabaseField(name="started_at", nullable=True),+ "finished_at": DateTimeDatabaseField(name="finished_at", nullable=True),+ "duration_ms": IntegerDatabaseField(name="duration_ms", nullable=True),+ "error_kind": StringDatabaseField(name="error_kind", nullable=False),+ "error_message": StringDatabaseField(name="error_message", nullable=False),+ "event_uuid": StringDatabaseField(name="event_uuid", nullable=False),+ "distinct_id": StringDatabaseField(name="distinct_id", nullable=False),+ "person_id": StringDatabaseField(name="person_id", nullable=False),+ "version": IntegerDatabaseField(name="version", nullable=False),+ "is_deleted": BooleanDatabaseField(name="is_deleted", nullable=False),+}+++class HogInvocationResultsTable(Table):+ fields: dict[str, FieldOrTable] = HOG_INVOCATION_RESULTS_FIELDS++ def to_printed_clickhouse(self, context):+ return "hog_invocation_results"++ def to_printed_hogql(self):+ return "hog_invocation_results"diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.pyindex 9a0782b2543a..eb4fc7912a27 100644--- a/posthog/plugins/plugin_server_api.py+++ b/posthog/plugins/plugin_server_api.py@@ -158,5 +158,34 @@ def create_batch_hog_flow_job_invocation()+def rerun_hog_invocations(+ team_id: int,+ function_kind: str,+ function_id: str,+ payload: dict,+) -> requests.Response:+ """+ Trigger a rerun of past hog function / hog flow invocations.++ `payload` is one of:+ - {"invocation_ids": ["uuid", ...]} -> rerun these specific runs+ - {"filter": {"window_start": "...", "window_end": "...", "status": [...], ...}}++ The Node side (`nodejs/src/cdp/rerun`) reads the matching rows from+ `hog_invocation_results`, rehydrates the invocation from the stored+ `invocation_globals`, and re-enqueues onto cyclotron with `is_retry=1`.+ """+ logger.info(+ "Triggering rerun of hog invocations",+ function_kind=function_kind,+ function_id=function_id,+ )+ return internal_requests.post(+ CDP_API_URL + f"/api/projects/{team_id}/{function_kind}s/{function_id}/rerun",+ json=payload,+ headers=get_internal_api_headers(),+ )++def get_plugin_server_status() -> requests.Response:return internal_requests.get(CDP_API_URL + f"/_health")diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.pyindex 506e051a4a9f..893bde278c4e 100644--- a/products/cdp/backend/api/hog_function.py+++ b/products/cdp/backend/api/hog_function.py@@ -18,6 +18,7 @@ from rest_framework.serializers import BaseSerializerfrom posthog.api.app_metrics2 import AppMetricsMixinfrom posthog.api.forbid_destroy_model import ForbidDestroyModel+from posthog.api.hog_invocation_rerun import HogInvocationRerunRequestSerializer, HogInvocationRerunResponseSerializerfrom posthog.api.log_entries import LogEntryMixinfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer@@ -37,7 +38,7 @@ from posthog.helpers.impersonation import is_impersonatedfrom posthog.helpers.trigram_search import DESCRIPTION_FIELD, MAX_SEARCH_LENGTH, NAME_FIELD, apply_trigram_searchfrom posthog.models import Teamfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity-from posthog.plugins.plugin_server_api import create_hog_invocation_test+from posthog.plugins.plugin_server_api import create_hog_invocation_test, rerun_hog_invocationsfrom products.cdp.backend.api.hog_function_template import HogFunctionTemplateSerializerfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplate@@ -501,13 +502,25 @@ class HogFunctionViewSet():scope_object = "hog_function"scope_object_read_actions = ["list", "retrieve", "logs", "metrics", "metrics_totals"]- scope_object_write_actions = ["create", "update", "partial_update", "invocations", "rearrange"]+ scope_object_write_actions = ["create", "update", "partial_update", "invocations", "rearrange", "rerun"]queryset = HogFunction.objects.all()filter_backends = [DjangoFilterBackend]filterset_class = HogFunctionFilterSetlog_source = "hog_function"app_source = "hog_function"+ def dangerously_get_required_scopes(self, request, view) -> Optional[list[str]]:+ # Rerun re-executes stored invocations — it replays up to 30 days of+ # persisted event/person/group data through the current (possibly+ # reconfigured) function. A `hog_function:write`-only token could use+ # that to route historical data it can't otherwise read to a destination+ # it controls, so gate rerun on person:read + group:read on top of write+ # — the same data-read scopes the invocation-inspection paths require.+ # (`hog_function:read` would be a no-op since :write already satisfies it.)+ if self.action == "rerun":+ return ["hog_function:write", "person:read", "group:read"]+ return None+def get_serializer_class(self) -> type[BaseSerializer]:if self.action == "list":# Use full serializer (including inputs, mappings, etc.) when ?full=true@@ -640,6 +653,55 @@ class HogFunctionViewSet(return Response(res.json())+ @extend_schema(+ request=HogInvocationRerunRequestSerializer,+ responses={200: HogInvocationRerunResponseSerializer, 400: HogInvocationRerunResponseSerializer},+ )+ @action(detail=True, methods=["POST"])+ def rerun(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """+ Rerun past invocations of this hog function from their stored payloads.++ The CDP worker reads matching rows from the `hog_invocation_results`+ ClickHouse table, rehydrates the invocation from the stored+ `invocation_globals`, and re-enqueues onto cyclotron. Each rerun+ run reuses the original `invocation_id` with `is_retry=1` set on the+ new lifecycle row so the UI can surface that it was a rerun.++ For source-webhook functions the worker strips `request.headers` from+ the rehydrated globals before re-enqueuing (see the rerun paginator):+ those headers carry the inbound sender's credentials, and replaying+ them through a reconfigured function would let a write-access user+ exfiltrate stored secrets.++ Because rerun replays historical event/person/group data, it requires+ `person:read` and `group:read` on top of `hog_function:write`.+ """+ hog_function = self.get_object()++ serializer = HogInvocationRerunRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ # `serializer.data` runs `to_representation`, which converts the+ # `DateTimeField`s on `filter.window_start` / `filter.window_end` to+ # ISO-8601 strings — `requests.post(json=...)` can't serialize raw+ # `datetime` objects, so passing `validated_data` would 500 every+ # filter-mode rerun before the request even left Django.+ res = rerun_hog_invocations(+ team_id=self.team_id,+ function_kind="hog_function",+ function_id=str(hog_function.id),+ payload=serializer.data,+ )++ if res.status_code != 200:+ return Response(+ {"queued_count": 0, "skipped_count": 0, "detail": res.text},+ status=res.status_code,+ )++ return Response(res.json())+def perform_create(self, serializer):serializer.save()log_activity_from_viewset(diff --git a/products/cdp/frontend/generated/api.schemas.ts b/products/cdp/frontend/generated/api.schemas.tsindex 25ef970225fc..77c38cbf8e1c 100644--- a/products/cdp/frontend/generated/api.schemas.ts+++ b/products/cdp/frontend/generated/api.schemas.ts@@ -566,6 +566,74 @@ export interface AppMetricsTotalsResponseApi {totals: AppMetricsTotalsResponseApiTotals}+/**+ * * `running` - running+ * * `succeeded` - succeeded+ * * `failed` - failed+ */+export type HogInvocationRerunFilterStatusEnumApi =+ (typeof HogInvocationRerunFilterStatusEnumApi)[keyof typeof HogInvocationRerunFilterStatusEnumApi]++export const HogInvocationRerunFilterStatusEnumApi = {+ Running: 'running',+ Succeeded: 'succeeded',+ Failed: 'failed',+} as const++/**+ * Filter shape for the rerun endpoint. `window_start`/`window_end` are required.+ */+export interface HogInvocationRerunFilterApi {+ /** Inclusive lower bound on `scheduled_at` (UTC). */+ window_start: string+ /** Exclusive upper bound on `scheduled_at` (UTC). */+ window_end: string+ /** Restrict to invocations whose latest status is one of these. Defaults to ['failed']. */+ status?: HogInvocationRerunFilterStatusEnumApi[]+ /** Restrict to invocations whose error_kind matches one of these (e.g. 'http_5xx', 'timeout'). */+ error_kind?: string[]+ /**+ * Skip invocations that have already been attempted this many times or more.+ * @minimum 1+ * @maximum 255+ */+ max_attempts?: number+ /**+ * Maximum number of invocations to rerun in this request. Server-side cap is 10000.+ * @minimum 1+ * @maximum 10000+ */+ max_count?: number+ /**+ * Optional restriction to specific invocation IDs within the window. Capped at 10000 per request. Always combined with `window_start`/`window_end` so the ClickHouse query can be partition-pruned.+ * @maxItems 10000+ */+ invocation_ids?: string[]+}++/**+ * Rerun invocations of a hog function or hog flow from their stored payloads.+ */+export interface HogInvocationRerunRequestApi {+ /** Required. `window_start` / `window_end` pin the query to a small set of date partitions on the `hog_invocation_results` table. Optional `invocation_ids` restricts to specific invocations within that window. */+ filter: HogInvocationRerunFilterApi+}++/**+ * Response from the rerun endpoint. The endpoint only enqueues a wrapper+ * job onto the cyclotron `rerun` queue — the actual ClickHouse paging and+ * re-enqueue work happens asynchronously in the `cdp-rerun-worker` service.+ * Use `rerun_job_id` to look up progress on the wrapper job later.+ */+export interface HogInvocationRerunResponseApi {+ /** ID of the cyclotron wrapper job that will run the rerun. Use this to poll status. */+ rerun_job_id: string+ /** Always 0 — rerun runs asynchronously. Kept for response shape stability. */+ queued_count: number+ /** Always 0 — rerun runs asynchronously. Kept for response shape stability. */+ skipped_count: number+}+/*** Map of hog function UUIDs to their new execution_order values.*/diff --git a/products/cdp/frontend/generated/api.ts b/products/cdp/frontend/generated/api.tsindex d2942956791d..83afc3c8a1f4 100644--- a/products/cdp/frontend/generated/api.ts+++ b/products/cdp/frontend/generated/api.ts@@ -19,6 +19,8 @@ import type {HogFunctionsLogsRetrieveParams,HogFunctionsMetricsRetrieveParams,HogFunctionsMetricsTotalsRetrieveParams,+ HogInvocationRerunRequestApi,+ HogInvocationRerunResponseApi,PaginatedHogFunctionMinimalListApi,PaginatedHogFunctionTemplateListApi,PaginatedPluginLogEntryListApi,@@ -328,6 +330,42 @@ export const hogFunctionsMetricsTotalsRetrieve = async (})}+export const getHogFunctionsRerunCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/hog_functions/${id}/rerun/`+}++/**+ * Rerun past invocations of this hog function from their stored payloads.+ *+ * The CDP worker reads matching rows from the `hog_invocation_results`+ * ClickHouse table, rehydrates the invocation from the stored+ * `invocation_globals`, and re-enqueues onto cyclotron. Each rerun+ * run reuses the original `invocation_id` with `is_retry=1` set on the+ * new lifecycle row so the UI can surface that it was a rerun.+ *+ * For source-webhook functions the worker strips `request.headers` from+ * the rehydrated globals before re-enqueuing (see the rerun paginator):+ * those headers carry the inbound sender's credentials, and replaying+ * them through a reconfigured function would let a write-access user+ * exfiltrate stored secrets.+ *+ * Because rerun replays historical event/person/group data, it requires+ * `person:read` and `group:read` on top of `hog_function:write`.+ */+export const hogFunctionsRerunCreate = async (+ projectId: string,+ id: string,+ hogInvocationRerunRequestApi: HogInvocationRerunRequestApi,+ options?: RequestInit+): Promise<HogInvocationRerunResponseApi> => {+ return apiMutator<HogInvocationRerunResponseApi>(getHogFunctionsRerunCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(hogInvocationRerunRequestApi),+ })+}+export const getHogFunctionsIconRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/hog_functions/icon/`}diff --git a/products/cdp/frontend/generated/api.zod.ts b/products/cdp/frontend/generated/api.zod.tsindex bae6858f3318..85d56a51b0d3 100644--- a/products/cdp/frontend/generated/api.zod.ts+++ b/products/cdp/frontend/generated/api.zod.ts@@ -1416,6 +1416,81 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({invocation_id: zod.string().nullish().describe('Optional invocation ID for correlation.'),})+/**+ * Rerun past invocations of this hog function from their stored payloads.+ *+ * The CDP worker reads matching rows from the `hog_invocation_results`+ * ClickHouse table, rehydrates the invocation from the stored+ * `invocation_globals`, and re-enqueues onto cyclotron. Each rerun+ * run reuses the original `invocation_id` with `is_retry=1` set on the+ * new lifecycle row so the UI can surface that it was a rerun.+ *+ * For source-webhook functions the worker strips `request.headers` from+ * the rehydrated globals before re-enqueuing (see the rerun paginator):+ * those headers carry the inbound sender's credentials, and replaying+ * them through a reconfigured function would let a write-access user+ * exfiltrate stored secrets.+ *+ * Because rerun replays historical event/person/group data, it requires+ * `person:read` and `group:read` on top of `hog_function:write`.+ */+export const hogFunctionsRerunCreateBodyFilterOneMaxAttemptsMax = 255++export const hogFunctionsRerunCreateBodyFilterOneMaxCountMax = 10000++export const hogFunctionsRerunCreateBodyFilterOneInvocationIdsMax = 10000++export const HogFunctionsRerunCreateBody = /* @__PURE__ */ zod+ .object({+ filter: zod+ .object({+ window_start: zod.iso+ .datetime({ offset: true })+ .describe('Inclusive lower bound on `scheduled_at` (UTC).'),+ window_end: zod.iso+ .datetime({ offset: true })+ .describe('Exclusive upper bound on `scheduled_at` (UTC).'),+ status: zod+ .array(+ zod+ .enum(['running', 'succeeded', 'failed'])+ .describe('\* `running` - running\n\* `succeeded` - succeeded\n\* `failed` - failed')+ )+ .optional()+ .describe("Restrict to invocations whose latest status is one of these. Defaults to ['failed']."),+ error_kind: zod+ .array(zod.string())+ .optional()+ .describe(+ "Restrict to invocations whose error_kind matches one of these (e.g. 'http_5xx', 'timeout')."+ ),+ max_attempts: zod+ .number()+ .min(1)+ .max(hogFunctionsRerunCreateBodyFilterOneMaxAttemptsMax)+ .optional()+ .describe('Skip invocations that have already been attempted this many times or more.'),+ max_count: zod+ .number()+ .min(1)+ .max(hogFunctionsRerunCreateBodyFilterOneMaxCountMax)+ .optional()+ .describe('Maximum number of invocations to rerun in this request. Server-side cap is 10000.'),+ invocation_ids: zod+ .array(zod.string())+ .max(hogFunctionsRerunCreateBodyFilterOneInvocationIdsMax)+ .optional()+ .describe(+ 'Optional restriction to specific invocation IDs within the window. Capped at 10000 per request. Always combined with `window_start`\/`window_end` so the ClickHouse query can be partition-pruned.'+ ),+ })+ .describe('Filter shape for the rerun endpoint. `window_start`\/`window_end` are required.')+ .describe(+ 'Required. `window_start` \/ `window_end` pin the query to a small set of date partitions on the `hog_invocation_results` table. Optional `invocation_ids` restricts to specific invocations within that window.'+ ),+ })+ .describe('Rerun invocations of a hog function or hog flow from their stored payloads.')+/*** Update the execution order of multiple HogFunctions.*/diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 87e2cb4d9c47..f5b7b737df46 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -26,6 +26,7 @@ from posthog.schema import ProductKeyfrom posthog.api.app_metrics2 import AppMetricsMixin, fetch_app_metric_totals_by_sourcefrom posthog.api.documentation import _FallbackSerializer+from posthog.api.hog_invocation_rerun import HogInvocationRerunRequestSerializer, HogInvocationRerunResponseSerializerfrom posthog.api.hog_invocation_results import (HogInvocationResultDetailSerializer,HogInvocationResultSerializer,@@ -49,7 +50,11 @@ from posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.event_usage import EventSource, get_event_sourcefrom posthog.models import Teamfrom posthog.models.filters import Filter-from posthog.plugins.plugin_server_api import create_hog_flow_invocation_test, create_hog_flow_scheduled_invocation+from posthog.plugins.plugin_server_api import (+ create_hog_flow_invocation_test,+ create_hog_flow_scheduled_invocation,+ rerun_hog_invocations,+)from posthog.utils import relative_date_parse_with_delta_mappingfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplate@@ -1169,6 +1174,7 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie"invocations","schedule_detail","bulk_delete",+ "rerun","graph",]queryset = HogFlow.objects.all()@@ -1203,6 +1209,15 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie# running tests while editing is unaffected.if self.action == "invocations":return ["hog_flow:write", "group:read"]+ # Rerun re-executes stored invocations — it replays up to 30 days of+ # persisted event/person/group data through the current (possibly+ # reconfigured) workflow. A `hog_flow:write`-only token could use that to+ # route historical data it can't otherwise read to a destination it+ # controls, so gate rerun on person:read + group:read on top of write —+ # the same data-read scopes invocation inspection requires. (`hog_flow:read`+ # would be a no-op since :write already satisfies it.)+ if self.action == "rerun":+ return ["hog_flow:write", "person:read", "group:read"]return Nonedef get_serializer_class(self) -> type[BaseSerializer]:@@ -1240,6 +1255,48 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, viedef _is_mcp_request(request: Request) -> bool:return request.headers.get("x-posthog-client") == "mcp"+ @extend_schema(+ request=HogInvocationRerunRequestSerializer,+ responses={200: HogInvocationRerunResponseSerializer, 400: HogInvocationRerunResponseSerializer},+ )+ @action(detail=True, methods=["POST"])+ def rerun(self, request: Request, *args, **kwargs) -> Response:+ """+ Rerun past invocations of this hog flow from their stored payloads.++ Same shape and semantics as the hog function rerun endpoint —+ proxies through to the CDP worker, which reads matching rows from+ ClickHouse, rehydrates from `invocation_globals`, and re-enqueues+ onto cyclotron with `is_retry=1`.++ Because rerun replays historical event/person/group data, it requires+ `person:read` and `group:read` on top of `hog_flow:write`.+ """+ hog_flow = self.get_object()++ serializer = HogInvocationRerunRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ # `serializer.data` runs `to_representation`, which converts the+ # `DateTimeField`s on `filter.window_start` / `filter.window_end` to+ # ISO-8601 strings — `requests.post(json=...)` can't serialize raw+ # `datetime` objects, so passing `validated_data` would 500 every+ # filter-mode rerun before the request even left Django.+ res = rerun_hog_invocations(+ team_id=self.team_id,+ function_kind="hog_flow",+ function_id=str(hog_flow.id),+ payload=serializer.data,+ )++ if res.status_code != 200:+ return Response(+ {"queued_count": 0, "skipped_count": 0, "detail": res.text},+ status=res.status_code,+ )++ return Response(res.json())+def _emit_resource_edited(self, instance: HogFlow) -> None:# Realtime "edited elsewhere" signal so an open builder (or another tab) can refresh instead of# clobbering edits made via a different channel (UI/MCP/API). Fires for every channel; thediff --git a/products/workflows/frontend/Workflows/WorkflowInvocations.tsx b/products/workflows/frontend/Workflows/WorkflowInvocations.tsxnew file mode 100644index 000000000000..a26e9db33cd0--- /dev/null+++ b/products/workflows/frontend/Workflows/WorkflowInvocations.tsx@@ -0,0 +1,26 @@+import { useValues } from 'kea'++import { HogInvocations } from 'scenes/hog-functions/invocations/HogInvocations'++import { renderWorkflowLogMessage } from './logs/log-utils'+import { workflowLogic } from './workflowLogic'++/**+ * Workflow-side wrapper around the shared `HogInvocations` component,+ * scoped to `function_kind = 'hog_flow'`. The component does all the work —+ * this file exists so the workflow scene can wire its own tab without+ * leaking the cross-product import into every call site.+ *+ * Passes the workflow-aware log renderer so event/person/action tokens in the+ * per-run logs become links, matching the standalone Logs tab.+ */+export function WorkflowInvocations({ id }: { id: string }): JSX.Element | null {+ const { workflow } = useValues(workflowLogic)+ return (+ <HogInvocations+ id={id}+ functionKind="hog_flow"+ renderLogMessage={workflow ? (m) => renderWorkflowLogMessage(workflow, m) : undefined}+ />+ )+}diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsxindex 061db8adc232..8d8266e2257e 100644--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx@@ -9,7 +9,9 @@ import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'import { LastSavedIndicator } from 'lib/components/LastSavedIndicator'import { NotFound } from 'lib/components/NotFound'import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'+import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { SceneExport } from 'scenes/sceneTypes'@@ -21,6 +23,7 @@ import { ActivityScope } from '~/types'import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'import { Workflow } from './Workflow'+import { WorkflowInvocations } from './WorkflowInvocations'import { workflowLogic } from './workflowLogic'import { WorkflowLogs } from './WorkflowLogs'import { WorkflowMetrics } from './WorkflowMetrics'@@ -56,6 +59,8 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {const showSaving = useDebouncedValue(isAutoSavePending || workflowLoading, 1000)const isDraft = originalWorkflow?.status === 'draft'+ const runsV2Enabled = useFeatureFlag('HOG_INVOCATION_RESULTS_RUNS_TAB')+// Attach child logics to the scene logic so they persist across tab switchesuseAttachedLogic(batchJobsLogic, sceneLogic)useAttachedLogic(logic, sceneLogic)@@ -76,10 +81,26 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {},{- label: 'Invocations',+ // Once the new Invocations (beta) tab is on, the old log viewer becomes "Logs"+ // to match the hog function scene and avoid two "Invocations" tabs.+ label: runsV2Enabled ? 'Logs' : 'Invocations',key: 'logs',content: <WorkflowLogs id={workflowSceneProps.id!} />,},+ runsV2Enabled+ ? {+ label: (+ <div className="flex flex-row">+ <div>Invocations</div>+ <LemonTag className="ml-2 uppercase" type="warning">+ Beta+ </LemonTag>+ </div>+ ),+ key: 'invocations',+ content: <WorkflowInvocations id={workflowSceneProps.id!} />,+ }+ : null,{label: 'Metrics',key: 'metrics',diff --git a/products/workflows/frontend/Workflows/workflowSceneLogic.ts b/products/workflows/frontend/Workflows/workflowSceneLogic.tsindex dc3ea563fc4f..c3dcbe188ae1 100644--- a/products/workflows/frontend/Workflows/workflowSceneLogic.ts+++ b/products/workflows/frontend/Workflows/workflowSceneLogic.ts@@ -8,7 +8,7 @@ import { Breadcrumb } from '~/types'import type { workflowSceneLogicType } from './workflowSceneLogicType'-export const WorkflowTabs = ['workflow', 'logs', 'metrics', 'history'] as const+export const WorkflowTabs = ['workflow', 'logs', 'invocations', 'metrics', 'history'] as constexport type WorkflowTab = (typeof WorkflowTabs)[number]export interface WorkflowSceneLogicProps {diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 7e0af5da6a0a..b6e343a12e9e 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -726,6 +726,74 @@ export interface AppMetricsTotalsResponseApi {totals: AppMetricsTotalsResponseApiTotals}+/**+ * * `running` - running+ * * `succeeded` - succeeded+ * * `failed` - failed+ */+export type HogInvocationRerunFilterStatusEnumApi =+ (typeof HogInvocationRerunFilterStatusEnumApi)[keyof typeof HogInvocationRerunFilterStatusEnumApi]++export const HogInvocationRerunFilterStatusEnumApi = {+ Running: 'running',+ Succeeded: 'succeeded',+ Failed: 'failed',+} as const++/**+ * Filter shape for the rerun endpoint. `window_start`/`window_end` are required.+ */+export interface HogInvocationRerunFilterApi {+ /** Inclusive lower bound on `scheduled_at` (UTC). */+ window_start: string+ /** Exclusive upper bound on `scheduled_at` (UTC). */+ window_end: string+ /** Restrict to invocations whose latest status is one of these. Defaults to ['failed']. */+ status?: HogInvocationRerunFilterStatusEnumApi[]+ /** Restrict to invocations whose error_kind matches one of these (e.g. 'http_5xx', 'timeout'). */+ error_kind?: string[]+ /**+ * Skip invocations that have already been attempted this many times or more.+ * @minimum 1+ * @maximum 255+ */+ max_attempts?: number+ /**+ * Maximum number of invocations to rerun in this request. Server-side cap is 10000.+ * @minimum 1+ * @maximum 10000+ */+ max_count?: number+ /**+ * Optional restriction to specific invocation IDs within the window. Capped at 10000 per request. Always combined with `window_start`/`window_end` so the ClickHouse query can be partition-pruned.+ * @maxItems 10000+ */+ invocation_ids?: string[]+}++/**+ * Rerun invocations of a hog function or hog flow from their stored payloads.+ */+export interface HogInvocationRerunRequestApi {+ /** Required. `window_start` / `window_end` pin the query to a small set of date partitions on the `hog_invocation_results` table. Optional `invocation_ids` restricts to specific invocations within that window. */+ filter: HogInvocationRerunFilterApi+}++/**+ * Response from the rerun endpoint. The endpoint only enqueues a wrapper+ * job onto the cyclotron `rerun` queue — the actual ClickHouse paging and+ * re-enqueue work happens asynchronously in the `cdp-rerun-worker` service.+ * Use `rerun_job_id` to look up progress on the wrapper job later.+ */+export interface HogInvocationRerunResponseApi {+ /** ID of the cyclotron wrapper job that will run the rerun. Use this to poll status. */+ rerun_job_id: string+ /** Always 0 — rerun runs asynchronously. Kept for response shape stability. */+ queued_count: number+ /** Always 0 — rerun runs asynchronously. Kept for response shape stability. */+ skipped_count: number+}+export interface PatchedHogFlowScheduleApi {readonly id?: string/** iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour. */diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.tsindex 87fc2264ff8d..6214091f01ca 100644--- a/products/workflows/frontend/generated/api.ts+++ b/products/workflows/frontend/generated/api.ts@@ -26,6 +26,8 @@ import type {HogFlowsMetricsGlobalRetrieveParams,HogFlowsMetricsRetrieveParams,HogFlowsMetricsTotalsRetrieveParams,+ HogInvocationRerunRequestApi,+ HogInvocationRerunResponseApi,HogInvocationResultApi,HogInvocationResultDetailApi,PaginatedHogFlowMinimalListApi,@@ -528,6 +530,35 @@ export const hogFlowsMetricsTotalsRetrieve = async (})}+export const getHogFlowsRerunCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/hog_flows/${id}/rerun/`+}++/**+ * Rerun past invocations of this hog flow from their stored payloads.+ *+ * Same shape and semantics as the hog function rerun endpoint —+ * proxies through to the CDP worker, which reads matching rows from+ * ClickHouse, rehydrates from `invocation_globals`, and re-enqueues+ * onto cyclotron with `is_retry=1`.+ *+ * Because rerun replays historical event/person/group data, it requires+ * `person:read` and `group:read` on top of `hog_flow:write`.+ */+export const hogFlowsRerunCreate = async (+ projectId: string,+ id: string,+ hogInvocationRerunRequestApi: HogInvocationRerunRequestApi,+ options?: RequestInit+): Promise<HogInvocationRerunResponseApi> => {+ return apiMutator<HogInvocationRerunResponseApi>(getHogFlowsRerunCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(hogInvocationRerunRequestApi),+ })+}+export const getHogFlowsSchedulesListUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/hog_flows/${id}/schedules/`}diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex 278757eaeb98..3d716fe7f6b7 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -1892,6 +1892,74 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({),})+/**+ * Rerun past invocations of this hog flow from their stored payloads.+ *+ * Same shape and semantics as the hog function rerun endpoint —+ * proxies through to the CDP worker, which reads matching rows from+ * ClickHouse, rehydrates from `invocation_globals`, and re-enqueues+ * onto cyclotron with `is_retry=1`.+ *+ * Because rerun replays historical event/person/group data, it requires+ * `person:read` and `group:read` on top of `hog_flow:write`.+ */+export const hogFlowsRerunCreateBodyFilterOneMaxAttemptsMax = 255++export const hogFlowsRerunCreateBodyFilterOneMaxCountMax = 10000++export const hogFlowsRerunCreateBodyFilterOneInvocationIdsMax = 10000++export const HogFlowsRerunCreateBody = /* @__PURE__ */ zod+ .object({+ filter: zod+ .object({+ window_start: zod.iso+ .datetime({ offset: true })+ .describe('Inclusive lower bound on `scheduled_at` (UTC).'),+ window_end: zod.iso+ .datetime({ offset: true })+ .describe('Exclusive upper bound on `scheduled_at` (UTC).'),+ status: zod+ .array(+ zod+ .enum(['running', 'succeeded', 'failed'])+ .describe('\* `running` - running\n\* `succeeded` - succeeded\n\* `failed` - failed')+ )+ .optional()+ .describe("Restrict to invocations whose latest status is one of these. Defaults to ['failed']."),+ error_kind: zod+ .array(zod.string())+ .optional()+ .describe(+ "Restrict to invocations whose error_kind matches one of these (e.g. 'http_5xx', 'timeout')."+ ),+ max_attempts: zod+ .number()+ .min(1)+ .max(hogFlowsRerunCreateBodyFilterOneMaxAttemptsMax)+ .optional()+ .describe('Skip invocations that have already been attempted this many times or more.'),+ max_count: zod+ .number()+ .min(1)+ .max(hogFlowsRerunCreateBodyFilterOneMaxCountMax)+ .optional()+ .describe('Maximum number of invocations to rerun in this request. Server-side cap is 10000.'),+ invocation_ids: zod+ .array(zod.string())+ .max(hogFlowsRerunCreateBodyFilterOneInvocationIdsMax)+ .optional()+ .describe(+ 'Optional restriction to specific invocation IDs within the window. Capped at 10000 per request. Always combined with `window_start`\/`window_end` so the ClickHouse query can be partition-pruned.'+ ),+ })+ .describe('Filter shape for the rerun endpoint. `window_start`\/`window_end` are required.')+ .describe(+ 'Required. `window_start` \/ `window_end` pin the query to a small set of date partitions on the `hog_invocation_results` table. Optional `invocation_ids` restricts to specific invocations within that window.'+ ),+ })+ .describe('Rerun invocations of a hog function or hog flow from their stored payloads.')+export const hogFlowsSchedulesCreateBodyTimezoneMax = 64export const HogFlowsSchedulesCreateBody = /* @__PURE__ */ zod.object({diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex 3eddc83cb590..deb254391bfe 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -57,6 +57,9 @@ tools:hog-flows-partial-update:operation: hog_flows_partial_updateenabled: false+ hog-flows-rerun-create:+ operation: hog_flows_rerun_create+ enabled: falsehog-flows-schedules-create:operation: hog_flows_schedules_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 69ce8fcbbe69..6ebfc251e94d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -25261,6 +25261,74 @@ export namespace Schemas {readonly search_match_type: SearchMatchTypeEnum | null;}+ /**+ * * `running` - running+ * * `succeeded` - succeeded+ * * `failed` - failed+ */+ export type HogInvocationRerunFilterStatusEnum = typeof HogInvocationRerunFilterStatusEnum[keyof typeof HogInvocationRerunFilterStatusEnum];+++ export const HogInvocationRerunFilterStatusEnum = {+ Running: 'running',+ Succeeded: 'succeeded',+ Failed: 'failed',+ } as const;++ /**+ * Filter shape for the rerun endpoint. `window_start`/`window_end` are required.+ */+ export interface HogInvocationRerunFilter {+ /** Inclusive lower bound on `scheduled_at` (UTC). */+ window_start: string;+ /** Exclusive upper bound on `scheduled_at` (UTC). */+ window_end: string;+ /** Restrict to invocations whose latest status is one of these. Defaults to ['failed']. */+ status?: HogInvocationRerunFilterStatusEnum[];+ /** Restrict to invocations whose error_kind matches one of these (e.g. 'http_5xx', 'timeout'). */+ error_kind?: string[];+ /**+ * Skip invocations that have already been attempted this many times or more.+ * @minimum 1+ * @maximum 255+ */+ max_attempts?: number;+ /**+ * Maximum number of invocations to rerun in this request. Server-side cap is 10000.+ * @minimum 1+ * @maximum 10000+ */+ max_count?: number;+ /**+ * Optional restriction to specific invocation IDs within the window. Capped at 10000 per request. Always combined with `window_start`/`window_end` so the ClickHouse query can be partition-pruned.+ * @maxItems 10000+ */+ invocation_ids?: string[];+ }++ /**+ * Rerun invocations of a hog function or hog flow from their stored payloads.+ */+ export interface HogInvocationRerunRequest {+ /** Required. `window_start` / `window_end` pin the query to a small set of date partitions on the `hog_invocation_results` table. Optional `invocation_ids` restricts to specific invocations within that window. */+ filter: HogInvocationRerunFilter;+ }++ /**+ * Response from the rerun endpoint. The endpoint only enqueues a wrapper+ * job onto the cyclotron `rerun` queue — the actual ClickHouse paging and+ * re-enqueue work happens asynchronously in the `cdp-rerun-worker` service.+ * Use `rerun_job_id` to look up progress on the wrapper job later.+ */+ export interface HogInvocationRerunResponse {+ /** ID of the cyclotron wrapper job that will run the rerun. Use this to poll status. */+ rerun_job_id: string;+ /** Always 0 — rerun runs asynchronously. Kept for response shape stability. */+ queued_count: number;+ /** Always 0 — rerun runs asynchronously. Kept for response shape stability. */+ skipped_count: number;+ }+export interface HogInvocationResult {invocation_id: string;status: string;