: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(error-tracking): add pagerduty to error tracking alerts (#107525)
Meikel Ratzdf51d3bd8a9e
diff --git a/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts b/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.tsindex faf308581a45..8d9545f64c77 100644--- a/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts+++ b/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts@@ -703,7 +703,10 @@ export const alertWizardLogic = kea<alertWizardLogicType>([(s) =>s.required &&!prefilledKeys.has(s.key) &&- (s.type === 'integration' || s.type === 'integration_field' || s.type === 'string')+ (s.type === 'integration' ||+ s.type === 'integration_field' ||+ s.type === 'string' ||+ s.type === 'choice'))},],diff --git a/frontend/src/lib/components/Alerting/AlertWizard/steps/ConfigureStep.tsx b/frontend/src/lib/components/Alerting/AlertWizard/steps/ConfigureStep.tsxindex f2d844c56d72..04c300fd49a9 100644--- a/frontend/src/lib/components/Alerting/AlertWizard/steps/ConfigureStep.tsx+++ b/frontend/src/lib/components/Alerting/AlertWizard/steps/ConfigureStep.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { LemonButton, LemonInput } from '@posthog/lemon-ui'+import { LemonButton, LemonInput, LemonSelect } from '@posthog/lemon-ui'import { CyclotronJobInputIntegration } from 'lib/components/CyclotronJob/integrations/CyclotronJobInputIntegration'import { CyclotronJobInputIntegrationField } from 'lib/components/CyclotronJob/integrations/CyclotronJobInputIntegrationField'@@ -100,5 +100,26 @@ function SchemaInput({)}- return <LemonInput value={value ?? ''} onChange={onChange} placeholder={schema.description || schema.label || ''} />+ // Autocapture records copied text, so a credential typed here would otherwise reach analytics.+ // The standard destination editor guards its inputs the same way.+ if (schema.type === 'choice') {+ return (+ <LemonSelect+ fullWidth+ className="ph-no-capture"+ options={(schema.choices ?? []).map((choice) => ({ value: choice.value, label: choice.label }))}+ value={value ?? schema.default}+ onChange={onChange}+ />+ )+ }++ return (+ <LemonInput+ className="ph-no-capture"+ value={value ?? ''}+ onChange={onChange}+ placeholder={schema.description || schema.label || ''}+ />+ )}diff --git a/frontend/src/scenes/health-alerts/HealthAlertsEntryPoint.tsx b/frontend/src/scenes/health-alerts/HealthAlertsEntryPoint.tsxindex aa030b85851e..24970eaf70e8 100644--- a/frontend/src/scenes/health-alerts/HealthAlertsEntryPoint.tsx+++ b/frontend/src/scenes/health-alerts/HealthAlertsEntryPoint.tsx@@ -24,7 +24,7 @@ import {HEALTH_ALERT_TRIGGERS,} from './healthAlertsWizardConfig'-const HOG_FUNCTION_FILTER_LIST = HEALTH_ALERT_SUB_TEMPLATE_IDS.map(getFiltersFromSubTemplateId).filter(+const HOG_FUNCTION_FILTER_LIST = HEALTH_ALERT_SUB_TEMPLATE_IDS.map((id) => getFiltersFromSubTemplateId(id)).filter((f) => !!f) as CyclotronJobFiltersType[]diff --git a/frontend/src/scenes/hog-functions/list/LinkedHogFunctions.tsx b/frontend/src/scenes/hog-functions/list/LinkedHogFunctions.tsxindex 9e61e7ba7f59..615d721f81b8 100644--- a/frontend/src/scenes/hog-functions/list/LinkedHogFunctions.tsx+++ b/frontend/src/scenes/hog-functions/list/LinkedHogFunctions.tsx@@ -2,7 +2,12 @@ import { useMemo, useState } from 'react'import { LemonButton } from '@posthog/lemon-ui'-import { CyclotronJobFiltersType, HogFunctionSubTemplateIdType, HogFunctionTypeType } from '~/types'+import {+ CyclotronJobFiltersType,+ HogFunctionSubTemplateIdType,+ HogFunctionSubTemplateType,+ HogFunctionTypeType,+} from '~/types'import { HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES } from '../sub-templates/sub-templates'import { HogFunctionList } from './HogFunctionsList'@@ -18,11 +23,15 @@ export type LinkedHogFunctionsProps = {queryParams?: Record<string, string>}+// A sub-template can widen the filters its trigger shares with the other destinations. A PagerDuty+// alert also runs on the resolved event, so the incident it opened closes again. Its own filters+// therefore win over the common ones, which carry the trigger event alone.export const getFiltersFromSubTemplateId = (- subTemplateId: HogFunctionSubTemplateIdType+ subTemplateId: HogFunctionSubTemplateIdType,+ subTemplate?: HogFunctionSubTemplateType | null): CyclotronJobFiltersType | undefined => {const commonProperties = HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES[subTemplateId]- return commonProperties.filters ?? undefined+ return subTemplate?.filters ?? commonProperties.filters ?? undefined}export function LinkedHogFunctions({@@ -58,7 +67,7 @@ export function LinkedHogFunctions({const hogFunctionFilterList =forceFilterGroups ??- (subTemplateIds?.map(getFiltersFromSubTemplateId).filter((filters) => !!filters) as+ (subTemplateIds?.map((id) => getFiltersFromSubTemplateId(id)).filter((filters) => !!filters) as| CyclotronJobFiltersType[]| undefined)diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.test.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.test.tsindex c227f9c21b4c..d65e57887b98 100644--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.test.ts+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.test.ts@@ -30,6 +30,30 @@ describe('sub-templates', () => {expect(eventToHogFunctionContextId(event)).toBe(expected)})+ it.each([+ ['error-tracking-issue-created', '$error_tracking_issue_created'],+ ['error-tracking-issue-reopened', '$error_tracking_issue_reopened'],+ ['error-tracking-issue-spiking', '$error_tracking_issue_spiking'],+ ] as const)('pairs the %s PagerDuty trigger with issue resolution', (subTemplateId, triggerEvent) => {+ const pagerDutyTemplate = HOG_FUNCTION_SUB_TEMPLATES[subTemplateId].find(+ (template) => template.template_id === 'template-pagerduty'+ )++ expect(pagerDutyTemplate?.filters?.events).toEqual([+ { id: triggerEvent, type: 'events' },+ { id: '$error_tracking_issue_resolved', type: 'events' },+ ])+ expect(pagerDutyTemplate?.inputs).toMatchObject({+ event_action: {+ value: "{event.event == '$error_tracking_issue_resolved' ? 'resolve' : 'trigger'}",+ },+ dedup_key: { value: 'posthog-error-tracking-issue-{event.distinct_id}' },+ severity: {+ value: "{event.properties.severity == 'critical' ? 'critical' : event.properties.severity == 'high' ? 'error' : event.properties.severity == 'medium' ? 'warning' : event.properties.severity == 'low' ? 'info' : ''}",+ },+ })+ })+// A placeholder the sample event leaves empty renders an empty Slack block. Slack then rejects// the whole test message.it.each([diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.tsindex d3465f3b4d5c..e515f0418ef9 100644--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts@@ -20,6 +20,47 @@ import {export const errorTrackingIssueLinkHogTemplate = (medium: string): string =>`{project.url}/error-tracking/fingerprint/{replaceAll(replaceAll(encodeURLComponent(event.properties.fingerprint), '(', '%28'), ')', '%29')}?timestamp={event.properties.exception_timestamp}&utm_source=alert&utm_campaign=error_tracking_alert&utm_medium=${medium}`+// PagerDuty has no high, medium or low severity, so the issue severity maps onto its scale.+// The template sends error for an issue without a severity.+const ERROR_TRACKING_PAGERDUTY_SEVERITY =+ "{event.properties.severity == 'critical' ? 'critical' : event.properties.severity == 'high' ? 'error' : event.properties.severity == 'medium' ? 'warning' : event.properties.severity == 'low' ? 'info' : ''}"++// Every PagerDuty alert also runs on the resolved event, so resolving the issue resolves the incident+// that the alert opened. One dedup key per issue joins the two events.+const ERROR_TRACKING_ISSUE_RESOLVED_EVENT = '$error_tracking_issue_resolved'++const errorTrackingPagerDutyFilters = (triggerEvent: string): HogFunctionSubTemplateType['filters'] => ({+ source: 'internal-events',+ events: [+ { id: triggerEvent, type: 'events' },+ { id: ERROR_TRACKING_ISSUE_RESOLVED_EVENT, type: 'events' },+ ],+})++const errorTrackingPagerDutyInputs = (+ summary: string,+ extraDetails: Record<string, string> = {}+): HogFunctionSubTemplateType['inputs'] => ({+ event_action: { value: `{event.event == '${ERROR_TRACKING_ISSUE_RESOLVED_EVENT}' ? 'resolve' : 'trigger'}` },+ dedup_key: { value: 'posthog-error-tracking-issue-{event.distinct_id}' },+ summary: { value: summary },+ source: { value: '{project.name}' },+ severity: { value: ERROR_TRACKING_PAGERDUTY_SEVERITY },+ component: { value: 'error tracking' },+ custom_details: {+ value: {+ description: '{substring(event.properties.description, 1, 500)}',+ status: '{event.properties.status}',+ first_seen: '{event.properties.first_seen}',+ severity: '{event.properties.severity}',+ ...extraDetails,+ },+ },+ links: {+ value: [{ href: errorTrackingIssueLinkHogTemplate('pagerduty'), text: 'View issue in PostHog' }],+ },+})+// In single-exec mode $mcp_tool_name is always the 'exec' dispatcher; the inner tool the agent// actually invoked rides on $mcp_exec_tool_call_name. Rejected calls only carry the target.const MCP_EFFECTIVE_TOOL_EXPR = `(() -> {@@ -1233,6 +1274,15 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, Ho},},},+ {+ ...HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES['error-tracking-issue-created'],+ template_id: 'template-pagerduty',+ name: 'PagerDuty incident on issue created',+ description:+ 'Triggers a PagerDuty incident when an issue is created and resolves it when the issue is resolved',+ filters: errorTrackingPagerDutyFilters('$error_tracking_issue_created'),+ inputs: errorTrackingPagerDutyInputs('🔴 New issue: {event.properties.name}'),+ },],'error-tracking-issue-reopened': [{@@ -1303,6 +1353,15 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, Ho},},},+ {+ ...HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES['error-tracking-issue-reopened'],+ template_id: 'template-pagerduty',+ name: 'PagerDuty incident on issue reopened',+ description:+ 'Triggers a PagerDuty incident when an issue is reopened and resolves it when the issue is resolved',+ filters: errorTrackingPagerDutyFilters('$error_tracking_issue_reopened'),+ inputs: errorTrackingPagerDutyInputs('🔄 Issue reopened: {event.properties.name}'),+ },],'error-tracking-issue-spiking': [{@@ -1387,6 +1446,17 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, Ho},},},+ {+ ...HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES['error-tracking-issue-spiking'],+ template_id: 'template-pagerduty',+ name: 'PagerDuty incident on issue spiking',+ description:+ 'Triggers a PagerDuty incident when an issue is spiking and resolves it when the issue is resolved',+ filters: errorTrackingPagerDutyFilters('$error_tracking_issue_spiking'),+ inputs: errorTrackingPagerDutyInputs('📈 Issue spiking: {event.properties.name}', {+ exceptions_in_last_5_minutes: '{event.properties.current_bucket_value}',+ }),+ },],'experiment-significant': [{diff --git a/products/cdp/backend/test/test_validation.py b/products/cdp/backend/test/test_validation.pyindex fc945aea3cc9..84a8aa24893c 100644--- a/products/cdp/backend/test/test_validation.py+++ b/products/cdp/backend/test/test_validation.py@@ -1470,6 +1470,32 @@ class TestTaskInputTypeValidation(SimpleTestCase):validate_inputs(schema, inputs)+class TestChoiceInputTemplating(SimpleTestCase):+ CHOICE_SCHEMA = [+ {+ "key": "event_action",+ "type": "choice",+ "label": "Event action",+ "choices": [+ {"label": "Trigger", "value": "trigger"},+ {"label": "Resolve", "value": "resolve"},+ ],+ "required": True,+ }+ ]++ @parameterized.expand(+ [+ ("declared_choice", "trigger", False),+ ("templated_choice", "{event.event == 'x' ? 'resolve' : 'trigger'}", True),+ ]+ )+ def test_only_a_value_outside_the_declared_choices_is_compiled(self, _name, value, expect_bytecode):+ validated = validate_inputs(self.CHOICE_SCHEMA, {"event_action": {"value": value}})++ assert ("bytecode" in validated["event_action"]) is expect_bytecode++class TestReservedFunctionsUsed(SimpleTestCase):# The worker's async function registry is global, so the save-time check is the only thing# that stops user-authored hog from reaching a handler only PostHog's machinery should call.diff --git a/products/cdp/backend/validation.py b/products/cdp/backend/validation.pyindex 319daa526f91..4cf886b96fff 100644--- a/products/cdp/backend/validation.py+++ b/products/cdp/backend/validation.py@@ -733,6 +733,19 @@ class HogFunctionTemplating(models.TextChoices):LIQUID = "liquid", "liquid"+def _is_templated_choice(schema: dict, value: Any) -> bool:+ """A choice value that is not one of the declared choices is a Hog template, not a selection.++ A sub-template can prefill a choice input with an expression, for example the PagerDuty+ `event_action` that sends `resolve` on the issue-resolved event and `trigger` otherwise. The+ destination then rejects the uncompiled text, so the expression has to become bytecode. A value+ the user picked from the dropdown is left alone, so it keeps compiling to nothing.+ """+ if not isinstance(value, str):+ return False+ return value not in {choice.get("value") for choice in schema.get("choices") or []}++class InputsItemSerializer(serializers.Serializer):value = AnyInputField(required=False)templating = serializers.ChoiceField(choices=HogFunctionTemplating.choices, required=False)@@ -899,17 +912,22 @@ class InputsItemSerializer(serializers.Serializer):passelse:# If we have a value and hog templating is enabled, we need to transpile the value- value_is_transpiled = item_type in [- "string",- "boolean",- "dictionary",- "json",- "email",- "native_email",- "posthog_ticket_tags",- "customer_analytics_account_properties",- "customer_analytics_account_relationships",- ] or (item_type == "boolean" and isinstance(value, str))+ value_is_transpiled = (+ item_type+ in [+ "string",+ "boolean",+ "dictionary",+ "json",+ "email",+ "native_email",+ "posthog_ticket_tags",+ "customer_analytics_account_properties",+ "customer_analytics_account_relationships",+ ]+ or (item_type == "boolean" and isinstance(value, str))+ or (item_type == "choice" and _is_templated_choice(schema, value))+ )if value_is_transpiled:if item_type in ("email", "native_email") and isinstance(value, dict):# We want to exclude the "design" propertydiff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/alerting/ErrorTrackingAlerting.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/alerting/ErrorTrackingAlerting.tsxindex abab56bd1c24..2b27da05823b 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/alerting/ErrorTrackingAlerting.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/alerting/ErrorTrackingAlerting.tsx@@ -21,7 +21,7 @@ import {ERROR_TRACKING_TRIGGERS,} from './alertWizardConfig'-const HOG_FUNCTION_FILTER_LIST = ERROR_TRACKING_SUB_TEMPLATE_IDS.map(getFiltersFromSubTemplateId).filter(+const HOG_FUNCTION_FILTER_LIST = ERROR_TRACKING_SUB_TEMPLATE_IDS.map((id) => getFiltersFromSubTemplateId(id)).filter((f) => !!f) as CyclotronJobFiltersType[]@@ -68,7 +68,9 @@ function ErrorTrackingAlertingInner(): JSX.Element {<HogFunctionTemplateListtype="destination"subTemplateIds={subTemplateIds}- getConfigurationOverrides={(id) => (id ? { filters: getFiltersFromSubTemplateId(id) } : undefined)}+ getConfigurationOverrides={(id, subTemplate) =>+ id ? { filters: getFiltersFromSubTemplateId(id, subTemplate) } : undefined+ }extraControls={<LemonButtontype="secondary"diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/alerting/alertWizardConfig.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/alerting/alertWizardConfig.tsindex eff6231ac069..f70bebf0de38 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/alerting/alertWizardConfig.ts+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/alerting/alertWizardConfig.ts@@ -69,4 +69,11 @@ export const ERROR_TRACKING_DESTINATIONS: WizardDestination[] = [icon: '/static/services/linear.png',templateId: 'template-linear',},+ {+ key: 'pagerduty',+ name: 'PagerDuty',+ description: 'Page the on-call responder',+ icon: '/static/services/pagerduty.png',+ templateId: 'template-pagerduty',+ },]diff --git a/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.ts b/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.tsindex 5b85fa44886b..53efb42cca43 100644--- a/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.ts+++ b/products/mcp_analytics/frontend/notifications/mcpAnalyticsNotificationsLogic.ts@@ -15,7 +15,7 @@ const MCP_NOTIFICATION_LIST_LIMIT = 500const MCP_NOTIFICATION_SUB_TEMPLATE_IDS: HogFunctionSubTemplateIdType[] = ['mcp-tool-error']function getMCPNotificationFilterGroups(): CyclotronJobFiltersType[] {- return MCP_NOTIFICATION_SUB_TEMPLATE_IDS.map(getFiltersFromSubTemplateId).filter(+ return MCP_NOTIFICATION_SUB_TEMPLATE_IDS.map((id) => getFiltersFromSubTemplateId(id)).filter((filters): filters is CyclotronJobFiltersType => !!filters)}diff --git a/products/product_analytics/frontend/notifications/productAnalyticsNotificationsLogic.ts b/products/product_analytics/frontend/notifications/productAnalyticsNotificationsLogic.tsindex 2f5f73ff0f20..775f1ae8c5ee 100644--- a/products/product_analytics/frontend/notifications/productAnalyticsNotificationsLogic.ts+++ b/products/product_analytics/frontend/notifications/productAnalyticsNotificationsLogic.ts@@ -15,7 +15,7 @@ const PA_NOTIFICATION_LIST_LIMIT = 500const PA_NOTIFICATION_SUB_TEMPLATE_IDS: HogFunctionSubTemplateIdType[] = ['pa-rageclick']function getPANotificationFilterGroups(): CyclotronJobFiltersType[] {- return PA_NOTIFICATION_SUB_TEMPLATE_IDS.map(getFiltersFromSubTemplateId).filter(+ return PA_NOTIFICATION_SUB_TEMPLATE_IDS.map((id) => getFiltersFromSubTemplateId(id)).filter((filters): filters is CyclotronJobFiltersType => !!filters)}