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.

feat(data-warehouse): bulk enable schemas with default sync settings (#71652)

estefania3cf5801410d4
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index b4041da724fa..9f98c1560f45 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -5922,7 +5922,10 @@ const api = {
sourceId: ExternalDataSource['id'],
// Callers send a minimal diff — only `id` is required; the backend writes just the fields
// present and leaves the rest untouched. (Matches `externalDataSchemas.update`'s shape.)
- schemas: (Partial<ExternalDataSourceSchema> & Pick<ExternalDataSourceSchema, 'id'>)[]
+ // `apply_sync_defaults` asks the backend to discover and fill in default sync settings
+ // for schemas that have no sync method configured yet.
+ schemas: (Partial<ExternalDataSourceSchema> &
+ Pick<ExternalDataSourceSchema, 'id'> & { apply_sync_defaults?: boolean })[]
): Promise<ExternalDataSourceSchema[]> {
return await new ApiRequest().externalDataSource(sourceId).withAction('bulk_update_schemas').update({
data: { schemas },
diff --git a/products/data_warehouse/backend/presentation/views/external_data_schema.py b/products/data_warehouse/backend/presentation/views/external_data_schema.py
index cd83e1913ccb..4b5f7a3749fd 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_schema.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_schema.py
@@ -1137,6 +1137,11 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
if self._webhook_only_check_applies():
self._is_webhook_only_schema_cached(instance)
+ def seed_webhook_only_check(self, webhook_only: bool) -> None:
+ """Pre-fill the webhook-only cache when the caller already discovered this table (e.g.
+ bulk sync-defaults filling), so warm_webhook_only_check doesn't re-probe the source."""
+ self.__dict__["_webhook_only_result"] = webhook_only
+
def _webhook_only_check_applies(self) -> bool:
# Single source of truth for when the webhook-only check runs, so update() and the
# pre-transaction warm step can't drift apart and push the network call back into the
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.py
index 67b0b343c230..cfa88aeb2c31 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_source.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py
@@ -151,6 +151,7 @@ from products.warehouse_sources.backend.facade.source_management import (
SSLRequiredError,
WebhookSource,
build_default_schemas,
+ build_default_sync_settings,
cdc_pg_connection,
draft_manifest_sync,
fetch_docs_text,
@@ -607,6 +608,15 @@ class ExternalDataSourceBulkUpdateSchemaSerializer(serializers.Serializer):
allow_null=True,
help_text="Row-filter predicates ANDed onto the source query. Null/empty means sync all rows.",
)
+ apply_sync_defaults = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "When true and the schema has no sync method configured yet (and this update does not set "
+ "one), discover the table on the source and fill in default sync settings: incremental sync "
+ "with an auto-selected tracking column where supported, otherwise append, otherwise full "
+ "refresh. Ignored for schemas that already have a sync method."
+ ),
+ )
class ExternalDataSourceBulkUpdateSchemasSerializer(serializers.Serializer):
@@ -4570,6 +4580,70 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
return Response(status=status.HTTP_200_OK, data={"success": True})
+ def _fill_default_sync_settings(
+ self,
+ source: ExternalDataSource,
+ schema_updates: list[dict[str, Any]],
+ source_schemas_by_id: dict[uuid.UUID, ExternalDataSchema],
+ ) -> tuple[dict[str, tuple[str, str]], set[str]]:
+ """Fill default sync settings into bulk-update items that ask for them.
+
+ Items with ``apply_sync_defaults`` targeting a schema that has no sync method yet (and
+ whose update doesn't set one) get their sync settings discovered from the source — one
+ discovery call for the whole batch. Returns per-schema failures (dropped tables,
+ webhook-only tables, discovery errors) for the caller to skip and report, plus the ids
+ of the schemas whose settings were filled in.
+ """
+ needing_defaults = [
+ schema_update
+ for schema_update in schema_updates
+ if schema_update.get("apply_sync_defaults")
+ and schema_update.get("sync_type") is None
+ and source_schemas_by_id[schema_update["id"]].sync_type is None
+ ]
+ # Direct-query sources have no sync method to configure — enabling is just should_sync.
+ if not needing_defaults or not source.supports_scheduled_sync:
+ return {}, set()
+
+ failures: dict[str, tuple[str, str]] = {}
+ names = [source_schemas_by_id[schema_update["id"]].name for schema_update in needing_defaults]
+ try:
+ source_impl = SourceRegistry.get_source(ExternalDataSourceType(source.source_type))
+ config = source_impl.parse_config(source.job_inputs)
+ discovered = source_impl.get_schemas(config, self.team_id, names=names)
+ except Exception as e:
+ capture_exception(e)
+ reason = "could not read the source to pick default sync settings; check the source credentials"
+ for schema_update in needing_defaults:
+ schema = source_schemas_by_id[schema_update["id"]]
+ failures[str(schema.id)] = (schema.name, reason)
+ return failures, set()
+
+ # Not every source honors the `names` filter, so match by name instead of order.
+ discovered_by_name = {discovered_schema.name: discovered_schema for discovered_schema in discovered}
+ defaulted_schema_ids: set[str] = set()
+ for schema_update in needing_defaults:
+ schema = source_schemas_by_id[schema_update["id"]]
+ discovered_schema = discovered_by_name.get(schema.name)
+ if discovered_schema is None:
+ failures[str(schema.id)] = (
+ schema.name,
+ "not found on the source; pull new schemas to refresh the table list",
+ )
+ continue
+ if discovered_schema.webhook_only:
+ failures[str(schema.id)] = (
+ schema.name,
+ "can only be synced via webhooks; set up the webhook sync method instead",
+ )
+ continue
+ for key, value in build_default_sync_settings(discovered_schema).items():
+ # A caller-sent value wins; None (missing or explicit null) means "not set".
+ if schema_update.get(key) is None:
+ schema_update[key] = value
+ defaulted_schema_ids.add(str(schema.id))
+ return failures, defaulted_schema_ids
+
@extend_schema(
request=ExternalDataSourceBulkUpdateSchemasSerializer,
responses={200: ExternalDataSchemaSerializer(many=True)},
@@ -4596,6 +4670,14 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
if len(source_schemas_by_id) != len(schema_ids):
raise ValidationError("One or more schemas could not be found for this source")
+ # Items that ask for sync defaults on a not-yet-configured schema get them discovered and
+ # filled in up front. Tables that can't get defaults (dropped from the source, webhook-only)
+ # fail individually and are skipped below, without blocking the rest of the batch.
+ failed_schemas, defaulted_schema_ids = self._fill_default_sync_settings(
+ source, schema_updates, source_schemas_by_id
+ )
+ only_validation_errors = True
+
serializer_context = self.get_serializer_context()
updated_schemas: list[ExternalDataSchema] = []
# Each deferred action is paired with its schema so a post-commit failure can be attributed.
@@ -4608,7 +4690,11 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
for schema_update in schema_updates:
schema_id = schema_update["id"]
schema = source_schemas_by_id[schema_id]
- schema_payload = {key: value for key, value in schema_update.items() if key != "id"}
+ if str(schema.id) in failed_schemas:
+ continue
+ schema_payload = {
+ key: value for key, value in schema_update.items() if key not in ("id", "apply_sync_defaults")
+ }
schema_post_commit_actions: list[Callable[[], None]] = []
schema_serializer = ExternalDataSchemaSerializer(
@@ -4618,6 +4704,10 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
context={**serializer_context, "post_commit_actions": schema_post_commit_actions},
)
schema_serializer.is_valid(raise_exception=True)
+ if str(schema.id) in defaulted_schema_ids:
+ # Defaults discovery already confirmed these tables aren't webhook-only; seed the
+ # cache so the warm step below doesn't re-probe the source once per schema.
+ schema_serializer.seed_webhook_only_check(False)
# Do the webhook-only source-discovery call (e.g. Google Ads token refresh + field query)
# here, before the per-schema transaction below. Running it inside update()'s transaction
# held the DB connection idle-in-transaction long enough for the server to close it.
@@ -4629,8 +4719,6 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
# meant one schema's failure rolled back every schema and failed the request, so the user
# got nothing applied. Isolating per schema keeps the ones that saved committed, attempts
# every schema so a single bad one can't block the rest, and reports the failures together.
- failed_schemas: dict[str, tuple[str, str]] = {}
- only_validation_errors = True
for schema, schema_serializer, schema_post_commit_actions in prepared:
try:
with transaction.atomic():
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.py
index fb9ccb71de5c..5d1fd1dffef1 100644
--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py
+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py
@@ -1156,6 +1156,227 @@ class TestExternalDataSource(APIBaseTest):
schema.refresh_from_db()
assert schema.sync_type == ExternalDataSchema.SyncType.WEBHOOK
+ @patch(
+ "products.data_warehouse.backend.presentation.views.external_data_schema.external_data_workflow_exists",
+ return_value=False,
+ )
+ def test_bulk_update_schemas_apply_sync_defaults_fills_settings_from_source(self, _mock_workflow_exists):
+ # `apply_sync_defaults` on a schema with no sync method: one discovery call fills in the
+ # default sync settings and the schema is enabled with them. Without this the request
+ # would 400 with "Sync type must be set up first before enabling schema".
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema as _SourceSchema,
+ )
+ from products.warehouse_sources.backend.types import IncrementalFieldType
+
+ source = self._create_external_data_source()
+ schema = ExternalDataSchema.objects.create(
+ name="Customer",
+ team_id=self.team.pk,
+ source=source,
+ should_sync=False,
+ sync_type=None,
+ )
+
+ discovered = [
+ _SourceSchema(
+ name="Customer",
+ supports_incremental=True,
+ supports_append=True,
+ incremental_fields=[
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ "nullable": False,
+ }
+ ],
+ detected_primary_keys=["id"],
+ )
+ ]
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.get_schemas",
+ return_value=discovered,
+ ) as mock_get_schemas,
+ patch(
+ "products.data_warehouse.backend.presentation.views.external_data_schema.sync_external_data_job_workflow"
+ ) as mock_sync_workflow,
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/bulk_update_schemas",
+ data={"schemas": [{"id": str(schema.id), "should_sync": True, "apply_sync_defaults": True}]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()[0]["should_sync"] is True
+ assert response.json()[0]["sync_type"] == "incremental"
+
+ schema.refresh_from_db()
+ assert schema.should_sync is True
+ assert schema.sync_type == ExternalDataSchema.SyncType.INCREMENTAL
+ assert schema.sync_type_config.get("incremental_field") == "updated_at"
+ assert schema.sync_type_config.get("incremental_field_type") == "datetime"
+ assert schema.sync_type_config.get("primary_key_columns") == ["id"]
+
+ # One discovery round-trip for the whole batch — the webhook-only warm check reuses it.
+ assert mock_get_schemas.call_count == 1
+ assert mock_get_schemas.call_args.kwargs.get("names") == ["Customer"]
+ # The newly enabled schema gets its Temporal schedule created.
+ assert mock_sync_workflow.call_count == 1
+ assert mock_sync_workflow.call_args.kwargs == {"create": True, "should_sync": True}
+
+ @patch(
+ "products.data_warehouse.backend.presentation.views.external_data_schema.external_data_workflow_exists",
+ return_value=False,
+ )
+ def test_bulk_update_schemas_apply_sync_defaults_webhook_only_fails_only_that_schema(self, _mock_workflow_exists):
+ # A webhook-only table can't be enabled with polling defaults: it fails with a clear
+ # reason while the rest of the batch is still applied.
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema as _SourceSchema,
+ )
+
+ source = self._create_external_data_source()
+ webhook_only_schema = ExternalDataSchema.objects.create(
+ name="Discount", team_id=self.team.pk, source=source, should_sync=False, sync_type=None
+ )
+ normal_schema = ExternalDataSchema.objects.create(
+ name="Customer", team_id=self.team.pk, source=source, should_sync=False, sync_type=None
+ )
+
+ discovered = [
+ _SourceSchema(
+ name="Discount",
+ supports_incremental=False,
+ supports_append=False,
+ supports_webhooks=True,
+ webhook_only=True,
+ ),
+ _SourceSchema(name="Customer", supports_incremental=False, supports_append=False),
+ ]
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.get_schemas",
+ return_value=discovered,
+ ),
+ patch(
+ "products.data_warehouse.backend.presentation.views.external_data_schema.sync_external_data_job_workflow"
+ ),
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/bulk_update_schemas",
+ data={
+ "schemas": [
+ {"id": str(webhook_only_schema.id), "should_sync": True, "apply_sync_defaults": True},
+ {"id": str(normal_schema.id), "should_sync": True, "apply_sync_defaults": True},
+ ]
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ detail = response.json()["detail"]
+ assert "Discount" in detail
+ assert "webhooks" in detail
+
+ webhook_only_schema.refresh_from_db()
+ normal_schema.refresh_from_db()
+ assert webhook_only_schema.should_sync is False
+ assert webhook_only_schema.sync_type is None
+ assert normal_schema.should_sync is True
+ assert normal_schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH
+
+ @patch(
+ "products.data_warehouse.backend.presentation.views.external_data_schema.external_data_workflow_exists",
+ return_value=True,
+ )
+ def test_bulk_update_schemas_apply_sync_defaults_discovery_failure_spares_other_items(self, _mock_workflow_exists):
+ # An unreachable source fails only the items that needed discovery; items that don't
+ # need defaults still apply.
+ source = self._create_external_data_source()
+ unconfigured_schema = ExternalDataSchema.objects.create(
+ name="Customer", team_id=self.team.pk, source=source, should_sync=False, sync_type=None
+ )
+ configured_schema = ExternalDataSchema.objects.create(
+ name="Invoice",
+ team_id=self.team.pk,
+ source=source,
+ should_sync=False,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ )
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.get_schemas",
+ side_effect=requests.ConnectionError("connection refused"),
+ ),
+ patch(
+ "products.data_warehouse.backend.presentation.views.external_data_schema.unpause_external_data_schedule"
+ ) as mock_unpause,
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/bulk_update_schemas",
+ data={
+ "schemas": [
+ {"id": str(unconfigured_schema.id), "should_sync": True, "apply_sync_defaults": True},
+ {"id": str(configured_schema.id), "should_sync": True},
+ ]
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ detail = response.json()["detail"]
+ assert "Customer" in detail
+ assert "could not read the source" in detail
+
+ unconfigured_schema.refresh_from_db()
+ configured_schema.refresh_from_db()
+ assert unconfigured_schema.should_sync is False
+ assert configured_schema.should_sync is True
+ assert mock_unpause.call_count == 1
+
+ @patch(
+ "products.data_warehouse.backend.presentation.views.external_data_schema.external_data_workflow_exists",
+ return_value=True,
+ )
+ def test_bulk_update_schemas_apply_sync_defaults_noop_for_configured_schema(self, _mock_workflow_exists):
+ # A schema that already has a sync method is just re-enabled: no discovery round-trip,
+ # and its existing sync settings are not clobbered by defaults.
+ source = self._create_external_data_source()
+ schema = ExternalDataSchema.objects.create(
+ name="Customer",
+ team_id=self.team.pk,
+ source=source,
+ should_sync=False,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ )
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.get_schemas"
+ ) as mock_get_schemas,
+ patch(
+ "products.data_warehouse.backend.presentation.views.external_data_schema.unpause_external_data_schedule"
+ ),
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/bulk_update_schemas",
+ data={"schemas": [{"id": str(schema.id), "should_sync": True, "apply_sync_defaults": True}]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ schema.refresh_from_db()
+ assert schema.should_sync is True
+ assert schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH
+ mock_get_schemas.assert_not_called()
+
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
return_value=(True, None),
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
index c8f8cefea54b..93122ec94af8 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
@@ -644,7 +644,9 @@ function SchemaBulkActions({
schemas: readonly ExternalDataSourceSchema[]
clearSelection: () => void
}): JSX.Element {
- const { bulkDisable, bulkSetFrequency, bulkSyncNow, bulkResync, bulkDeleteData } = useActions(sourceSettingsLogic)
+ const { bulkEnable, bulkDisable, bulkSetFrequency, bulkSyncNow, bulkResync, bulkDeleteData } =
+ useActions(sourceSettingsLogic)
+ const { bulkEnableLoading } = useValues(sourceSettingsLogic)
// Wrap every action so the selection clears once it's been kicked off.
const run = (action: () => void): void => {
@@ -660,6 +662,28 @@ function SchemaBulkActions({
const allCdc = selected.length > 0 && selected.every((schema) => schema.sync_type === 'cdc')
const frequencyOptions = allowedSyncFrequencies(allCdc ? 'cdc' : 'incremental')
+ const onEnable = (): void => {
+ const needingDefaults = selected.filter((schema) => !schema.should_sync && !schema.sync_type)
+ if (needingDefaults.length === 0) {
+ run(() => bulkEnable(selected))
+ return
+ }
+ LemonDialog.open({
+ title: `Enable ${pluralize(count, 'schema', 'schemas')}?`,
+ description: `${pluralize(
+ needingDefaults.length,
+ 'selected schema has',
+ 'selected schemas have'
+ )} no sync method configured yet. Default settings will be applied: incremental sync where the table supports it, otherwise a full refresh. Syncing starts right after enabling.`,
+ primaryButton: {
+ children: 'Enable',
+ type: 'primary',
+ onClick: () => run(() => bulkEnable(selected)),
+ },
+ secondaryButton: { children: 'Cancel', type: 'tertiary' },
+ })
+ }
+
const onDisable = (): void => {
const hasDataLossType = selected.some((schema) => schema.sync_type === 'cdc' || schema.sync_type === 'webhook')
if (!hasDataLossType) {
@@ -681,6 +705,9 @@ function SchemaBulkActions({
return (
<>
+ <LemonButton type="secondary" size="small" onClick={onEnable} loading={bulkEnableLoading}>
+ Enable
+ </LemonButton>
<LemonButton type="secondary" size="small" onClick={onDisable}>
Disable
</LemonButton>
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts
index 5cc6003a3d91..ebcbd7cd2bcc 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts
@@ -2,6 +2,7 @@ import type { SourceFieldConfig } from '~/queries/schema/schema-general'
import type { ExternalDataSourceSchema } from '~/types'
import {
+ buildBulkEnablePayloads,
clonePayloadPreservingFiles,
clampFrequencyForSchema,
isSensitiveCredentialField,
@@ -242,6 +243,22 @@ describe('clampFrequencyForSchema', () => {
})
})
+describe('buildBulkEnablePayloads', () => {
+ it('skips already-enabled schemas and requests sync defaults only where no sync method is set', () => {
+ const payloads = buildBulkEnablePayloads([
+ makeSchema({ id: 'enabled', should_sync: true, sync_type: 'incremental' }),
+ makeSchema({ id: 'configured', should_sync: false, sync_type: 'full_refresh' }),
+ makeSchema({ id: 'unconfigured', should_sync: false, sync_type: null }),
+ ])
+ // Sending an unconfigured schema without `apply_sync_defaults` would 400 on the backend
+ // ("Sync type must be set up first"); sending it for configured ones is a pointless probe.
+ expect(payloads).toEqual([
+ { id: 'configured', should_sync: true },
+ { id: 'unconfigured', should_sync: true, apply_sync_defaults: true },
+ ])
+ })
+})
+
describe('runBulkSchemaAction', () => {
it('invokes the action for every schema and reports zero failures on success', async () => {
const schemas = [makeSchema({ id: 'a' }), makeSchema({ id: 'b' })]
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
index 979784f83192..98c9695e6198 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
@@ -325,6 +325,20 @@ export function schemasEligibleForSync(schemas: ExternalDataSourceSchema[]): Ext
return schemas.filter((schema) => !!schema.sync_type && schema.should_sync)
}
+// Bulk-enable payloads: already-enabled schemas are skipped; schemas without a sync method ask
+// the backend to discover and fill in default sync settings as part of the same update.
+export function buildBulkEnablePayloads(
+ schemas: ExternalDataSourceSchema[]
+): (Partial<ExternalDataSourceSchema> & Pick<ExternalDataSourceSchema, 'id'> & { apply_sync_defaults?: boolean })[] {
+ return schemas
+ .filter((schema) => !schema.should_sync)
+ .map((schema) =>
+ schema.sync_type
+ ? { id: schema.id, should_sync: true }
+ : { id: schema.id, should_sync: true, apply_sync_defaults: true }
+ )
+}
+
export function clampFrequencyForSchema(
requested: DataWarehouseSyncInterval,
schema: ExternalDataSourceSchema
@@ -352,6 +366,7 @@ function reportBulkResult(verb: string, total: number, failed: number, skipped:
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sourceSettingsLogicValues {
availableSources: Record<string, SourceConfig> | null // availableSourcesLogic
+ bulkEnableLoading: boolean
canLoadMoreJobs: boolean
cdcStatus: CdcStatus | null
cdcStatusError: string | null
@@ -407,6 +422,9 @@ export interface sourceSettingsLogicActions {
bulkDisable: (schemas: ExternalDataSourceSchema[]) => {
schemas: ExternalDataSourceSchema[]
}
+ bulkEnable: (schemas: ExternalDataSourceSchema[]) => {
+ schemas: ExternalDataSourceSchema[]
+ }
bulkResync: (schemas: ExternalDataSourceSchema[]) => {
schemas: ExternalDataSourceSchema[]
}
@@ -526,6 +544,9 @@ export interface sourceSettingsLogicActions {
resyncSchema: (schema: ExternalDataSourceSchema) => {
schema: ExternalDataSourceSchema
}
+ setBulkEnableLoading: (loading: boolean) => {
+ loading: boolean
+ }
setCanLoadMoreJobs: (canLoadMoreJobs: boolean) => {
canLoadMoreJobs: boolean
}
@@ -664,6 +685,8 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
resyncSchema: (schema: ExternalDataSourceSchema) => ({ schema }),
cancelSchema: (schema: ExternalDataSourceSchema) => ({ schema }),
deleteTable: (schema: ExternalDataSourceSchema) => ({ schema }),
+ bulkEnable: (schemas: ExternalDataSourceSchema[]) => ({ schemas }),
+ setBulkEnableLoading: (loading: boolean) => ({ loading }),
bulkDisable: (schemas: ExternalDataSourceSchema[]) => ({ schemas }),
bulkSetFrequency: (schemas: ExternalDataSourceSchema[], frequency: DataWarehouseSyncInterval) => ({
schemas,
@@ -859,6 +882,13 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
refreshSchemas: () => true,
},
],
+ bulkEnableLoading: [
+ false as boolean,
+ {
+ bulkEnable: () => true,
+ setBulkEnableLoading: (_, { loading }) => loading,
+ },
+ ],
pollPauseCount: [
0 as number,
{
@@ -1416,6 +1446,48 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
}
}
},
+ bulkEnable: async ({ schemas }) => {
+ // Guard against concurrent submissions — a rapid double-click (e.g. on the
+ // imperative dialog's Enable button, which can't reactively disable) would
+ // otherwise fire the PATCH twice and prepare duplicate schedule side effects.
+ if (cache.bulkEnableInFlight) {
+ return
+ }
+ cache.bulkEnableInFlight = true
+ const payloads = buildBulkEnablePayloads(schemas)
+ if (payloads.length === 0) {
+ lemonToast.info('All selected schemas are already enabled')
+ actions.setBulkEnableLoading(false)
+ cache.bulkEnableInFlight = false
+ return
+ }
+ const defaultsCount = payloads.filter((payload) => payload.apply_sync_defaults).length
+ try {
+ const updatedSchemas = await api.externalDataSources.bulkUpdateSchemas(values.sourceId, payloads)
+ const nextSource = applySchemasToSource(values.source, updatedSchemas)
+ if (nextSource) {
+ actions.loadSourceSuccess(nextSource)
+ }
+ actions.loadJobs()
+ posthog.capture('schemas bulk enabled', {
+ sourceType: values.source?.source_type,
+ count: payloads.length,
+ defaultsApplied: defaultsCount,
+ })
+ lemonToast.success(
+ defaultsCount > 0
+ ? `Enabled ${pluralize(payloads.length, 'schema', 'schemas')} (${defaultsCount} set up with default sync settings)`
+ : `Enabled ${pluralize(payloads.length, 'schema', 'schemas')}`
+ )
+ } catch (e: any) {
+ // Partial failures stay committed server-side; reload to show what did apply.
+ actions.loadSource()
+ lemonToast.error(e?.message || "Can't enable schemas at this time")
+ } finally {
+ actions.setBulkEnableLoading(false)
+ cache.bulkEnableInFlight = false
+ }
+ },
bulkDisable: ({ schemas }) => {
// Reuse the debounced single-schema update — these coalesce into one bulk PATCH.
schemas.forEach((schema) => actions.updateSchema({ ...schema, should_sync: false }))
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index 08948db52d52..1d7f92235a41 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -36,6 +36,7 @@ _LAZY = {
"OAuthMixin": "sources.common.mixins",
"SourceSchema": "sources.common.schema",
"build_default_schemas": "sources.common.schema",
+ "build_default_sync_settings": "sources.common.schema",
"RowFilterValidationError": "sources.common.sql",
"filter_dwh_columns_by_enabled_columns": "sources.common.sql",
"sql_schema_metadata": "sources.common.sql",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py
index 1a579c9babbf..a7e92a1e9615 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py
@@ -72,19 +72,44 @@ def _select_incremental_field(incremental_fields: list[IncrementalField]) -> Inc
return candidates[0]
+def build_default_sync_settings(source_schema: SourceSchema) -> dict[str, Any]:
+ """Default sync settings for one discovered table.
+
+ Picks ``incremental`` when the source supports it and a tracking column exists (cheapest
+ ongoing sync), else ``append`` when supported, else ``full_refresh``. Never picks ``cdc``
+ or ``webhook`` — both need prerequisites (Postgres setup, webhook registration) and
+ explicit opt-in.
+ """
+ chosen = _select_incremental_field(source_schema.incremental_fields)
+ if source_schema.supports_incremental and chosen is not None:
+ sync_type = "incremental"
+ elif source_schema.supports_append and chosen is not None:
+ sync_type = "append"
+ else:
+ sync_type = "full_refresh"
+
+ settings: dict[str, Any] = {"sync_type": sync_type}
+ if sync_type in ("incremental", "append") and chosen is not None:
+ settings["incremental_field"] = chosen["field"]
+ settings["incremental_field_type"] = str(chosen.get("field_type") or chosen.get("type"))
+ if sync_type == "incremental" and source_schema.default_incremental_lookback_seconds is not None:
+ settings["incremental_field_lookback_seconds"] = source_schema.default_incremental_lookback_seconds
+ if source_schema.detected_primary_keys:
+ settings["primary_key_columns"] = source_schema.detected_primary_keys
+ return settings
+
+
def build_default_schemas(source_schemas: list[SourceSchema]) -> list[dict]:
"""Build a default ``schemas`` payload for one-shot source creation.
- Enables every discovered table the source marks as default-on and picks a sync type per
- table: ``incremental`` when the source supports it and a tracking column exists (cheapest
- ongoing sync), else ``append`` when supported, else ``full_refresh``. Never defaults to
- ``cdc`` — that needs Postgres prerequisites and explicit opt-in. Webhook-only tables start
- disabled because webhook registration needs the created source; the setup flow attempts it
- right after creation and, on success, switches webhook-capable tables to the webhook sync
- method. These polling defaults are also the fallback when that registration fails. Tables
- with ``should_sync_default=False`` also start disabled: sources use it for tables whose
- sync needs grants beyond what source creation validated, and the schema picker already
- honors it, so one-shot setup must not force-enable what the picker would leave off.
+ Enables every discovered table the source marks as default-on, with each table's sync
+ settings from ``build_default_sync_settings``. Webhook-only tables start disabled because
+ webhook registration needs the created source; the setup flow attempts it right after
+ creation and, on success, switches webhook-capable tables to the webhook sync method.
+ These polling defaults are also the fallback when that registration fails. Tables with
+ ``should_sync_default=False`` also start disabled: sources use it for tables whose sync
+ needs grants beyond what source creation validated, and the schema picker already honors
+ it, so one-shot setup must not force-enable what the picker would leave off.
"""
schemas: list[dict] = []
for source_schema in source_schemas:
@@ -92,21 +117,7 @@ def build_default_schemas(source_schemas: list[SourceSchema]) -> list[dict]:
schemas.append({"name": source_schema.name, "should_sync": False})
continue
- chosen = _select_incremental_field(source_schema.incremental_fields)
- if source_schema.supports_incremental and chosen is not None:
- sync_type = "incremental"
- elif source_schema.supports_append and chosen is not None:
- sync_type = "append"
- else:
- sync_type = "full_refresh"
-
- entry: dict = {"name": source_schema.name, "should_sync": True, "sync_type": sync_type}
- if sync_type in ("incremental", "append") and chosen is not None:
- entry["incremental_field"] = chosen["field"]
- entry["incremental_field_type"] = str(chosen.get("field_type") or chosen.get("type"))
- if source_schema.detected_primary_keys:
- entry["primary_key_columns"] = source_schema.detected_primary_keys
- schemas.append(entry)
+ schemas.append({"name": source_schema.name, "should_sync": True, **build_default_sync_settings(source_schema)})
return schemas
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py
index 59277d3f87ad..f9fd4ded82d4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py
@@ -119,6 +119,22 @@ class TestBuildDefaultSchemas:
)
assert schemas == [{"name": "teams", "should_sync": False}]
+ def test_incremental_lookback_default_flows_through(self) -> None:
+ # Sources whose recent rows get restated upstream (e.g. Google Ads stats tables) set a
+ # default lookback; dropping it here would freeze restated rows at first-imported values.
+ schemas = build_default_schemas(
+ [
+ SourceSchema(
+ name="campaign_stats",
+ supports_incremental=True,
+ supports_append=True,
+ incremental_fields=[_field("updated_at")],
+ default_incremental_lookback_seconds=86400,
+ )
+ ]
+ )
+ assert schemas[0]["incremental_field_lookback_seconds"] == 86400
+
def test_never_defaults_to_cdc(self) -> None:
schemas = build_default_schemas(
[
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 035b8cbe7afd..0c7426913d5c 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -3287,6 +3287,8 @@ export interface ExternalDataSourceBulkUpdateSchemaApi {
* @nullable
*/
row_filters?: ExternalDataSourceBulkUpdateSchemaApiRowFiltersItem[] | null
+ /** When true and the schema has no sync method configured yet (and this update does not set one), discover the table on the source and fill in default sync settings: incremental sync with an auto-selected tracking column where supported, otherwise append, otherwise full refresh. Ignored for schemas that already have a sync method. */
+ apply_sync_defaults?: boolean
}
export interface PatchedExternalDataSourceBulkUpdateSchemasApi {
diff --git a/products/warehouse_sources/frontend/generated/api.zod.ts b/products/warehouse_sources/frontend/generated/api.zod.ts
index 69073674449c..b152709aba52 100644
--- a/products/warehouse_sources/frontend/generated/api.zod.ts
+++ b/products/warehouse_sources/frontend/generated/api.zod.ts
@@ -1604,6 +1604,12 @@ export const ExternalDataSourcesBulkUpdateSchemasPartialUpdateBody = /* @__PURE_
)
.nullish()
.describe('Row-filter predicates ANDed onto the source query. Null\/empty means sync all rows.'),
+ apply_sync_defaults: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'When true and the schema has no sync method configured yet (and this update does not set one), discover the table on the source and fill in default sync settings: incremental sync with an auto-selected tracking column where supported, otherwise append, otherwise full refresh. Ignored for schemas that already have a sync method.'
+ ),
})
)
.optional()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ab05a47c0f5a..37a9ae8dcf95 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25877,6 +25877,8 @@ export namespace Schemas {
* @nullable
*/
row_filters?: ExternalDataSourceBulkUpdateSchemaRowFiltersItem[] | null;
+ /** When true and the schema has no sync method configured yet (and this update does not set one), discover the table on the source and fill in default sync settings: incremental sync with an auto-selected tracking column where supported, otherwise append, otherwise full refresh. Ignored for schemas that already have a sync method. */
+ apply_sync_defaults?: boolean;
}
export interface ExternalDataSourceConnectionOption {