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.

fix(marketing): recover source refreshes and report blocked imports (#114727)

Javier Bahamondesc2872f179004
diff --git a/docs/internal/marketing-source-suggestions.md b/docs/internal/marketing-source-suggestions.md
index a22c6a1375a7..231774f4645c 100644
--- a/docs/internal/marketing-source-suggestions.md
+++ b/docs/internal/marketing-source-suggestions.md
@@ -83,3 +83,5 @@ Table resolution uses schema metadata when available and otherwise recognizes so
The setup plan caches event scans for seven days per project. Explicit refresh requests respect a one-hour cooldown.
Source health polling refreshes metadata without forcing every dashboard query.
Campaign reporting waits for all required schemas to complete their first sync.
+Source refresh failures retain the previous list and allow a later retry.
+Native source readiness checks include required schema failures and paused imports.
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.test.ts
index 22b1560c17b2..ef08e4f8d4ac 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.test.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.test.ts
@@ -10,7 +10,14 @@ import {
NodeKind,
VALID_NATIVE_MARKETING_SOURCES,
} from '~/queries/schema/schema-general'
-import { BaseMathType, PropertyMathType } from '~/types'
+import {
+ AccessControlLevel,
+ BaseMathType,
+ PropertyMathType,
+ ExternalDataSource,
+ ExternalDataSchemaStatus,
+ ExternalDataJobStatus,
+} from '~/types'
import { NativeSource } from './marketingAnalyticsLogic'
import {
@@ -21,6 +28,8 @@ import {
goalSumsAProperty,
getSortedColumnsByArray,
orderArrayByPreference,
+ nativeSourceConnectionStatus,
+ NEEDED_FIELDS_FOR_NATIVE_MARKETING_ANALYTICS,
rowMatchesSearch,
sanitizeIntegrationFilter,
validColumnsForTiles,
@@ -686,6 +695,43 @@ describe('marketing analytics utils', () => {
})
})
+ it.each([ExternalDataSchemaStatus.Failed, ExternalDataSchemaStatus.Paused, ExternalDataSchemaStatus.Cancelled])(
+ 'reports a required %s schema as needing attention before the first sync',
+ (status) => {
+ const source: ExternalDataSource = {
+ id: 'source',
+ source_id: 'source',
+ connection_id: 'connection',
+ prefix: null,
+ description: null,
+ created_via: 'web',
+ latest_error: null,
+ sync_frequency: '24hour',
+ job_inputs: {},
+ revenue_analytics_config: { enabled: false, include_invoiceless_charges: false },
+ user_access_level: AccessControlLevel.Admin,
+ source_type: 'GoogleAds',
+ status: ExternalDataJobStatus.Completed,
+ schemas: NEEDED_FIELDS_FOR_NATIVE_MARKETING_ANALYTICS.GoogleAds.map((name) => ({
+ id: name,
+ name,
+ label: null,
+ should_sync: true,
+ status,
+ incremental: false,
+ sync_type: 'full_refresh',
+ sync_time_of_day: null,
+ latest_error: null,
+ incremental_field: null,
+ incremental_field_type: null,
+ sync_frequency: '24hour',
+ primary_key_columns: null,
+ })),
+ }
+ expect(nativeSourceConnectionStatus(source).status).toBe('Needs attention')
+ }
+ )
+
describe('sanitizeIntegrationFilter', () => {
it('drops a key the query schema no longer accepts', () => {
const stored = { integrationSourceIds: ['abc'], removedOption: true }
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts
index 5a5fe559382f..36aa17cdbbb8 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts
@@ -14,7 +14,7 @@ import {
NodeKind,
VALID_NATIVE_MARKETING_SOURCES,
} from '~/queries/schema/schema-general'
-import { HogQLMathType, ManualLinkSourceType, PropertyMathType } from '~/types'
+import { ExternalDataSource, HogQLMathType, ManualLinkSourceType, PropertyMathType } from '~/types'
import type { ExternalDataSourceTypeEnumApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
@@ -55,6 +55,31 @@ export function getEnabledNativeMarketingSources(
})
}
+export function getEnabledNativeMarketingSourcesInDisplayOrder(
+ featureFlags: Partial<Record<FeatureFlagKey, boolean | string>>
+): readonly NativeMarketingSource[] {
+ const sourceOrder: NativeMarketingSource[] = [
+ 'GoogleAds',
+ 'MetaAds',
+ 'BingAds',
+ 'LinkedinAds',
+ 'TikTokAds',
+ 'RedditAds',
+ 'PinterestAds',
+ 'SnapchatAds',
+ 'OpenAIAds',
+ 'AppleSearchAds',
+ 'AmazonAds',
+ 'RoktAds',
+ 'TwitterAds',
+ ]
+ return [...getEnabledNativeMarketingSources(featureFlags)].sort(
+ (left, right) =>
+ (sourceOrder.includes(left) ? sourceOrder.indexOf(left) : sourceOrder.length) -
+ (sourceOrder.includes(right) ? sourceOrder.indexOf(right) : sourceOrder.length)
+ )
+}
+
export const MAX_ITEMS_TO_SHOW = 3
// Derive table names from centralized config
@@ -1053,3 +1078,35 @@ export function sanitizeIntegrationFilter(stored: unknown): IntegrationFilter {
...(typeof includeNonIntegrated === 'boolean' ? { includeNonIntegrated } : {}),
}
}
+
+export function nativeSourceConnectionStatus(source: ExternalDataSource): {
+ status: 'Connected' | 'Syncing' | 'Needs attention'
+ detail: string
+} {
+ const fields = NEEDED_FIELDS_FOR_NATIVE_MARKETING_ANALYTICS[source.source_type as NativeMarketingSource]
+ if (!fields) {
+ return { status: 'Needs attention', detail: 'Open setup to check this connection.' }
+ }
+ const schemas = fields.map((field) => findSchemaByFieldName(source.schemas, field, source.source_type))
+ if (!schemas.every((schema) => schema?.should_sync)) {
+ return { status: 'Needs attention', detail: 'Open setup to enable the required tables for this connection.' }
+ }
+ if (['Billing limits', 'Billing limit too low'].includes(source.status)) {
+ return {
+ status: 'Needs attention',
+ detail: 'The import reached a billing limit. Open setup to review the limit.',
+ }
+ }
+ if (schemas.some((schema) => ['Paused', 'Cancelled'].includes(schema?.status ?? ''))) {
+ return { status: 'Needs attention', detail: 'The import is paused or canceled. Open setup to resume it.' }
+ }
+ if (source.status === 'Failed' || schemas.some((schema) => schema?.status === 'Failed')) {
+ return { status: 'Needs attention', detail: 'The import failed. Open setup to check this connection.' }
+ }
+ if (schemas.every((schema) => schema?.last_synced_at)) {
+ return { status: 'Connected', detail: 'Spend data is ready.' }
+ }
+ return source.status === 'Running'
+ ? { status: 'Syncing', detail: 'Your first import is running. Spend data will appear when it finishes.' }
+ : { status: 'Connected', detail: 'Waiting for the first sync to finish.' }
+}
diff --git a/products/data_warehouse/frontend/shared/logics/sourcesDataLogic.ts b/products/data_warehouse/frontend/shared/logics/sourcesDataLogic.ts
index 2c07e5bc8440..dbf7ea4b8265 100644
--- a/products/data_warehouse/frontend/shared/logics/sourcesDataLogic.ts
+++ b/products/data_warehouse/frontend/shared/logics/sourcesDataLogic.ts
@@ -1,7 +1,7 @@
import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
-import api, { ApiError, ApiMethodOptions, PaginatedResponse } from 'lib/api'
+import api, { ApiMethodOptions, PaginatedResponse } from 'lib/api'
import { ExternalDataSource, ExternalDataSourceRevenueAnalyticsConfig } from '~/types'
@@ -10,6 +10,7 @@ export interface sourcesDataLogicValues {
dataWarehouseSources: PaginatedResponse<ExternalDataSource> | null
dataWarehouseSourcesLoading: boolean
lastUpdateConnectionWarning: string | null
+ sourcesLoadError: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -135,7 +136,8 @@ export const sourcesDataLogic = kea<sourcesDataLogicType>([
await breakpoint(300)
actions.abortAnyRunningQuery()
- cache.abortController = new AbortController()
+ const controller = new AbortController()
+ cache.abortController = controller
const methodOptions: ApiMethodOptions = {
signal: cache.abortController.signal,
}
@@ -156,24 +158,15 @@ export const sourcesDataLogic = kea<sourcesDataLogicType>([
const response: PaginatedResponse<ExternalDataSource> = { ...res, results, next: null }
return response
} catch (error: any) {
- // Transient failures shouldn't surface as exceptions:
- // - 403: the user has no access to the endpoint
- // - AbortError: abortAnyRunningQuery cancelled this request mid-flight
- // - ApiError with no HTTP status: handleFetch wraps native fetch
- // failures (offline, DNS, CORS) as ApiError(err, undefined)
- // Anything else (including kea's BreakPointException) propagates.
- const isTransient =
- error?.status === 403 ||
- error?.name === 'AbortError' ||
- (error instanceof ApiError && error.status === undefined)
- if (!isTransient) {
- throw error
- }
- // Bail out if a newer loadSources has superseded this one so we don't
- // clobber its state with an empty result.
+ // A superseded request must not clear the newer request's controller.
breakpoint()
- cache.abortController = null
- return { results: [], count: 0, next: null, previous: null }
+ if (cache.abortController === controller) {
+ cache.abortController = null
+ }
+ if (error?.status === 403) {
+ return { results: [], count: 0, next: null, previous: null }
+ }
+ throw error
}
},
updateSource: async (source: ExternalDataSource) => {
@@ -207,6 +200,7 @@ export const sourcesDataLogic = kea<sourcesDataLogicType>([
],
})),
reducers(({ cache }) => ({
+ sourcesLoadError: [false, { loadSourcesSuccess: () => false, loadSourcesFailure: () => true }],
lastUpdateConnectionWarning: [
null as string | null,
{
diff --git a/products/data_warehouse/frontend/shared/logics/tests/sourcesDataLogic.test.ts b/products/data_warehouse/frontend/shared/logics/tests/sourcesDataLogic.test.ts
index 295196bf82a7..efc28ff49a25 100644
--- a/products/data_warehouse/frontend/shared/logics/tests/sourcesDataLogic.test.ts
+++ b/products/data_warehouse/frontend/shared/logics/tests/sourcesDataLogic.test.ts
@@ -91,27 +91,55 @@ describe('sourcesDataLogic', () => {
expect(api.get).toHaveBeenCalledWith(mockResponse.next, { signal: expect.any(AbortSignal) })
})
+ it.each([['403 access denied', new ApiError('forbidden', 403)]])(
+ 'returns an empty paginated result on %s without surfacing loader failure',
+ async (_label, error) => {
+ jest.spyOn(api.externalDataSources, 'list').mockResolvedValue({
+ ...emptyResponse,
+ next: '/api/environments/997/external_data_sources/?offset=1',
+ })
+ jest.spyOn(api, 'get').mockRejectedValue(error)
+
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.loadSources()
+ })
+ .toDispatchActions(['loadSources', 'loadSourcesSuccess'])
+ .toNotHaveDispatchedActions(['loadSourcesFailure'])
+ .toMatchValues({
+ dataWarehouseSources: emptyResponse,
+ dataWarehouseSourcesLoading: false,
+ })
+ }
+ )
it.each([
- ['403 access denied', new ApiError('forbidden', 403)],
- ['network failure (no HTTP status)', new ApiError('TypeError: Failed to fetch', undefined)],
- ['aborted request', Object.assign(new Error('aborted'), { name: 'AbortError' })],
- ])('returns an empty paginated result on %s without surfacing loader failure', async (_label, error) => {
- jest.spyOn(api.externalDataSources, 'list').mockResolvedValue({
+ ['server error', new ApiError('unavailable', 503)],
+ ['network error', new ApiError('offline', undefined)],
+ ])('keeps existing sources and recovers after a %s', async (_label, error) => {
+ const response = {
...emptyResponse,
- next: '/api/environments/997/external_data_sources/?offset=1',
- })
- jest.spyOn(api, 'get').mockRejectedValue(error)
-
+ results: [{ id: 'existing', source_type: 'GoogleSearchConsole' } as ExternalDataSource],
+ }
+ jest.spyOn(api.externalDataSources, 'list')
+ .mockResolvedValueOnce(response)
+ .mockRejectedValueOnce(error)
+ .mockResolvedValueOnce(response)
logic.mount()
-
- await expectLogic(logic, () => {
- logic.actions.loadSources()
- })
- .toDispatchActions(['loadSources', 'loadSourcesSuccess'])
- .toNotHaveDispatchedActions(['loadSourcesFailure'])
+ await expectLogic(logic, () => logic.actions.loadSources()).toDispatchActions(['loadSourcesSuccess'])
+ await expectLogic(logic, () => logic.actions.loadSources())
+ .toDispatchActions(['loadSourcesFailure'])
+ .toMatchValues({
+ dataWarehouseSources: response,
+ dataWarehouseSourcesLoading: false,
+ sourcesLoadError: true,
+ })
+ await expectLogic(logic, () => logic.actions.loadSources())
+ .toDispatchActions(['loadSourcesSuccess'])
.toMatchValues({
- dataWarehouseSources: emptyResponse,
+ dataWarehouseSources: response,
dataWarehouseSourcesLoading: false,
+ sourcesLoadError: false,
})
})
})