: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
fix(marketing): avoid stale search data and preselect source tables (#112607)
Javier Bahamondes9a8b01154501
diff --git a/docs/internal/web-analytics-query-serving.md b/docs/internal/web-analytics-query-serving.mdindex 3946dfe9298e..51d6d8454c8e 100644--- a/docs/internal/web-analytics-query-serving.md+++ b/docs/internal/web-analytics-query-serving.md@@ -82,7 +82,16 @@ The Search performance section sits below the campaign table in Ad performance,It shares the integration, date and comparison filters with the campaign table.The integration filter and Add source menu list Google Search Console separately under Organic search.Empty filtered results offer Clear filters; unfiltered views suggest connecting missing Google Ads or Google Search Console sources.-Connected sources with missing tables show a sync setup action instead of a reconnect prompt.+Connected sources show separate setup messages for disabled tables, tables awaiting a first successful sync, failed or paused syncs, and stale data.+Search performance excludes a table when its last successful sync is older than twice its configured sync interval.+The source list includes each table's sync frequency so this check uses the table's schedule.+An unrecognized sync interval is returned as null, which keeps the source list available and skips the cadence check for that table.+GSC prefers the dedicated query or page table, then falls back to a ready query-and-page table with a notice that totals can differ.+If neither table is ready, the source is excluded instead of displaying zero traffic and misleading period comparisons.+Query and page details use the same readiness checks.+New Google Ads connections preselect `keyword`, `keyword_stats`, and `landing_page_stats`; Bing Ads preselects `keyword_performance_report`.+New GSC connections preselect the web query, page, and query-and-page tables; non-web search types remain opt-in.+These defaults do not change the saved table selection of an existing source.Source discovery loads every page of connected integrations before applying the filter.The date and comparison controls select the current and comparison periods.Organic query and page details retain the selected integration sources.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex e6a3f6b7c142..9fb5f56fe392 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11819,9 +11819,9 @@ snapshots:scenes-app-marketing-analytics-freshness--fresh--light:hash: v1.k794b7964.b8d9453c270c310350d2bcf30cdb54cae4da19b8877e8d3206160478eb2dda94.dJpt6MIMxg7mOxiHC6PoqwTGwMfiGrln7SheHTKHTcUscenes-app-marketing-analytics-search-performance--awaiting-sync--dark:- hash: v1.k794b7964.9d8eec78fb7621fa32363daf0190898cb58113226a3b97ab564057c12399d1ce.gC-HZMskxryXdiDccRsq7kft4ozwhNtMhMU1cX9__2o+ hash: v1.k794b7964.a68e5069915d1416731bb56e1bd061b81020839cf35d98cdc01552a0c7fe0602.s7rS2bvBpMV8lvMnKn2C5VihtDFuU_Bq0x7vnTZ7jK4scenes-app-marketing-analytics-search-performance--awaiting-sync--light:- hash: v1.k794b7964.9a6ee81e77cfe8c5a3b432480754b1e1d68f8bd6e26744fc9281728dd33e2299.WE2_FirF5AFc0ouzNiOtwr_BsrMZ8WqrkpTHYSXCspY+ hash: v1.k794b7964.1e682849cf3ff944c156abae9e4a762cbfb4a6067a3a28b92f0a900f62d781cd.2NWULrKTIdOxwZwMcOOWiXaakv5AQ5GNtbiACz2FzyUscenes-app-marketing-analytics-search-performance--comparison--dark:hash: v1.k794b7964.de77865816c9cd27388687b2ec104f69a0940f558f33eeb71209f88972fb39e6.myT4UFo_7h3EJKHq1MYkev21vFTvp4RNgINtO1ksSq4scenes-app-marketing-analytics-search-performance--comparison--light:@@ -11902,6 +11902,18 @@ snapshots:hash: v1.k794b7964.874d4819628e188381b6b9c0c7799b572d512e05a3ef968fd5bce45fe72df26b.34-FVEAK6yWUfN6uBxYIlsg7eEov6vFa4oCCKG82J7sscenes-app-marketing-analytics-search-performance--sources-error--light:hash: v1.k794b7964.159cf8b9647d98ad2c63ce40109229e9ffd0352de1d98167b9446794a947ff21.gupk_qTVysxLVkierQb3CrLvQ4-AtOFEXoQ4yuxHtlU+ scenes-app-marketing-analytics-search-performance--stale-aggregate--dark:+ hash: v1.k794b7964.46d7f9bf54008e910deb07c593b94f52dd4c2b4ed4b29a57ac0caec2eb24819f.J-z6BD0oFq5-WRV9lJv3yc1IX0LBjCEAOKlW-2zeQQU+ scenes-app-marketing-analytics-search-performance--stale-aggregate--light:+ hash: v1.k794b7964.81cfee0cb23c6efe920258b66ff25585e1ba4f40dbab428bf0d8f07826dc81bf.tZDfCQ37-cegGm-Zm6GWo942xnmXkZHwbdFsHdzAGQE+ scenes-app-marketing-analytics-search-performance--unavailable-sources--dark:+ hash: v1.k794b7964.f6115da5bb35e65e9e48dda2f2caa8c3ea2c5d29b2e820f0a151f544f9d9c6c6.JiUwR7QskSO2lnI3Iq0P_NclgAPQye-fndfCTAjqDsQ+ scenes-app-marketing-analytics-search-performance--unavailable-sources--light:+ hash: v1.k794b7964.c71766ec41c46d47dd676129e4f3b837ecab3cc59a65af160c45c0c0a809f922.qbs-hSZcGidbcdyt3ggbsM6icZ28TM29U78ALMAktfE+ scenes-app-marketing-analytics-search-performance--unavailable-sources-narrow--dark:+ hash: v1.k794b7964.b8c97421239d5053d4ae1f01901a73254eee804c8dd722f71062593004d23422.HCopq5hkJ4Ru-bHW4fdMVo0bK3WC_R-Kn5XZ-NYFPKo+ scenes-app-marketing-analytics-search-performance--unavailable-sources-narrow--light:+ hash: v1.k794b7964.7f7d654e0ec8b3c7bd0709a979fce22876760760ccc966528354484f84a5f139.A1RAOnCcgSPTsbI7KQYj06cYSVRXK8cRvdT2bk8SvO4scenes-app-marketing-analytics-source-status--source-issues--dark:hash: v1.k794b7964.f387ac40dbf399676c91b2f6de86c2b169e9aaa86205af692abf51a141ead5d7.3PpHqWiSeMKvXuYLv4lU1yM_tqF38xD4NiUkUX6XW2Uscenes-app-marketing-analytics-source-status--source-issues--light:diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.tsindex 43b07bdf5087..1d8adfad6b29 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts@@ -5,6 +5,7 @@ import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'import { FEATURE_FLAGS } from 'lib/constants'+import { dayjs } from 'lib/dayjs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'import { teamLogic } from 'scenes/teamLogic'@@ -113,6 +114,8 @@ describe('marketingAnalyticsLogic', () => {{name: 'search_analytics_by_query_page',should_sync: true,+ last_synced_at: dayjs(),+ sync_frequency: '24hour',table: { name: 'organic_query_pages', hogql_name: 'organic_query_pages' },} as ExternalDataSourceSchema,],diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceDetail.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceDetail.tsxindex 27944a88c887..2d271e80f6e6 100644--- a/products/marketing_analytics/frontend/search/SearchPerformanceDetail.tsx+++ b/products/marketing_analytics/frontend/search/SearchPerformanceDetail.tsx@@ -12,7 +12,8 @@ import { searchPerformanceLogic } from './searchPerformanceLogic'import { SearchPerformanceTable } from './SearchPerformanceTable'export function SearchPerformanceDetail(): JSX.Element {- const { selectedRow, detailQuery, compareFilter, hasSearchConsole } = useValues(searchPerformanceLogic)+ const { selectedRow, detailQuery, detailSourceNotices, compareFilter, hasSearchConsole } =+ useValues(searchPerformanceLogic)const { selectRow } = useActions(searchPerformanceLogic)const organic = selectedRow?.platform === 'GoogleSearchConsole'const metricKeys: ('clicks' | 'impressions' | 'ctr' | 'position' | 'conversions')[] = [@@ -81,19 +82,26 @@ export function SearchPerformanceDetail(): JSX.Element {' Ad keywords can match different searches; these organic results are for the same text.'}</p></div>+ {detailSourceNotices.map(({ sourceId, message }) => (+ <LemonBanner+ key={sourceId}+ type="info"+ action={{ children: 'Manage source', to: urls.dataWarehouseSource(sourceId) }}+ >+ {message}+ </LemonBanner>+ ))}{detailQuery?.sources.length ? (<SearchPerformanceTablequery={detailQuery}metrics="traffic"queryKey="marketing-search-detail"/>- ) : (+ ) : !hasSearchConsole ? (<LemonBanner type="info">- {hasSearchConsole- ? 'Enable search_analytics_by_query_page in Google Search Console to see this breakdown.'- : 'Connect Google Search Console to see organic queries and landing pages.'}+ Connect Google Search Console to see organic queries and landing pages.</LemonBanner>- )}+ ) : null}{!hasSearchConsole && (<LemonButtontype="primary"diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsxindex 829b960ae85d..eb95ef182eeb 100644--- a/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx+++ b/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx@@ -33,6 +33,8 @@ const SOURCES = [id: `example-${name}`,name,should_sync: true,+ sync_frequency: '24hour',+ last_synced_at: '2025-02-14T12:00:00Z',status: 'Completed',table: { name: `example_${name}`, hogql_name: `example.${name}` },})@@ -48,6 +50,8 @@ const SOURCES = [id: `example-bing-${name}`,name,should_sync: true,+ sync_frequency: '24hour',+ last_synced_at: '2025-02-14T12:00:00Z',status: 'Completed',table: { name: `example_bing_${name}`, hogql_name: `example.bing_${name}` },})),@@ -63,6 +67,8 @@ const SOURCES = [id: `example-organic-${name}`,name,should_sync: true,+ sync_frequency: '24hour',+ last_synced_at: '2025-02-14T12:00:00Z',status: 'Completed',table: { name: `example_organic_${name}`, hogql_name: `example.organic_${name}` },})@@ -242,6 +248,7 @@ const meta: Meta<typeof SearchPerformanceTab> = {],parameters: {layout: 'fullscreen',+ mockDate: '2025-02-15T12:00:00Z',msw: { mocks: MOCKS },pageUrl: `${urls.marketingAnalyticsApp()}?tab=ad-performance&date_from=-7d`,featureFlags: [FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS],@@ -329,7 +336,7 @@ export const AwaitingSync: Story = {'/api/environments/:team_id/external_data_sources/': {results: SOURCES.map((source) => ({...source,- schemas: source.schemas.map((schema) => ({ ...schema, table: null })),+ schemas: source.schemas.map((schema) => ({ ...schema, table: null, last_synced_at: null })),})),count: SOURCES.length,next: null,@@ -340,6 +347,72 @@ export const AwaitingSync: Story = {},},}+export const StaleAggregate: Story = {+ parameters: {+ ...Comparison.parameters,+ msw: {+ mocks: {+ get: {+ '/api/environments/:team_id/external_data_sources/': {+ results: SOURCES.map((source) => ({+ ...source,+ schemas: source.schemas.map((schema) => ({+ ...schema,+ last_synced_at:+ schema.name === 'search_analytics_by_query'+ ? '2025-02-01T12:00:00Z'+ : schema.last_synced_at,+ })),+ })),+ count: SOURCES.length,+ next: null,+ previous: null,+ },+ },+ },+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(await canvas.findByText(/Showing query-and-page data instead/)).toBeVisible()+ await expect(await canvas.findByText('1,240')).toBeVisible()+ },+}+export const UnavailableSources: Story = {+ parameters: {+ ...Comparison.parameters,+ msw: {+ mocks: {+ get: {+ '/api/environments/:team_id/external_data_sources/': {+ results: SOURCES.map((source) => ({+ ...source,+ schemas: source.schemas.map((schema) => ({+ ...schema,+ should_sync: source.source_type !== 'GoogleAds',+ last_synced_at: source.source_type === 'BingAds' ? null : '2025-02-01T12:00:00Z',+ })),+ })),+ count: SOURCES.length,+ next: null,+ previous: null,+ },+ },+ },+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(await canvas.findByText(/Enable keyword and keyword_stats/)).toBeVisible()+ await expect(await canvas.findByText(/Waiting for the first sync/)).toBeVisible()+ await expect(await canvas.findByText(/out of date/)).toBeVisible()+ expect(canvas.queryByRole('table')).toBeNull()+ },+}+export const UnavailableSourcesNarrow: Story = {+ ...UnavailableSources,+ decorators: Narrow.decorators,+}export const OnlyGoogleAds: Story = {parameters: {msw: {diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceTab.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceTab.tsxindex 33daafd75a5c..8e87224ee42b 100644--- a/products/marketing_analytics/frontend/search/SearchPerformanceTab.tsx+++ b/products/marketing_analytics/frontend/search/SearchPerformanceTab.tsx@@ -12,7 +12,7 @@ import {import { urls } from 'scenes/urls'-import { SEARCH_PLATFORM_LABELS, SearchChannel, SearchPlatform, requiredSearchTables } from './searchPerformance'+import { SearchChannel } from './searchPerformance'import { SearchPerformanceDetail } from './SearchPerformanceDetail'import { searchPerformanceLogic } from './searchPerformanceLogic'import { SearchPerformanceTable } from './SearchPerformanceTable'@@ -25,7 +25,7 @@ export function SearchPerformanceTab(): JSX.Element {sourcesError,sources,allSearchSources,- pendingSources,+ sourceNotices,readySources,displayMetrics,hasPaidSources,@@ -86,13 +86,13 @@ export function SearchPerformanceTab(): JSX.Element {available under Keywords and queries.</LemonBanner>)}- {pendingSources.map((source) => (+ {sourceNotices.map(({ sourceId, message }) => (<LemonBanner- key={source.id}+ key={sourceId}type="info"- action={{ children: 'Manage source', to: urls.dataWarehouseSource(source.id) }}+ action={{ children: 'Manage source', to: urls.dataWarehouseSource(sourceId) }}>- {`${source.description || SEARCH_PLATFORM_LABELS[source.source_type as SearchPlatform]}: enable ${requiredSearchTables(source, breakdown)} and wait for the first sync to finish.`}+ {message}</LemonBanner>))}{sources.length === 0 && (hasActiveFilters || allSearchSources.length > 0) && (diff --git a/products/marketing_analytics/frontend/search/searchPerformance.test.ts b/products/marketing_analytics/frontend/search/searchPerformance.test.tsindex 4b78320059a7..ac0d8346b15b 100644--- a/products/marketing_analytics/frontend/search/searchPerformance.test.ts+++ b/products/marketing_analytics/frontend/search/searchPerformance.test.ts@@ -1,15 +1,21 @@-import { ExternalDataSource, ExternalDataSourceSchema } from '~/types'+import { dayjs } from 'lib/dayjs'-import { searchPerformanceSource, selectedSearchSources } from './searchPerformance'+import { ExternalDataSchemaStatus, ExternalDataSource, ExternalDataSourceSchema } from '~/types'++import { searchPerformanceSource, searchPerformanceSourceNotice, selectedSearchSources } from './searchPerformance'const schema = (name: string, shouldSync = true, synced = true): ExternalDataSourceSchema =>({name,should_sync: shouldSync,+ sync_frequency: '24hour',+ last_synced_at: synced ? dayjs('2025-02-14T12:00:00Z') : undefined,table: synced ? { name: `example_${name}`, hogql_name: `example.${name}` } : undefined,}) as ExternalDataSourceSchemadescribe('search performance sources', () => {+ beforeEach(() => jest.useFakeTimers().setSystemTime(new Date('2025-02-15T12:00:00Z')))+ afterEach(() => jest.useRealTimers())it.each([['GoogleAds',@@ -76,6 +82,67 @@ describe('search performance sources', () => {).toEqual(expected)})+ it.each([+ ['disabled', { should_sync: false }, 'Enable keyword_stats'],+ ['first sync with a materialized table', { last_synced_at: undefined }, 'first sync'],+ ['failed', { status: ExternalDataSchemaStatus.Failed }, 'failed'],+ ['paused', { status: ExternalDataSchemaStatus.Paused }, 'Syncing has stopped'],+ ['billing limit', { status: 'Billing limits' as ExternalDataSchemaStatus }, 'billing limit'],+ ['stale', { last_synced_at: dayjs('2025-02-10T12:00:00Z') }, 'out of date'],+ ])('excludes %s tables and explains how to fix them', (_, overrides, message) => {+ const source = {+ source_type: 'GoogleAds',+ schemas: [schema('keyword'), { ...schema('keyword_stats'), ...overrides }],+ } as ExternalDataSource+ expect(searchPerformanceSource(source)).toBeNull()+ expect(searchPerformanceSourceNotice(source)).toContain(message)+ })++ it.each(['keyword', 'page'] as const)('uses fresh query-page data instead of a stale %s aggregate', (breakdown) => {+ const source = {+ source_type: 'GoogleSearchConsole',+ schemas: [+ { ...schema('search_analytics_by_query'), last_synced_at: dayjs('2025-02-10T12:00:00Z') },+ { ...schema('search_analytics_by_page'), last_synced_at: dayjs('2025-02-10T12:00:00Z') },+ schema('search_analytics_by_query_page'),+ ],+ } as ExternalDataSource+ expect(searchPerformanceSource(source, breakdown)).toEqual({+ sourceType: 'GoogleSearchConsole',+ statsTable: 'example.search_analytics_by_query_page',+ queryPageTable: true,+ })+ expect(searchPerformanceSourceNotice(source, breakdown)).toContain('Showing query-and-page data instead')+ expect(searchPerformanceSourceNotice(source, breakdown)).toContain('Totals may differ')+ source.schemas[2].last_synced_at = dayjs('2025-02-10T12:00:00Z')+ expect(searchPerformanceSource(source, breakdown)).toBeNull()+ expect(searchPerformanceSource(source, breakdown, true)).toBeNull()+ expect(searchPerformanceSourceNotice(source, breakdown, true)).toContain('out of date')+ })++ it.each([+ ['24hour', '2025-02-13T12:00:00Z', true],+ ['24hour', '2025-02-13T11:59:59Z', false],+ ['7day', '2025-02-10T12:00:00Z', true],+ ['1hour', '2025-02-15T09:00:00Z', false],+ ['15min', '2025-02-15T11:29:00Z', false],+ [undefined, '2025-02-10T12:00:00Z', true],+ ])('uses each table cadence (%s) when the last successful sync is %s', (syncFrequency, lastSync, ready) => {+ const source = {+ source_type: 'BingAds',+ schemas: [+ {+ ...schema('keyword_performance_report'),+ sync_frequency: syncFrequency,+ last_synced_at: dayjs(lastSync),+ status: ExternalDataSchemaStatus.Running,+ },+ ],+ } as ExternalDataSource+ expect(searchPerformanceSource(source) !== null).toBe(ready)+ expect(searchPerformanceSourceNotice(source) === null).toBe(ready)+ })+it.each([[[], ['google-main', 'google-secondary', 'bing']],[['google-secondary'], ['google-secondary']],diff --git a/products/marketing_analytics/frontend/search/searchPerformance.ts b/products/marketing_analytics/frontend/search/searchPerformance.tsindex c3b9560ed4f7..2ca7525a2b79 100644--- a/products/marketing_analytics/frontend/search/searchPerformance.ts+++ b/products/marketing_analytics/frontend/search/searchPerformance.ts@@ -1,5 +1,7 @@+import { dayjs } from 'lib/dayjs'+import { MarketingAnalyticsSearchQuery, MarketingAnalyticsSearchSource } from '~/queries/schema/schema-general'-import { ExternalDataSource } from '~/types'+import { ExternalDataSource, ExternalDataSourceSchema } from '~/types'export type SearchPlatform = MarketingAnalyticsSearchSource['sourceType']export type SearchMetrics = 'traffic' | 'conversions'@@ -12,37 +14,112 @@ export const SEARCH_PLATFORM_LABELS: Record<SearchPlatform, string> = {GoogleSearchConsole: 'Google Search Console',}+type SearchTableStatus = 'ready' | 'disabled' | 'pending' | 'failed' | 'paused' | 'billing' | 'stale'++function searchTableStatus(schema: ExternalDataSourceSchema | undefined): SearchTableStatus {+ if (!schema?.should_sync) {+ return 'disabled'+ }+ if (schema.status && ['Billing limits', 'Billing limits too low'].includes(schema.status)) {+ return 'billing'+ }+ if (schema.status === 'Failed') {+ return 'failed'+ }+ if (schema.status === 'Paused' || schema.status === 'Cancelled') {+ return 'paused'+ }+ if (!schema.table || !schema.last_synced_at || !dayjs(schema.last_synced_at).isValid()) {+ return 'pending'+ }+ const interval = schema.sync_frequency?.match(/^(\d+)(min|hour|day)$/)+ if (interval) {+ const unit = interval[2] === 'min' ? 'minute' : interval[2] === 'hour' ? 'hour' : 'day'+ if (+ dayjs(schema.last_synced_at)+ .add(Number(interval[1]) * 2, unit)+ .isBefore(dayjs())+ ) {+ return 'stale'+ }+ }+ return 'ready'+}++function searchTableNames(source: ExternalDataSource, breakdown: SearchBreakdown, detail: boolean): string[] {+ if (source.source_type === 'GoogleSearchConsole') {+ return detail+ ? ['search_analytics_by_query_page']+ : [+ breakdown === 'page' ? 'search_analytics_by_page' : 'search_analytics_by_query',+ 'search_analytics_by_query_page',+ ]+ }+ if (source.source_type === 'GoogleAds') {+ return breakdown === 'page' ? ['landing_page_stats'] : ['keyword', 'keyword_stats']+ }+ return source.source_type === 'BingAds' && breakdown === 'keyword' ? ['keyword_performance_report'] : []+}+export function searchPerformanceSource(source: ExternalDataSource,breakdown: SearchBreakdown = 'keyword',detail = false): MarketingAnalyticsSearchSource | null {const table = (name: string): string | undefined => {- const schema = source.schemas.find((schema) => schema.name === name && schema.should_sync && schema.table)- return schema?.table?.hogql_name ?? schema?.table?.name+ const schema = source.schemas.find((schema) => schema.name === name)+ return searchTableStatus(schema) === 'ready' ? (schema?.table?.hogql_name ?? schema?.table?.name) : undefined}+ const tables = searchTableNames(source, breakdown, detail).map(table)if (source.source_type === 'GoogleSearchConsole') {- const queryPage = table('search_analytics_by_query_page')- const aggregate = detail- ? undefined- : table(breakdown === 'page' ? 'search_analytics_by_page' : 'search_analytics_by_query')- const statsTable = aggregate ?? queryPage- return statsTable ? { sourceType: 'GoogleSearchConsole', statsTable, queryPageTable: !aggregate } : null+ const index = tables.findIndex(Boolean)+ return index < 0+ ? null+ : { sourceType: 'GoogleSearchConsole', statsTable: tables[index]!, queryPageTable: detail || index === 1 }}- if (source.source_type === 'GoogleAds') {- if (breakdown === 'page') {- const statsTable = table('landing_page_stats')- return statsTable ? { sourceType: 'GoogleAds', statsTable } : null- }- const statsTable = table('keyword_stats')- const keywordTable = table('keyword')- return statsTable && keywordTable ? { sourceType: 'GoogleAds', statsTable, keywordTable } : null+ if (tables.length === 0 || tables.some((table) => !table)) {+ return null+ }+ return source.source_type === 'GoogleAds'+ ? {+ sourceType: 'GoogleAds',+ statsTable: tables[tables.length - 1]!,+ ...(breakdown === 'keyword' ? { keywordTable: tables[0] } : {}),+ }+ : { sourceType: 'BingAds', statsTable: tables[0]! }+}++export function searchPerformanceSourceNotice(+ source: ExternalDataSource,+ breakdown: SearchBreakdown = 'keyword',+ detail = false+): string | null {+ const querySource = searchPerformanceSource(source, breakdown, detail)+ const fallback = querySource?.queryPageTable && !detail+ if (querySource && !fallback) {+ return null}- if (source.source_type === 'BingAds' && breakdown === 'keyword') {- const statsTable = table('keyword_performance_report')- return statsTable ? { sourceType: 'BingAds', statsTable } : null+ const names = searchTableNames(source, breakdown, detail)+ const tablesByStatus = new Map<Exclude<SearchTableStatus, 'ready'>, string[]>()+ for (const name of names) {+ const status = searchTableStatus(source.schemas.find((schema) => schema.name === name))+ if (status !== 'ready') {+ tablesByStatus.set(status, [...(tablesByStatus.get(status) ?? []), name])+ }}- return null+ const issues = [...tablesByStatus].map(([status, tables]) => {+ const tableNames = tables.join(' and ')+ return {+ disabled: `Enable ${tableNames} in the source settings.`,+ pending: `Waiting for the first sync of ${tableNames} to finish.`,+ failed: `The sync of ${tableNames} failed. Retry it in the source settings.`,+ billing: `A billing limit is blocking the sync of ${tableNames}. Check the source settings.`,+ paused: `Syncing has stopped for ${tableNames}. Resume it in the source settings.`,+ stale: `Data in ${tableNames} is out of date. Sync it again in the source settings.`,+ }[status]+ })+ const label = source.description || SEARCH_PLATFORM_LABELS[source.source_type as SearchPlatform]+ return `${label}: ${issues.join(' ')}${fallback ? ' Showing query-and-page data instead. Totals may differ from the dedicated query or page table.' : ' Data from this source will appear when the tables are ready.'}`}export const SEARCH_SOURCE_TYPES = ['GoogleAds', 'BingAds', 'GoogleSearchConsole']@@ -52,16 +129,3 @@ export function selectedSearchSources(sources: ExternalDataSource[], selectedIdsconst selected = searchSources.filter((source) => selectedIds.includes(source.id))return selectedIds.length > 0 ? selected : searchSources}--export function requiredSearchTables(source: ExternalDataSource, breakdown: SearchBreakdown): string {- if (source.source_type === 'GoogleSearchConsole') {- return breakdown === 'page'- ? 'search_analytics_by_page or search_analytics_by_query_page'- : 'search_analytics_by_query or search_analytics_by_query_page'- }- return source.source_type === 'GoogleAds'- ? breakdown === 'page'- ? 'landing_page_stats'- : 'keyword and keyword_stats'- : 'keyword_performance_report'-}diff --git a/products/marketing_analytics/frontend/search/searchPerformanceLogic.ts b/products/marketing_analytics/frontend/search/searchPerformanceLogic.tsindex b2f7170deefd..29ecb2b2686a 100644--- a/products/marketing_analytics/frontend/search/searchPerformanceLogic.ts+++ b/products/marketing_analytics/frontend/search/searchPerformanceLogic.ts@@ -21,6 +21,7 @@ import {SearchPlatform,selectedSearchSources,searchPerformanceSource,+ searchPerformanceSourceNotice,} from './searchPerformance'export interface searchPerformanceLogicValues extends Pick<@@ -45,7 +46,9 @@ export interface searchPerformanceLogicValues extends Pick<querySearch: stringsourcesError: booleansources: ExternalDataSource[]- pendingSources: ExternalDataSource[]+ sourceNotices: { sourceId: string; message: string }[]+ detailSourceNotices: { sourceId: string; message: string }[]+ detailSources: ExternalDataSource[]readySources: MarketingAnalyticsSearchSource[]query: MarketingAnalyticsSearchQuery}@@ -154,10 +157,13 @@ export const searchPerformanceLogic = kea<searchPerformanceLogicType>([(breakdown !== 'page' || source.source_type !== 'BingAds')),],- pendingSources: [+ sourceNotices: [(s) => [s.sources, s.breakdown],- (sources: ExternalDataSource[], breakdown): ExternalDataSource[] =>- sources.filter((source) => !searchPerformanceSource(source, breakdown)),+ (sources: ExternalDataSource[], breakdown): { sourceId: string; message: string }[] =>+ sources.flatMap((source) => {+ const message = searchPerformanceSourceNotice(source, breakdown)+ return message ? [{ sourceId: source.id, message }] : []+ }),],readySources: [(s) => [s.sources, s.breakdown],@@ -194,22 +200,32 @@ export const searchPerformanceLogic = kea<searchPerformanceLogicType>([search,}),],+ detailSources: [+ (s) => [s.allSearchSources, s.integrationFilter, s.selectedRow],+ (allSources: ExternalDataSource[], integrationFilter, row): ExternalDataSource[] =>+ (row?.platform === 'GoogleSearchConsole'+ ? selectedSearchSources(allSources, integrationFilter.integrationSourceIds ?? [])+ : allSources+ ).filter((source) => source.source_type === 'GoogleSearchConsole'),+ ],+ detailSourceNotices: [+ (s) => [s.detailSources],+ (sources: ExternalDataSource[]): { sourceId: string; message: string }[] =>+ sources.flatMap((source) => {+ const message = searchPerformanceSourceNotice(source, 'keyword', true)+ return message ? [{ sourceId: source.id, message }] : []+ }),+ ],detailQuery: [- (s) => [s.allSearchSources, s.integrationFilter, s.selectedRow, s.query],- (allSources: ExternalDataSource[], integrationFilter, row, query): MarketingAnalyticsSearchQuery | null => {+ (s) => [s.detailSources, s.selectedRow, s.query],+ (sources: ExternalDataSource[], row, query): MarketingAnalyticsSearchQuery | null => {if (!row || !(row.page || row.keyword)) {return null}- const sources =- row.platform === 'GoogleSearchConsole'- ? selectedSearchSources(allSources, integrationFilter.integrationSourceIds ?? [])- : allSources- const detailSources = sources- .filter((source) => source.source_type === 'GoogleSearchConsole')- .flatMap((source) => {- const detailSource = searchPerformanceSource(source, row.page ? 'keyword' : 'page', true)- return detailSource ? [detailSource] : []- })+ const detailSources = sources.flatMap((source) => {+ const detailSource = searchPerformanceSource(source, row.page ? 'keyword' : 'page', true)+ return detailSource ? [detailSource] : []+ })return {...query,sources: detailSources,diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.pyindex d71a50442458..bd98bfe36ce4 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py@@ -1739,6 +1739,10 @@ class ExternalDataSchemaListSerializer(serializers.ModelSerializer):)status = serializers.SerializerMethodField(read_only=True, help_text="Current sync status for this schema.")+ sync_frequency = serializers.SerializerMethodField(+ read_only=True, help_text="How often this table is scheduled to sync, or null if no interval is set."+ )+class Meta:model = ExternalDataSchemafields = [@@ -1749,6 +1753,7 @@ class ExternalDataSchemaListSerializer(serializers.ModelSerializer):"status","sync_type","last_synced_at",+ "sync_frequency","latest_error","table",]@@ -1775,6 +1780,13 @@ class ExternalDataSchemaListSerializer(serializers.ModelSerializer):def get_status(self, schema: ExternalDataSchema) -> str | None:return schema_display_status(schema)+ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_sync_frequency(self, schema: ExternalDataSchema) -> str | None:+ try:+ return sync_frequency_interval_to_sync_frequency(schema.sync_frequency_interval)+ except ValueError:+ return None+def to_representation(self, instance: ExternalDataSchema) -> dict[str, Any]:ret = super().to_representation(instance)ret["latest_error"] = redact_schema_error(instance, self.context)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.pyindex 7f52437154c1..e92529e8a299 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py@@ -79,6 +79,7 @@ class TestBingAdsSource:def test_get_schemas(self):schemas = self.source.get_schemas(self.valid_config, self.team_id)+ assert next(schema for schema in schemas if schema.name == "keyword_performance_report").should_sync_defaultassert len(schemas) > 0diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/schemas.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/schemas.pyindex 6db881ec3562..dfe0699e3a7d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/schemas.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/schemas.py@@ -1233,7 +1233,7 @@ RESOURCE_SCHEMAS: dict[str, dict[str, Any]] = {"segments.ad_network_type",],"filter_field_names": [("segments.date", IncrementalFieldType.Date)],- "should_sync_default": False,+ "should_sync_default": True,"description": "This table fans out to every landing page URL per campaign and day, so it can get large for accounts with many final URLs.","extra_where": "metrics.impressions > 0","field_names": [diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.pyindex 7f6fca01495c..2dd96a0f83bc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py@@ -2093,10 +2093,9 @@ class TestCriterionTablesReachNegatives:class TestBreakdownStatsDefaultOff:- # These tables fan a day of spend out across placements, landing pages, product groups, hours and+ # These tables fan a day of spend out across placements, product groups, hours and# demographics, so they are orders of magnitude larger than the campaign and ad group reports.- # Defaulting one of them on would silently start syncing it for every account on the next schema- # reconcile, so each must stay opt-in and explain its size in the picker.+ # Keep them opt-in so new connections do not start these large imports without a table selection.@pytest.mark.parametrize("alias",[@@ -2107,7 +2106,6 @@ class TestBreakdownStatsDefaultOff:"campaign_hourly_stats","detail_placement_stats","gender_stats",- "landing_page_stats","location_stats","product_group_stats","user_location_stats",@@ -2120,3 +2118,8 @@ class TestBreakdownStatsDefaultOff:assert contents["should_sync_default"] is Falseassert contents["description"]++[email protected]("alias", ["keyword", "keyword_stats", "landing_page_stats"])+def test_search_performance_tables_are_preselected(alias: str) -> None:+ assert RESOURCE_SCHEMAS[alias].get("should_sync_default", True) is Truediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/settings.pyindex 29ba16185553..1d83196cf670 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/settings.py@@ -52,7 +52,7 @@ SEARCH_ANALYTICS_SCHEMAS: dict[str, SearchAnalyticsSchema] = {"search_analytics_by_query": {"dimensions": ["date", "query"],"primary_key": ["date", "query"],- "should_sync_default": False,+ "should_sync_default": True,"description": ("Daily performance broken out by search query (keyword). ""Sites with >50K distinct queries/day will lose long-tail keywords to API sampling."@@ -61,7 +61,7 @@ SEARCH_ANALYTICS_SCHEMAS: dict[str, SearchAnalyticsSchema] = {"search_analytics_by_page": {"dimensions": ["date", "page"],"primary_key": ["date", "page"],- "should_sync_default": False,+ "should_sync_default": True,"description": ("Daily performance broken out by landing page URL. ""Sites with >50K distinct landing pages/day will lose long-tail URLs to API sampling."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.pyindex 4313c53dcdb2..821330746a5b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py@@ -101,10 +101,13 @@ def test_property_schemas_are_not_incremental(name):def test_get_schemas_default_on_tables(config):schemas = GoogleSearchConsoleSource().get_schemas(config, team_id=1)by_default_on = {s.name for s in schemas if s.should_sync_default}- # Search analytics tables are opt-in apart from the most useful one; the property metadata- # tables are one cheap request each per sync, so they stay on. Picking an extra search type- # must never switch one on, since each table costs a full history backfill.- assert by_default_on == {"search_analytics_by_query_page", *PROPERTY_SCHEMAS.keys()}+ # Extra search types stay opt-in because each table needs its own full history backfill.+ assert by_default_on == {+ "search_analytics_by_query",+ "search_analytics_by_page",+ "search_analytics_by_query_page",+ *PROPERTY_SCHEMAS.keys(),+ }@pytest.mark.parametrize(diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex 64885fc9a509..edc4f55c0745 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -216,15 +216,29 @@ class TestExternalDataSource(APIBaseTest):# The sources list embeds every schema of every source, so it serializes a trimmed per-schema# shape (the fields the list UI reads); the single-source view keeps the full schema.source = self._make_source("trim")- self._make_schema_with_table(source, "Customers", row_count=42)+ schema = self._make_schema_with_table(source, "Customers", row_count=42)+ schema.sync_frequency_interval = timedelta(hours=6)+ schema.save(update_fields=["sync_frequency_interval"])list_response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/")self.assertEqual(list_response.status_code, 200)listed_schema = list_response.json()["results"][0]["schemas"][0]self.assertEqual(set(listed_schema.keys()),- {"id", "name", "label", "should_sync", "status", "sync_type", "last_synced_at", "latest_error", "table"},+ {+ "id",+ "name",+ "label",+ "should_sync",+ "status",+ "sync_type",+ "last_synced_at",+ "sync_frequency",+ "latest_error",+ "table",+ },)+ self.assertEqual(listed_schema["sync_frequency"], "6hour")self.assertEqual(listed_schema["table"]["row_count"], 42)self.assertEqual(listed_schema["table"]["name"], "Customers")# sync_type is kept for the PostHog Desktop app, which reads it from the list; without it the@@ -238,6 +252,13 @@ class TestExternalDataSource(APIBaseTest):self.assertIn("sync_type", detail_schema)self.assertIn("available_columns", detail_schema)+ ExternalDataSchema.objects.filter(team_id=self.team.pk, pk=schema.pk).update(+ sync_frequency_interval=timedelta(hours=7)+ )+ list_response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/")+ self.assertEqual(list_response.status_code, 200)+ self.assertIsNone(list_response.json()["results"][0]["schemas"][0]["sync_frequency"])+def test_list_source_status_and_latest_error_reflect_syncing_schemas(self):# `active_schemas` is derived in Python from the single schemas prefetch; the derived subset# must still drive the source-level status/error the same way the second prefetch did.