: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(data-warehouse): let the destination step turn every destination off (#113427)
Tom Owers41676822d011
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/components/DestinationStep.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/components/DestinationStep.tsxindex 77359800b003..3c2f22aef0ec 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/components/DestinationStep.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/components/DestinationStep.tsx@@ -41,6 +41,13 @@ export function DestinationStep(): JSX.Element {}const { openForCreate, openForEdit } = useActions(destinationModalLogic(modalProps))+ // A team with no destination rows yet has nothing to turn on, and its source writes to the+ // PostHog warehouse, so that case reads as warehouse-only rather than as nowhere to sync.+ const nothingSelected = destinations.length > 0 && selectedIds.length === 0+ const warehouseOnly =+ destinations.length === 0 ||+ !selectedIds.some((id) => destinations.find((d) => d.id === id)?.type !== 'PostHogWarehouse')+return (<div className="deprecated-space-y-4"><div className="flex gap-2 items-start justify-between">@@ -67,12 +74,18 @@ export function DestinationStep(): JSX.Element {/>{!destinationsLoading &&- !selectedIds.some((id) => destinations.find((d) => d.id === id)?.type !== 'PostHogWarehouse') && (- <LemonBanner type="info">- This source will sync into PostHog only. Turn on another destination to also send its tables to- your own database.+ (nothingSelected ? (+ <LemonBanner type="warning">+ This source has nowhere to sync. Turn on at least one destination to import it.</LemonBanner>- )}+ ) : (+ warehouseOnly && (+ <LemonBanner type="info">+ This source will sync into PostHog only. Turn on another destination to also send its tables+ to your own database.+ </LemonBanner>+ )+ ))}<DestinationModal {...modalProps} /></div>diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepLogic.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepLogic.tsindex 3272944178f1..afe8e1451932 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepLogic.ts+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepLogic.ts@@ -21,6 +21,9 @@ export interface destinationStepLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface destinationStepLogicActions {+ setWizardAvailableDestinationCount: (count: number) => {+ count: number+ } // sourceWizardLogicsetWizardDestinationIds: (destinationIds: string[]) => {destinationIds: string[]} // sourceWizardLogic@@ -65,7 +68,7 @@ export const destinationStepLogic = kea<destinationStepLogicType>([path(['products', 'data_warehouse', 'frontend', 'scenes', 'NewSourceScene', 'destinationStepLogic']),connect(() => ({values: [teamLogic, ['currentTeamId'], sourceWizardLogic, ['wizardDestinationIds']],- actions: [sourceWizardLogic, ['setWizardDestinationIds']],+ actions: [sourceWizardLogic, ['setWizardDestinationIds', 'setWizardAvailableDestinationCount']],})),actions({toggleDestination: (destinationId: string) => ({ destinationId }),@@ -102,6 +105,9 @@ export const destinationStepLogic = kea<destinationStepLogicType>([selectDefault: () => {actions.setWizardDestinationIds(defaultDestinationIds(values.destinations, values.wizardDestinationIds))},+ loadDestinationsSuccess: ({ destinations }: { destinations: ExternalDataDestinationApi[] }) => {+ actions.setWizardAvailableDestinationCount(destinations.length)+ },})),afterMount(({ actions }: any) => {actions.loadDestinations()diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.test.tsindex 33fe30d70362..c57afe91e744 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.test.ts+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.test.ts@@ -1,4 +1,9 @@-import { defaultDestinationIds, shouldShowDestinationStep, toggleDestinationId } from './destinationStepUtils'+import {+ defaultDestinationIds,+ destinationStepBlockReason,+ shouldShowDestinationStep,+ toggleDestinationId,+} from './destinationStepUtils'const WAREHOUSE = { id: 'wh', is_posthog_warehouse: true }const POSTGRES = { id: 'pg', is_posthog_warehouse: false }@@ -60,6 +65,16 @@ describe('destination step', () => {})})+ describe('destinationStepBlockReason', () => {+ it.each([+ ['every destination is turned off', 2, [], 'Pick at least one destination'],+ ['one destination is on', 2, ['wh'], null],+ ['the team has no destinations to pick from', 0, [], null],+ ])('reports %s', (_label, availableCount, selectedIds, expected) => {+ expect(destinationStepBlockReason(availableCount as number, selectedIds as string[])).toEqual(expected)+ })+ })+describe('toggleDestinationId', () => {it('adds one that is off', () => {expect(toggleDestinationId(['wh'], 'pg')).toEqual(['wh', 'pg'])diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.tsindex 940d1019adc0..6da812c4143f 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.ts+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/components/destinationStepUtils.ts@@ -42,6 +42,20 @@ export function defaultDestinationIds(return warehouse ? [warehouse.id] : []}+/**+ * Why the wizard cannot create the source yet, or null when it can.+ *+ * The toggles stay free, so the warehouse can go off before another destination goes on, which+ * leaves the Import button to hold the rule. A team with no destination rows yet has nothing to+ * pick, and its source writes to the PostHog warehouse, so the step does not block there.+ */+export function destinationStepBlockReason(availableCount: number, selectedIds: string[]): string | null {+ if (availableCount === 0 || selectedIds.length > 0) {+ return null+ }+ return 'Pick at least one destination'+}+/** Adding or removing one destination from the picked set. */export function toggleDestinationId(current: string[], destinationId: string): string[] {return current.includes(destinationId) ? current.filter((id) => id !== destinationId) : [...current, destinationId]diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsxindex b2a133270805..a73ba746c0b3 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx@@ -53,7 +53,7 @@ import type { WebhookCreateResult } from '../../shared/components/forms/WebhookSimport { sourceManagementLogic } from '../../shared/logics/sourceManagementLogic'import { clonePayloadPreservingFiles, findUploadedFiles, readJsonFile } from '../../shared/sourceFieldFiles'import { MANUAL_LINK_SOURCE_LABELS } from '../../shared/storageProvider'-import { shouldShowDestinationStep } from './components/destinationStepUtils'+import { destinationStepBlockReason, shouldShowDestinationStep } from './components/destinationStepUtils'import { FILE_UPLOAD_SOURCE_CONFIG, FILE_UPLOAD_SOURCE_NAME } from './fileUploadSource'import { selfManagedSourceLogic } from './selfManagedSourceLogic'import { restoreSourceFormState, saveSourceFormState } from './wizardFormStorage'@@ -522,6 +522,7 @@ export interface sourceWizardLogicValues {webhookFieldInputsValidationErrors: DeepPartialMap<Record<string, any>, ValidationErrorType>webhookResult: WebhookCreateResult | nullwebhookStepComplete: boolean+ wizardAvailableDestinationCount: numberwizardDestinationIds: string[]}@@ -755,6 +756,9 @@ export interface sourceWizardLogicActions {setWebhookResult: (result: WebhookCreateResult | null) => {result: WebhookCreateResult | null}+ setWizardAvailableDestinationCount: (count: number) => {+ count: number+ }setWizardDestinationIds: (destinationIds: string[]) => {destinationIds: string[]}@@ -913,14 +917,18 @@ export interface sourceWizardLogicMeta {isManualLinkingSelected: boolean,databaseSchema: ExternalDataSourceSyncSchema[],isDirectQueryMode: boolean,- webhookStepComplete: boolean+ webhookStepComplete: boolean,+ wizardAvailableDestinationCount: number,+ wizardDestinationIds: string[]) => booleannextButtonDisabledReason: (currentStep: number,isManualLinkingSelected: boolean,databaseSchema: ExternalDataSourceSyncSchema[],isDirectQueryMode: boolean,- webhookStepComplete: boolean+ webhookStepComplete: boolean,+ wizardAvailableDestinationCount: number,+ wizardDestinationIds: string[]) => string | nullshowSkipButton: (currentStep: number) => booleannextButtonText: (@@ -1027,6 +1035,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([onNext: true,onSubmit: true,setWizardDestinationIds: (destinationIds: string[]) => ({ destinationIds }),+ setWizardAvailableDestinationCount: (count: number) => ({ count }),resetSourceForm: (accessMethod?: 'warehouse' | 'direct') => ({ accessMethod }),setDatabaseSchemas: (schemas: ExternalDataSourceSyncSchema[]) => ({schemas,@@ -1153,6 +1162,15 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([onClear: () => [],},],+ // Reported by the destination step once its list resolves. The Import button needs it to+ // tell "turned every destination off" apart from "this team has no destinations yet".+ wizardAvailableDestinationCount: [+ 0,+ {+ setWizardAvailableDestinationCount: (_, { count }) => count,+ onClear: () => 0,+ },+ ],currentStep: [1,{@@ -1563,13 +1581,17 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([s.databaseSchema,s.isDirectQueryMode,s.webhookStepComplete,+ s.wizardAvailableDestinationCount,+ s.wizardDestinationIds,],(currentStep: number,isManualLinkingSelected: boolean,databaseSchema: ExternalDataSourceSyncSchema[],isDirectQueryMode: boolean,- webhookStepComplete: boolean+ webhookStepComplete: boolean,+ wizardAvailableDestinationCount: number,+ wizardDestinationIds: string[]): boolean => {if (isManualLinkingSelected && currentStep === 1) {return false@@ -1591,6 +1613,10 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([return webhookStepComplete}+ if (currentStep === WIZARD_DESTINATION_STEP) {+ return destinationStepBlockReason(wizardAvailableDestinationCount, wizardDestinationIds) === null+ }+return true},],@@ -1601,13 +1627,17 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([s.databaseSchema,s.isDirectQueryMode,s.webhookStepComplete,+ s.wizardAvailableDestinationCount,+ s.wizardDestinationIds,],(currentStep: number,isManualLinkingSelected: boolean,databaseSchema: ExternalDataSourceSyncSchema[],isDirectQueryMode: boolean,- webhookStepComplete: boolean+ webhookStepComplete: boolean,+ wizardAvailableDestinationCount: number,+ wizardDestinationIds: string[]): string | null => {if (!isManualLinkingSelected && currentStep === 3) {const tablesToSync = databaseSchema.filter((n) => n.should_sync)@@ -1624,6 +1654,10 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([return 'Finish setting up the webhook to continue'}+ if (currentStep === WIZARD_DESTINATION_STEP) {+ return destinationStepBlockReason(wizardAvailableDestinationCount, wizardDestinationIds)+ }+return null},],diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.tsindex 96320439d084..d21b973b552d 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts@@ -22,6 +22,7 @@ import {resolveConnectErrorMessage,shouldHydrateSourceFromUrl,sourceWizardLogic,+ WIZARD_DESTINATION_STEP,} from '../sourceWizardLogic'function buildSourceConfig(overrides: Partial<SourceConfigResponseApi>): SourceConfigResponseApi {@@ -1134,6 +1135,26 @@ describe('sourceWizardLogic', () => {unmount()}})++ it('blocks Import on the destination step until one destination is turned on', () => {+ const { logic, unmount } = mountWithSchemas([+ buildSchema({ table: 'Customer', should_sync: true, sync_type: 'full_refresh' }),+ ])++ try {+ logic.actions.setStep(WIZARD_DESTINATION_STEP)+ logic.actions.setWizardAvailableDestinationCount(2)+ logic.actions.setWizardDestinationIds([])+ expect(logic.values.canGoNext).toBe(false)+ expect(logic.values.nextButtonDisabledReason).toEqual('Pick at least one destination')++ logic.actions.setWizardDestinationIds(['warehouse-id'])+ expect(logic.values.canGoNext).toBe(true)+ expect(logic.values.nextButtonDisabledReason).toBeNull()+ } finally {+ unmount()+ }+ })})// Onboarding one-click setup: autoConfigureTables opts every syncable table in so the userdiff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/DestinationsTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/DestinationsTab.tsxindex af4245c3d018..81b2b4cec381 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/DestinationsTab.tsx+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/DestinationsTab.tsx@@ -17,8 +17,13 @@ export interface DestinationsTabProps {export function DestinationsTab({ id }: DestinationsTabProps): JSX.Element {const logic = destinationsLogic({ sourceId: id })- const { destinations, destinationsLoading, attachedDestinationIds, savedDestinationIdsLoading, canSave } =- useValues(logic)+ const {+ destinations,+ destinationsLoading,+ attachedDestinationIds,+ savedDestinationIdsLoading,+ saveDisabledReason,+ } = useValues(logic)const { toggleDestination, save, loadDestinations, setAttached } = useActions(logic)const modalProps = {@@ -72,7 +77,7 @@ export function DestinationsTab({ id }: DestinationsTabProps): JSX.Element {type="primary"onClick={save}loading={savedDestinationIdsLoading}- disabledReason={canSave ? undefined : 'No changes to save'}+ disabledReason={saveDisabledReason ?? undefined}data-attr="warehouse-destinations-save">Save destinationsdiff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/destinationsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/destinationsLogic.tsindex c967263bb257..663a243ac580 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/destinationsLogic.ts+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/destinationsLogic.ts@@ -26,10 +26,10 @@ export interface destinationsLogicValues {currentTeamId: number | null // teamLogicaddedDestinationIds: string[]attachedDestinationIds: string[]- canSave: booleandestinations: ExternalDataDestinationApi[]destinationsLoading: booleanhasUnsavedChanges: boolean+ saveDisabledReason: string | nullsavedDestinationIds: string[]savedDestinationIdsLoading: booleansourceSchemas: ExternalDataSourceSchema[]@@ -118,7 +118,7 @@ export interface destinationsLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {hasUnsavedChanges: (attachedDestinationIds: string[], savedDestinationIds: string[]) => boolean- canSave: (attachedDestinationIds: string[], hasUnsavedChanges: boolean) => boolean+ saveDisabledReason: (attachedDestinationIds: string[], hasUnsavedChanges: boolean) => string | nulladdedDestinationIds: (attachedDestinationIds: string[], savedDestinationIds: string[]) => string[]syncedSchemas: (sourceSchemas: ExternalDataSourceSchema[]) => ExternalDataSourceSchema[]}@@ -206,9 +206,14 @@ export const destinationsLogic = kea<destinationsLogicType>([(attached: string[], saved: string[]): boolean =>attached.length !== saved.length || attached.some((id: string) => !saved.includes(id)),],- canSave: [+ saveDisabledReason: [(s) => [s.attachedDestinationIds, s.hasUnsavedChanges],- (attached: string[], hasUnsavedChanges: boolean): boolean => hasUnsavedChanges && attached.length > 0,+ (attached: string[], hasUnsavedChanges: boolean): string | null => {+ if (attached.length === 0) {+ return 'Pick at least one destination'+ }+ return hasUnsavedChanges ? null : 'No changes to save'+ },],// A destination added now holds none of the history already synced, so these are the ones// that make a resync necessary. Removing one never does.diff --git a/products/data_warehouse/frontend/shared/components/DestinationList.stories.tsx b/products/data_warehouse/frontend/shared/components/DestinationList.stories.tsxindex 422b786fabd8..651c76a3e14e 100644--- a/products/data_warehouse/frontend/shared/components/DestinationList.stories.tsx+++ b/products/data_warehouse/frontend/shared/components/DestinationList.stories.tsx@@ -46,7 +46,6 @@ BothSelected.args = {onEdit: () => {},}-// The last one on cannot be turned off, so a source can never end up syncing nowhere.export const OnlyOneLeft = Template.bind({})OnlyOneLeft.args = {...BothSelected.args,diff --git a/products/data_warehouse/frontend/shared/components/DestinationList.tsx b/products/data_warehouse/frontend/shared/components/DestinationList.tsxindex 9e0062ba5a99..3e229d782972 100644--- a/products/data_warehouse/frontend/shared/components/DestinationList.tsx+++ b/products/data_warehouse/frontend/shared/components/DestinationList.tsx@@ -34,10 +34,6 @@ export function DestinationList({toggleDisabledReason,metricsSourceId,}: DestinationListProps): JSX.Element {- // Turning the last one off would leave the source syncing nowhere, which is what disabling a- // table is for. Pin it on rather than letting the save fail.- const isLastSelected = (id: string): boolean => selectedIds.length === 1 && selectedIds[0] === id-const columns: LemonTableColumn<ExternalDataDestinationApi, any>[] = [{title: '',@@ -116,16 +112,14 @@ export function DestinationList({destination.is_posthog_warehouse ? 'The PostHog warehouse is managed for you' : undefined}/>+ {/* Every toggle stays free, the last one on included, so a person can turn the+ warehouse off before turning another destination on. The caller's save button+ rejects an empty set. */}<LemonSwitchchecked={selectedIds.includes(destination.id)}onChange={() => onToggle(destination.id)}data-attr="warehouse-destination-toggle"- disabledReason={- toggleDisabledReason ??- (isLastSelected(destination.id)- ? 'Pick at least one destination. To stop syncing, turn off syncing instead.'- : undefined)- }+ disabledReason={toggleDisabledReason}/></div>),diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.pyindex 3908e2750695..0606340f85e6 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py@@ -74,7 +74,10 @@ from products.warehouse_sources.backend.facade.source_management import (validate_and_coerce_row_filters,)from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind, ExternalDataSourceType-from products.warehouse_sources.backend.presentation.views.destination_links import set_source_destinations+from products.warehouse_sources.backend.presentation.views.destination_links import (+ EMPTY_SET_MESSAGE,+ set_source_destinations,+)from products.warehouse_sources.backend.presentation.views.external_data_schema import (ExternalDataSchemaListSerializer,ExternalDataSchemaSerializer,@@ -788,6 +791,16 @@ class ExternalDataSourceCreateSerializer(serializers.Serializer):),)+ def validate_destination_ids(self, destination_ids: list) -> list:+ # An explicit empty list means the caller turned every destination off, which would leave+ # the source syncing nowhere. Rejected here, before the source is created, because+ # `set_source_destinations` runs after creation and swallows its own failures so that a bad+ # destination set never costs the user the source. Omitting the field keeps its meaning of+ # "the PostHog warehouse", which is what callers written before destinations existed send.+ if not destination_ids:+ raise serializers.ValidationError(EMPTY_SET_MESSAGE)+ return destination_ids+class SourceSetupSerializer(serializers.Serializer):source_type = serializers.ChoiceField(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 026aa4312bd0..b362edfd7ed8 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@@ -486,6 +486,28 @@ class TestExternalDataSource(APIBaseTest):assert link.enabled is Trueassert link.destination.type == ExternalDataDestination.Type.POSTHOG_WAREHOUSE+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(True, None),+ )+ def test_create_rejects_an_empty_destination_set_before_creating_the_source(self, _mock_validate):+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/",+ data={+ "source_type": "Stripe",+ "created_via": "web",+ "destination_ids": [],+ "payload": {+ "auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"},+ "schemas": [{"name": "Customer", "should_sync": True, "sync_type": "full_refresh"}],+ },+ },+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert "at least one destination" in response.json()["detail"]+ assert not ExternalDataSource.objects.filter(team_id=self.team.pk).exists()+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",side_effect=AttributeError("boom"),