Skip to content

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

chore(cdp): remove the destinations incident replay banner (#108183)

Harley Alexander6fb4b34a8620
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5bb028002596..4f1082b2bf2c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9746,10 +9746,6 @@ snapshots:
hash: v1.k794b7964.80ed280a18ac82339016e10800dd1ccbeaff542a392e26996c31590a5a745e8d.hBH3ORNIgQtdMNE08Hbdt7zaAyUWBD8rhYJmdVqOEo4
scenes-app-data-pipelines-destinations--realtime--light:
hash: v1.k794b7964.90a104b79843b4b06635df7d85ccd0549df8f0b9a4971afea09f374c05bcd010.E9MSjaXn9JMVTj-quN955urarkj2H7a3oVXuHooUd50
- scenes-app-data-pipelines-destinations-incident-replay-banner--default--dark:
- hash: v1.k794b7964.180cab2c6184f778ee72521bfd3776004d62c8fa7d822ae91a7af06d1ab12111.LmUCiAt2EBpkwhT4s3chjsCdq4JD3V_b2HeDkKSnifw
- scenes-app-data-pipelines-destinations-incident-replay-banner--default--light:
- hash: v1.k794b7964.68aae054d71cc2b3f9fa5cf6e2f341f23bbff3057a67d8aa1491c057b127050e.ZzeUlB7VWX3jhleoby_01IQMZePDlv9netuwDg7nnY8
scenes-app-data-pipelines-event-filtering--add-condition-and-test-case--dark:
hash: v1.k794b7964.054b485fa44909bda3f635ba9d134cea4dfa7e60bbc65206ba752f23b7729c42._2cxQzZ_XmaTvoI9Z7hIKh5kpuDY5rxQG0-1RNRyDgE
scenes-app-data-pipelines-event-filtering--add-condition-and-test-case--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 6f770b3f9aee..97c26a850553 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -321,7 +321,6 @@ export const FEATURE_FLAGS = {
DATA_WAREHOUSE_CUSTOM_SOURCE_AI_BUILDER: 'dwh-custom-source-ai-builder', // owner: #team-warehouse-sources
DATA_WAREHOUSE_CUSTOM_SOURCE_OAUTH2: 'dwh-custom-source-oauth2', // owner: #team-warehouse-sources
DATA_WAREHOUSE_SCENE: 'data-warehouse-scene', // owner: #team-data-modeling
- DESTINATIONS_INCIDENT_REPLAY: 'destinations-incident-replay', // owner: #team-workflows
DISCUSSIONS_SLACK_SYNC: 'discussions-slack-sync', // owner: #team-platform-features
DROP_PERSON_LIST_ORDER_BY: 'drop-person-list-order-by', // owner: @arthurdedeus #team-customer-analytics
DWH_POSTGRES_CDC: 'dwh-postgres-cdc', // owner: #team-warehouse-sources
diff --git a/frontend/src/scenes/data-pipelines/DestinationsScene.stories.tsx b/frontend/src/scenes/data-pipelines/DestinationsScene.stories.tsx
index bc1463fbb0a7..a8b4581c2f93 100644
--- a/frontend/src/scenes/data-pipelines/DestinationsScene.stories.tsx
+++ b/frontend/src/scenes/data-pipelines/DestinationsScene.stories.tsx
@@ -59,7 +59,6 @@ const meta: Meta = {
new URL(request.url).searchParams.get('type') === 'internal_destination'
? NOTIFICATIONS
: hogFunctionDestinations,
- '/api/projects/:team_id/hog_functions/masked_secrets/': [],
'/api/projects/:team_id/batch_exports/': batchExports,
'/api/environments/:team_id/batch_exports/': batchExports,
'/api/projects/:team_id/pipeline_destination_configs/': EMPTY_PAGE,
diff --git a/frontend/src/scenes/data-pipelines/DestinationsScene.tsx b/frontend/src/scenes/data-pipelines/DestinationsScene.tsx
index eafd8aecef31..3b7e3498320b 100644
--- a/frontend/src/scenes/data-pipelines/DestinationsScene.tsx
+++ b/frontend/src/scenes/data-pipelines/DestinationsScene.tsx
@@ -15,7 +15,6 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
import { ActivityScope } from '~/types'
-import { DestinationsIncidentReplayBanner } from 'products/cdp/frontend/DestinationsIncidentReplayBanner'
import { destinationsEmptyState } from 'products/cdp/frontend/emptyState/destinationsEmptyState'
import { DataPipelinesHogFunctions } from './DataPipelinesHogFunctions'
@@ -96,7 +95,6 @@ export function DestinationsScene(): JSX.Element {
}}
actions={action}
/>
- <DestinationsIncidentReplayBanner />
<LemonTabs activeKey={activeTab} onChange={setActiveTab} tabs={TABS} sceneInset />
</SceneContent>
)
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5466e5172863..64c909e59417 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2850,16 +2850,10 @@ importers:
kea-loaders:
specifier: 'catalog:'
version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
- kea-subscriptions:
- specifier: 'catalog:'
- version: 3.0.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
react:
specifier: 18.3.1
version: 18.3.1
devDependencies:
- '@storybook/react':
- specifier: 'catalog:'
'@testing-library/react':
specifier: ^14.3.1
diff --git a/products/cdp/frontend/DestinationsIncidentReplayBanner.stories.tsx b/products/cdp/frontend/DestinationsIncidentReplayBanner.stories.tsx
deleted file mode 100644
index 8712ed2ec072..000000000000
--- a/products/cdp/frontend/DestinationsIncidentReplayBanner.stories.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { Meta, StoryObj } from '@storybook/react'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-import { App } from 'scenes/App'
-import { urls } from 'scenes/urls'
-
-import { mswDecorator } from '~/mocks/browser'
-
-const NEEDS_CREDENTIALS_ID = '0196b144-1f82-0000-0d0d-a01de54d674d'
-const REPLAYABLE_ID = '0196b144-1f82-0000-0d0d-a01de54d6750'
-
-const hogFunction = (id: string, name: string): Record<string, unknown> => ({
- id,
- name,
- type: 'destination',
- enabled: true,
- inputs_schema: [{ key: 'api_key', type: 'string', label: 'API key', secret: true }],
- inputs: {},
- filters: {},
- icon_url: null,
- created_at: '2026-08-01T00:00:00Z',
- updated_at: '2026-08-18T14:00:00Z',
-})
-
-const meta: Meta = {
- component: App,
- title: 'Scenes-App/Data pipelines/Destinations incident replay banner',
- parameters: {
- layout: 'fullscreen',
- viewMode: 'story',
- pageUrl: urls.destinations(),
- mockDate: '2026-08-21',
- featureFlags: [FEATURE_FLAGS.DESTINATIONS_INCIDENT_REPLAY],
- },
- decorators: [
- mswDecorator({
- get: {
- '/api/projects/:team_id/hog_functions/masked_secrets/': [
- {
- id: NEEDS_CREDENTIALS_ID,
- name: 'Customer.io',
- type: 'destination',
- enabled: true,
- input_keys: ['api_key'],
- draft_input_keys: [],
- },
- ],
- [`/api/projects/:team_id/hog_functions/${NEEDS_CREDENTIALS_ID}/`]: hogFunction(
- NEEDS_CREDENTIALS_ID,
- 'Customer.io'
- ),
- [`/api/projects/:team_id/hog_functions/${REPLAYABLE_ID}/`]: hogFunction(REPLAYABLE_ID, 'HubSpot'),
- '/api/projects/:team_id/hog_functions/': {
- count: 2,
- results: [hogFunction(NEEDS_CREDENTIALS_ID, 'Customer.io'), hogFunction(REPLAYABLE_ID, 'HubSpot')],
- next: null,
- },
- },
- post: {
- '/api/environments/:team_id/query/:query_kind/': {
- results: [
- [REPLAYABLE_ID, 12480],
- [NEEDS_CREDENTIALS_ID, 3106],
- ],
- },
- },
- }),
- ],
-}
-export default meta
-
-type Story = StoryObj<{}>
-
-// One destination still storing the mask and one already fixed, which is what the banner has to
-// tell apart: the first can only be sent to its configuration, the second can be replayed.
-export const Default: Story = {}
diff --git a/products/cdp/frontend/DestinationsIncidentReplayBanner.tsx b/products/cdp/frontend/DestinationsIncidentReplayBanner.tsx
deleted file mode 100644
index 319645639ff4..000000000000
--- a/products/cdp/frontend/DestinationsIncidentReplayBanner.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { LemonBanner, LemonButton, LemonDialog } from '@posthog/lemon-ui'
-
-import { humanFriendlyNumber } from 'lib/utils/numbers'
-import { isRerunnableHogFunctionType } from 'scenes/hog-functions/invocations/hogInvocationsLogic'
-import { urls } from 'scenes/urls'
-
-import { type AffectedDestination, destinationsIncidentReplayLogic } from './destinationsIncidentReplayLogic'
-
-// Mirrors the server-side HOG_INVOCATION_RERUN_MAX_COUNT default: one replay request queues at
-// most this many invocations, so a busier destination needs a second pass.
-const RERUN_MAX_COUNT_PER_REQUEST = 10000
-
-function replayBlockedReason(destination: AffectedDestination): string | undefined {
- if (!destination.enabled) {
- return 'This destination is disabled. Enable it to replay its failed events.'
- }
- if (!isRerunnableHogFunctionType(destination.type)) {
- return 'This type of destination cannot be replayed.'
- }
- if (destination.failedCount === 0) {
- return 'There is nothing left to replay.'
- }
- return undefined
-}
-
-/**
- * A replay sends real events to the third party, so it gets the same confirmation the per-invocation
- * and bulk rerun buttons already use. It matters more here: one click covers the whole backlog.
- */
-function confirmReplay(destination: AffectedDestination, replayDestination: (id: string) => void): void {
- LemonDialog.open({
- title: `Replay failed events for ${destination.name || 'this destination'}?`,
- content: `This sends ${humanFriendlyNumber(destination.failedCount)} failed ${
- destination.failedCount === 1 ? 'event' : 'events'
- } to the destination again, starting from August 18. Events the destination already processed are sent a second time.`,
- primaryButton: {
- children: 'Replay',
- onClick: () => replayDestination(destination.id),
- },
- secondaryButton: { children: 'Cancel' },
- })
-}
-
-export function DestinationsIncidentReplayBanner(): JSX.Element | null {
- const { showBanner, affectedDestinations, replayStatusById, currentProjectId } = useValues(
- destinationsIncidentReplayLogic
- )
- const { replayDestination } = useActions(destinationsIncidentReplayLogic)
-
- if (!showBanner) {
- return null
- }
-
- const hasLargeBacklog = affectedDestinations.some(
- (destination) => destination.failedCount > RERUN_MAX_COUNT_PER_REQUEST
- )
-
- return (
- <LemonBanner
- type="warning"
- // Per project: without the suffix, dismissing in one project hides the recovery path
- // in every other project this browser visits.
- dismissKey={`destinations-incident-replay-2026-08-18-${currentProjectId}`}
- >
- {/* LemonBanner takes no data-attr, so the hook for autocapture and tests sits here. */}
- <div className="flex flex-col gap-2" data-attr="destinations-incident-replay-banner">
- <div>
- On August 18 an incident on our side replaced the saved credentials on some destinations with a
- placeholder, so their events stopped being delivered. We can't recover the original values. Any
- destination below marked "Enter credentials" is affected, and needs its credentials again. The rest
- have events that failed since August 18, which may or may not be related, and you can replay those.
- {hasLargeBacklog ? (
- <> A replay covers up to 10,000 failed events per run. Replay again to send the rest.</>
- ) : null}
- </div>
- <ul className="flex flex-col gap-1">
- {affectedDestinations.map((destination) => {
- const status = replayStatusById[destination.id]
- const blockedReason = replayBlockedReason(destination)
- return (
- <li key={destination.id} className="flex items-center gap-2">
- {destination.needsCredentials ? (
- <LemonButton
- type="secondary"
- size="xsmall"
- data-attr="destinations-incident-credentials-button"
- to={urls.hogFunction(destination.id, 'configuration')}
- >
- Enter credentials
- </LemonButton>
- ) : (
- <LemonButton
- type="secondary"
- size="xsmall"
- data-attr="destinations-incident-replay-button"
- loading={status === 'pending'}
- disabledReason={
- status === 'queued'
- ? 'Replay queued. Refresh the page to replay again once it finishes.'
- : blockedReason
- }
- onClick={() => confirmReplay(destination, replayDestination)}
- >
- {status === 'queued' ? 'Replay queued' : 'Replay failed events'}
- </LemonButton>
- )}
- <LemonButton size="xsmall" to={urls.hogFunction(destination.id, 'configuration')}>
- {destination.name}
- </LemonButton>
- {destination.failedCount > 0 ? (
- <span className="text-secondary">
- {humanFriendlyNumber(destination.failedCount)} failed{' '}
- {destination.failedCount === 1 ? 'event' : 'events'}
- </span>
- ) : null}
- </li>
- )
- })}
- </ul>
- </div>
- </LemonBanner>
- )
-}
diff --git a/products/cdp/frontend/destinationsIncidentReplayLogic.test.ts b/products/cdp/frontend/destinationsIncidentReplayLogic.test.ts
deleted file mode 100644
index 6fe6066d5aa3..000000000000
--- a/products/cdp/frontend/destinationsIncidentReplayLogic.test.ts
+++ /dev/null
@@ -1,180 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { useMocks } from '~/mocks/jest'
-import { initKeaTests } from '~/test/init'
-
-import {
- destinationsIncidentReplayLogic,
- incidentCountWindowStart,
- incidentReplayWindow,
-} from './destinationsIncidentReplayLogic'
-
-const MASKED_ONLY_ID = '019d244c-42c9-0000-ec6c-752c8b265c4f'
-const FAILED_ONLY_ID = '019d9146-223a-0000-8165-1a3489e88b3d'
-const DELETED_ID = '019f3834-8dbd-0000-4b19-073031109b21'
-const NO_SECRET_ID = '019f3834-8dbd-0000-4b19-073031109b22'
-
-const SECRET_SCHEMA = [{ key: 'api_key', type: 'string', label: 'API key', secret: true }]
-const INTEGRATION_SCHEMA = [{ key: 'slack_workspace', type: 'integration', label: 'Slack workspace' }]
-
-describe('destinationsIncidentReplayLogic', () => {
- let logic: ReturnType<typeof destinationsIncidentReplayLogic.build>
-
- beforeEach(() => {
- useMocks({
- post: {
- '/api/environments/:team_id/query/:query_kind/': () => [
- 200,
- {
- results: [
- [FAILED_ONLY_ID, 224],
- [NO_SECRET_ID, 91],
- [DELETED_ID, 3],
- ],
- },
- ],
- },
- get: {
- '/api/projects/:team_id/hog_functions/masked_secrets/': () => [
- 200,
- [
- {
- id: MASKED_ONLY_ID,
- name: 'Customer.io',
- type: 'destination',
- enabled: true,
- input_keys: ['api_key'],
- draft_input_keys: [],
- },
- ],
- ],
- '/api/projects/:team_id/hog_functions/:id/': (req) => {
- if (req.params.id === MASKED_ONLY_ID) {
- return [
- 200,
- {
- id: MASKED_ONLY_ID,
- name: 'Customer.io',
- type: 'destination',
- enabled: true,
- inputs_schema: SECRET_SCHEMA,
- },
- ]
- }
- if (req.params.id === FAILED_ONLY_ID) {
- return [
- 200,
- {
- id: FAILED_ONLY_ID,
- name: 'HubSpot',
- type: 'destination',
- enabled: true,
- inputs_schema: SECRET_SCHEMA,
- },
- ]
- }
- if (req.params.id === NO_SECRET_ID) {
- return [
- 200,
- {
- id: NO_SECRET_ID,
- name: 'Slack',
- type: 'destination',
- enabled: true,
- inputs_schema: INTEGRATION_SCHEMA,
- },
- ]
- }
- return [404, { detail: 'Not found.' }]
- },
- },
- })
- initKeaTests()
- logic = destinationsIncidentReplayLogic()
- logic.mount()
- })
-
- it('excludes a failing destination that holds no secret the incident could clear', async () => {
- await expectLogic(logic, () => logic.actions.loadAffectedDestinations()).toDispatchActions([
- 'loadAffectedDestinationsSuccess',
- ])
-
- expect(logic.values.affectedDestinations.map((row) => row.id)).not.toContain(NO_SECRET_ID)
- })
-
- it('lists destinations found by either signal and drops deleted ones', async () => {
- await expectLogic(logic, () => logic.actions.loadAffectedDestinations()).toDispatchActions([
- 'loadAffectedDestinationsSuccess',
- ])
-
- expect(logic.values.affectedDestinations).toEqual([
- {
- id: FAILED_ONLY_ID,
- name: 'HubSpot',
- type: 'destination',
- failedCount: 224,
- needsCredentials: false,
- enabled: true,
- },
- {
- id: MASKED_ONLY_ID,
- name: 'Customer.io',
- type: 'destination',
- failedCount: 0,
- needsCredentials: true,
- enabled: true,
- },
- ])
- })
-
- it('still surfaces the recovery path when the failed-count query errors', async () => {
- useMocks({
- post: {
- '/api/environments/:team_id/query/:query_kind/': () => [500, { detail: 'Query timed out' }],
- },
- })
-
- await expectLogic(logic, () => logic.actions.loadAffectedDestinations()).toDispatchActions([
- 'loadAffectedDestinationsSuccess',
- ])
-
- expect(logic.values.affectedDestinations).toEqual([
- {
- id: MASKED_ONLY_ID,
- name: 'Customer.io',
- type: 'destination',
- failedCount: 0,
- needsCredentials: true,
- enabled: true,
- },
- ])
- })
-
- describe('incidentCountWindowStart', () => {
- // The replay sends the incident start as UTC. If the count read it as team-local wall time
- // instead, the two would cover spans a whole timezone offset apart.
- it('renders the same instant the replay sends, in the team timezone', () => {
- expect(incidentCountWindowStart('UTC')).toEqual('2026-08-18 13:30:00.000')
- expect(incidentCountWindowStart('US/Pacific')).toEqual('2026-08-18 06:30:00.000')
- expect(incidentCountWindowStart('Europe/Berlin')).toEqual('2026-08-18 15:30:00.000')
- })
- })
-
- describe('incidentReplayWindow', () => {
- it('uses the incident start while the incident is within the 30-day cap', () => {
- expect(incidentReplayWindow(new Date('2026-08-25T00:00:00.000Z'))).toEqual({
- window_start: '2026-08-18T13:30:00.000Z',
- window_end: '2026-08-25T00:00:00.000Z',
- })
- })
-
- it('clamps the start to 30 days once the incident is older than the cap', () => {
- const { window_start, window_end } = incidentReplayWindow(new Date('2026-10-01T00:00:00.000Z'))
- expect(window_start).toEqual('2026-09-01T00:00:00.000Z')
- expect(window_end).toEqual('2026-10-01T00:00:00.000Z')
- // Stays within the rerun endpoint's 30-day cap, so the request is not rejected.
- const spanDays = (new Date(window_end).getTime() - new Date(window_start).getTime()) / (24 * 60 * 60 * 1000)
- expect(spanDays).toBeLessThanOrEqual(30)
- })
- })
-})
diff --git a/products/cdp/frontend/destinationsIncidentReplayLogic.ts b/products/cdp/frontend/destinationsIncidentReplayLogic.ts
deleted file mode 100644
index 4634a1d664ed..000000000000
--- a/products/cdp/frontend/destinationsIncidentReplayLogic.ts
+++ /dev/null
@@ -1,333 +0,0 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-import { subscriptions } from 'kea-subscriptions'
-
-import api from 'lib/api'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { dayjs } from 'lib/dayjs'
-import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
-import { projectTimezoneOf } from 'scenes/hog-functions/invocations/hogInvocationsLogic'
-import { projectLogic } from 'scenes/projectLogic'
-import { teamLogic } from 'scenes/teamLogic'
-
-import { hogql } from '~/queries/utils'
-import type { HogFunctionTypeType } from '~/types'
-
-import { hogFunctionsMaskedSecretsRetrieve, hogFunctionsRerunCreate, hogFunctionsRetrieve } from './generated/api'
-import type { HogFunctionApi } from './generated/api.schemas'
-
-// Deploy time of the change that started overwriting stored secrets with the mask, rounded down
-// from the two regional deploys (13:34 UTC in EU, 13:35 in US). Failures do not stop at a fix
-// deploy the way an ordinary regression's do - they stop when the owner enters the credential
-// again - so the window has no fixed end and runs up to the moment of the replay.
-const INCIDENT_WINDOW_START = '2026-08-18T13:30:00.000Z'
-
-// The rerun endpoint rejects a window wider than 30 days (RERUN_MAX_WINDOW_DAYS in
-// posthog/api/hog_invocation_rerun.py), a cap that tracks the 30-day ClickHouse TTL on the failed
-// rows. Once the incident is more than 30 days old the fixed start above would push the window past
-// that cap and every replay would 400 while the banner still shows a working button. The clamped-off
-// span holds only rows the TTL has already dropped, so nothing replayable is lost.
-const REPLAY_MAX_WINDOW_DAYS = 30
-const MS_PER_DAY = 24 * 60 * 60 * 1000
-
-// Clamp the replay start to the later of the incident start and 30 days before now, so the window
-// sent to the rerun endpoint never exceeds its cap. Exported for the unit test.
-export function incidentReplayWindow(now: Date): { window_start: string; window_end: string } {
- const earliestStart = new Date(now.getTime() - REPLAY_MAX_WINDOW_DAYS * MS_PER_DAY)
- const incidentStart = new Date(INCIDENT_WINDOW_START)
- const windowStart = incidentStart > earliestStart ? incidentStart : earliestStart
- return { window_start: windowStart.toISOString(), window_end: now.toISOString() }
-}
-
-// One row per destination, so a project with a long tail of unrelated failures would otherwise
-// render a wall of them. Ordered by failure count, so the cut keeps the rows worth showing.
-const MAX_LISTED_DESTINATIONS = 20
-
-export interface AffectedDestination {
- id: string
- name: string
- type: HogFunctionTypeType | null
- failedCount: number
- /** The stored secret is still the mask, so a replay would fail against the third party again. */
- needsCredentials: boolean
- enabled: boolean
-}
-
-export type ReplayStatus = 'pending' | 'queued'
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface destinationsIncidentReplayLogicValues {
- featureFlags: FeatureFlagsSet // featureFlagLogic
- currentProjectId: number | null // projectLogic
- affectedDestinations: AffectedDestination[]
- affectedDestinationsLoading: boolean
- replayStatusById: Record<string, ReplayStatus>
- showBanner: boolean
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface destinationsIncidentReplayLogicActions {
- loadAffectedDestinations: () => any
- loadAffectedDestinationsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadAffectedDestinationsSuccess: (
- affectedDestinations: {
- enabled: boolean
- failedCount: number
- id: string
- name: string
- needsCredentials: boolean
- type: HogFunctionTypeType | null
- }[],
- payload?: any
- ) => {
- affectedDestinations: {
- enabled: boolean
- failedCount: number
- id: string
- name: string
- needsCredentials: boolean
- type: HogFunctionTypeType | null
- }[]
- payload?: any
- }
- replayDestination: (id: string) => {
- id: string
- }
- replayDestinationFailure: (id: string) => {
- id: string
- }
- replayDestinationSuccess: (id: string) => {
- id: string
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface destinationsIncidentReplayLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- showBanner: (featureFlags: FeatureFlagsSet, affectedDestinations: AffectedDestination[]) => boolean
- }
-}
-
-export type destinationsIncidentReplayLogicType = MakeLogicType<
- destinationsIncidentReplayLogicValues,
- destinationsIncidentReplayLogicActions,
- Record<string, any>,
- destinationsIncidentReplayLogicMeta
->
-
-/** Whether the destination stores a credential of its own, which is what the incident could clear. */
-function hasSecretInput(hogFunction: HogFunctionApi): boolean {
- return (hogFunction.inputs_schema ?? []).some((schema) => schema.secret)
-}
-
-/**
- * The incident start as a `scheduled_at` literal, in the team's timezone.
- *
- * Not `dateClauseFor`: that runs the bound through `dayjs.tz(value, zone)`, which reads the string
- * as wall time in the team's zone and discards the `Z`. The instant would shift by the team's
- * offset, so the count would cover a different span than the replay, which sends the same boundary
- * as UTC. Parsing as UTC first and rendering in the team's zone keeps the two in step.
- *
- * Exported for the unit test.
- */
-export function incidentCountWindowStart(timezone: string): string {
- return dayjs(INCIDENT_WINDOW_START).tz(timezone).format('YYYY-MM-DD HH:mm:ss.SSS')
-}
-
-/**
- * Counts, per destination, the invocations whose latest status is still failed since the incident
- * began. One query rather than one per destination, and it doubles as the discovery step.
- *
- * There is deliberately no upper bound on `scheduled_at`: a replay writes its lifecycle rows into
- * the partition of the replay time, not the original one. Collapsing every partition from the
- * incident start onwards is what makes a recovered invocation read as succeeded, so a count shrinks
- * as a replay drains and the destination leaves the banner when it reaches zero. Leaving the bound
- * off also keeps the query text stable between mounts, which a `< now` bound did not.
- */
-async function loadFailedCountsByDestination(): Promise<Map<string, number>> {
- const timezone = projectTimezoneOf(teamLogic.findMounted()?.values.currentTeam)
- const dateClause = hogql.raw(`AND scheduled_at >= '${incidentCountWindowStart(timezone)}'`)
- const query = hogql`
- SELECT function_id, count() AS failed_count FROM (
- SELECT
- function_id,
- invocation_id
- FROM posthog.hog_invocation_results
- WHERE function_kind = 'hog_function'
- ${dateClause}
- GROUP BY function_id, invocation_id
- HAVING argMax(is_deleted, version) = 0
- AND argMax(status, version) = 'failed'
- )
- GROUP BY function_id
- ORDER BY failed_count DESC
- LIMIT ${MAX_LISTED_DESTINATIONS}
- `
- const response = await api.queryHogQL(query, {
- scene: 'DestinationsIncidentReplay',
- productKey: 'pipeline_destinations',
- })
-
- const counts = new Map<string, number>()
- response.results?.forEach((row) => {
- if (Array.isArray(row) && row[0]) {
- counts.set(String(row[0]), Number(row[1] ?? 0))
- }
- })
- return counts
-}
-
-export const destinationsIncidentReplayLogic = kea<destinationsIncidentReplayLogicType>([
- path(['products', 'cdp', 'frontend', 'destinationsIncidentReplayLogic']),
- connect(() => ({
- values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags']],
- })),
- actions({
- replayDestination: (id: string) => ({ id }),
- replayDestinationSuccess: (id: string) => ({ id }),
- replayDestinationFailure: (id: string) => ({ id }),
- }),
- loaders(({ values }) => ({
- affectedDestinations: [
- [] as AffectedDestination[],
- {
- loadAffectedDestinations: async () => {
- if (!values.currentProjectId) {
- return []
- }
- const projectId = String(values.currentProjectId)
-
- // Two independent signals, because neither covers the whole recovery on its
- // own. A destination still storing the mask is definitely broken, even with no
- // traffic yet. One with failures but no mask has either had its credential
- // entered again already, or broke for its own reasons - either way its failed
- // invocations are still sitting there to replay.
- //
- // The masked-secrets lookup is the primary recovery signal and cheap, so its
- // failure still fails the load. The failed-count query is heavy and its window
- // grows daily, so a timeout on it must not hide the "Enter credentials" rows the
- // masked-secrets signal builds on its own.
- const [maskedSecrets, failedCounts] = await Promise.all([
- hogFunctionsMaskedSecretsRetrieve(projectId),
- loadFailedCountsByDestination().catch(() => new Map<string, number>()),
- ])
-
- const maskedIds = new Set(maskedSecrets.map((row) => String(row.id)))
- const candidateIds = [...new Set([...maskedIds, ...failedCounts.keys()])]
- if (candidateIds.length === 0) {
- return []
- }
-
- // Fetch each destination by ID rather than intersecting with the list endpoint,
- // which caps at a page size: in a project with more destinations than one page
- // the affected ones can fall outside it and silently drop off the banner. Only a
- // definitive 403 (no access) or 404 (hard-deleted, nothing to replay) drops a
- // row. A transient failure keeps it, so a blip never hides the recovery path.
- const dropped = new Set<string>()
- const fetched = await Promise.all(
- candidateIds.map(async (id) => {
- try {
- return await hogFunctionsRetrieve(projectId, id)
- } catch (error) {
- const status = (error as { status?: number }).status
- if (status === 403 || status === 404) {
- dropped.add(id)
- }
- return null
- }
- })
- )
- const byId = new Map(
- fetched
- .filter((hogFunction): hogFunction is HogFunctionApi => hogFunction !== null)
- .map((hogFunction) => [String(hogFunction.id), hogFunction])
- )
-
- return (
- candidateIds
- .filter((id) => !dropped.has(id))
- // A destination with no secret input never held a credential we could clear,
- // so a failure on it belongs to the destination, not to this incident. This
- // drops every OAuth-backed destination (Slack, ads, Discord, Linear, GitHub),
- // whose credentials live on the Integration record. A destination we could
- // not fetch stays: an unknown schema must not hide a real recovery path.
- .filter((id) => {
- const hogFunction = byId.get(id)
- return maskedIds.has(id) || !hogFunction || hasSecretInput(hogFunction)
- })
- .map((id) => {
- const hogFunction = byId.get(id)
- const maskedRow = maskedSecrets.find((row) => String(row.id) === id)
- return {
- id,
- name: hogFunction?.name ?? maskedRow?.name ?? '',
- type: (hogFunction?.type ?? maskedRow?.type ?? null) as HogFunctionTypeType | null,
- failedCount: failedCounts.get(id) ?? 0,
- needsCredentials: maskedIds.has(id),
- enabled: hogFunction?.enabled ?? maskedRow?.enabled ?? false,
- }
- })
- .sort((a, b) => b.failedCount - a.failedCount)
- )
- },
- },
- ],
- })),
- reducers({
- replayStatusById: [
- {} as Record<string, ReplayStatus>,
- {
- replayDestination: (state, { id }) => ({ ...state, [id]: 'pending' }),
- replayDestinationSuccess: (state, { id }) => ({ ...state, [id]: 'queued' }),
- replayDestinationFailure: (state, { id }) => {
- const { [id]: _discarded, ...rest } = state
- return rest
- },
- },
- ],
- }),
- selectors({
- showBanner: [
- (s) => [s.featureFlags, s.affectedDestinations],
- (featureFlags: FeatureFlagsSet, affectedDestinations: AffectedDestination[]): boolean =>
- !!featureFlags[FEATURE_FLAGS.DESTINATIONS_INCIDENT_REPLAY] && affectedDestinations.length > 0,
- ],
- }),
- listeners(({ actions, values }) => ({
- replayDestination: async ({ id }) => {
- if (!values.currentProjectId) {
- actions.replayDestinationFailure(id)
- return
- }
- try {
- await hogFunctionsRerunCreate(String(values.currentProjectId), id, {
- filter: incidentReplayWindow(new Date()),
- })
- actions.replayDestinationSuccess(id)
- lemonToast.success('Replay queued. Failed events will be sent again shortly.')
- } catch {
- actions.replayDestinationFailure(id)
- lemonToast.error("Couldn't queue the replay. Try again, and contact support if it keeps happening.")
- }
- },
- })),
- // A subscription instead of afterMount: flags can resolve after the logic mounts, and a
- // one-time mount check would then never load. This fires with the value at mount and again
- // when the flag flips on, so only flagged teams pay for the lookup query.
- subscriptions(({ actions }) => ({
- featureFlags: (featureFlags: FeatureFlagsSet, oldFeatureFlags: FeatureFlagsSet | undefined) => {
- const isOn = !!featureFlags[FEATURE_FLAGS.DESTINATIONS_INCIDENT_REPLAY]
- const wasOn = !!oldFeatureFlags?.[FEATURE_FLAGS.DESTINATIONS_INCIDENT_REPLAY]
- if (isOn && !wasOn) {
- actions.loadAffectedDestinations()
- }
- },
- })),
-])
diff --git a/products/cdp/package.json b/products/cdp/package.json
index 05953d8bec12..164625ec1cc7 100644
--- a/products/cdp/package.json
+++ b/products/cdp/package.json
@@ -5,11 +5,9 @@
},
"dependencies": {
"kea": "catalog:",
- "kea-loaders": "catalog:",
- "kea-subscriptions": "catalog:"
+ "kea-loaders": "catalog:"
},
"devDependencies": {
- "@storybook/react": "catalog:",
"@testing-library/react": "^14.3.1",
"kea-test-utils": "catalog:"
},