: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(data-warehouse): safer default sync settings for supabase sources (#85203)
estefaniaec23322fbd1a
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsxindex 520a278eec5f..cd0a586a840f 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx@@ -322,6 +322,28 @@ const resolveIncrementalField = (fields: IncrementalField[]): IncrementalField |return undefined}+// Supabase tables carry arbitrary user columns, so the "any timestamp/date" and id-column+// fallbacks above can land on a value that never changes on update (a date of birth, a+// config integer). Such a cursor syncs each row once and then silently stops seeing+// updates, so only trust update-tracking columns and otherwise default to full refresh.+export const resolveUpdateTrackedIncrementalField = (fields: IncrementalField[]): IncrementalField | undefined =>+ fields.find((field) => /^(updated|modified|last_modified)/i.test(field.label) && isTimestampType(field)) ??+ fields.find((field) => /^created/i.test(field.label) && isTimestampType(field))++// Shared rule for bulk enablement (select-all, onboarding auto-configure): permission_error+// rows stay off so bulk toggle never queues guaranteed-403 syncs, and default-off tables+// (e.g. Supabase Vault tables, which hold decrypted secrets) keep their current state so+// enabling them always takes an explicit per-table opt-in. Bulk disable still clears them.+export const bulkToggledShouldSync = (schema: ExternalDataSourceSyncSchema, selectAll: boolean): boolean => {+ if (schema.permission_error) {+ return false+ }+ if (selectAll && schema.should_sync_default === false) {+ return schema.should_sync+ }+ return selectAll+}+function syncExpandedSchemaGroupKeys(actions: sourceWizardLogicType['actions'],values: sourceWizardLogicType['values']@@ -2366,20 +2388,17 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([{setDatabaseSchemas: (_, { schemas }) => schemas,toggleAllTables: (state, { selectAll, tableNames }) => {- // permission_error rows stay off — bulk toggle never queues guaranteed-403 syncs.if (!tableNames) {return state.map((schema) => ({...schema,- should_sync: schema.permission_error ? false : selectAll,+ should_sync: bulkToggledShouldSync(schema, selectAll),}))}const targetSet = new Set(tableNames)return state.map((schema) => ({...schema,should_sync: targetSet.has(schema.table)- ? schema.permission_error- ? false- : selectAll+ ? bulkToggledShouldSync(schema, selectAll): schema.should_sync,}))},@@ -3508,7 +3527,10 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([schema.sync_type = 'webhook'} else if (schema.incremental_available || schema.append_available) {const method = schema.incremental_available ? 'incremental' : 'append'- const resolvedField = resolveIncrementalField(schema.incremental_fields)+ const resolvedField =+ values.selectedConnector.name === 'Supabase'+ ? resolveUpdateTrackedIncrementalField(schema.incremental_fields)+ : resolveIncrementalField(schema.incremental_fields)schema.sync_type = methodif (resolvedField) {schema.incremental_field = resolvedField.field@@ -3523,8 +3545,10 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([// Onboarding one-click setup: opt every syncable table in (permission errors// already continued above), so the user can sync the whole source in one click.+ // Default-off tables stay off via the shared bulk rule: this path shows no+ // table picker, so nothing else stops a secrets table from syncing.if (props.autoConfigureTables) {- schema.should_sync = true+ schema.should_sync = bulkToggledShouldSync(schema, true)}}diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.tsindex 077441b34137..284f74443041 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts@@ -4,7 +4,7 @@ import api from 'lib/api'import type { SourceConfig } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import type { ExternalDataSourceSyncSchema } from '~/types'+import type { ExternalDataSourceSyncSchema, IncrementalField } from '~/types'import {buildKeaFormDefaultFromSourceDetails,@@ -825,6 +825,30 @@ describe('sourceWizardLogic', () => {}})+ it('toggleAllTables(selectAll=true) never opts into default-off rows, deselect still clears them', () => {+ // Default-off tables (e.g. Supabase Vault secrets tables) need an explicit per-table+ // opt-in; select-all must neither enable them nor undo a deliberate manual opt-in.+ const { logic, unmount } = mountWithSchemas([+ buildSchema({ table: 'Customer' }),+ buildSchema({ table: 'vault.decrypted_secrets', should_sync_default: false }),+ buildSchema({ table: 'vault.secrets', should_sync_default: false, should_sync: true }),+ ])++ try {+ logic.actions.toggleAllTables(true)+ let byTable = Object.fromEntries(logic.values.databaseSchema.map((s) => [s.table, s]))+ expect(byTable['Customer'].should_sync).toBe(true)+ expect(byTable['vault.decrypted_secrets'].should_sync).toBe(false)+ expect(byTable['vault.secrets'].should_sync).toBe(true)++ logic.actions.toggleAllTables(false)+ byTable = Object.fromEntries(logic.values.databaseSchema.map((s) => [s.table, s]))+ expect(byTable['vault.secrets'].should_sync).toBe(false)+ } finally {+ unmount()+ }+ })+it('toggleAllTables(selectAll=true) with explicit tableNames still skips permission_error rows', () => {const { logic, unmount } = mountWithSchemas([buildSchema({ table: 'Customer' }),@@ -971,14 +995,16 @@ describe('sourceWizardLogic', () => {jest.spyOn(api.externalDataSources, 'database_schema').mockResolvedValue([apiSchema({table: 'Customer',- should_sync_default: false, // proves autoConfigureTables overrides the per-table defaultincremental_available: true,incremental_fields: [{ field: 'updated_at', field_type: 'datetime', label: 'updated_at', type: 'datetime' },],}),- apiSchema({ table: 'Product', should_sync_default: false }),+ apiSchema({ table: 'Product' }),apiSchema({ table: 'Charge', permission_error: 'Missing scope' }),+ // Auto-configure shows no table picker, so a table the source marks default-off+ // (e.g. a Supabase Vault secrets table) must not be silently opted in.+ apiSchema({ table: 'vault.decrypted_secrets', should_sync_default: false }),] as ExternalDataSourceSyncSchema[])const logic = sourceWizardLogic({ availableSources: { Stripe: stripeSource }, autoConfigureTables: true })@@ -995,6 +1021,7 @@ describe('sourceWizardLogic', () => {expect(byTable['Product'].should_sync).toBe(true)// permission_error rows can never be synced, even under auto-configure.expect(byTable['Charge'].should_sync).toBe(false)+ expect(byTable['vault.decrypted_secrets'].should_sync).toBe(false)} finally {unmount()}@@ -1192,4 +1219,104 @@ describe('sourceWizardLogic', () => {}})})++ // Supabase tables carry arbitrary user columns, so the wizard only trusts update-tracking+ // columns as default cursors; anything else falls back to full refresh instead of a cursor+ // that never advances (see resolveUpdateTrackedIncrementalField).+ describe('Supabase incremental defaults', () => {+ const supabaseSource = { name: 'Supabase', iconPath: '', caption: null, fields: [] } as SourceConfig+ const postgresSource = { name: 'Postgres', iconPath: '', caption: null, fields: [] } as SourceConfig++ const apiSchema = (+ table: string,+ overrides: Partial<ExternalDataSourceSyncSchema> = {}+ ): ExternalDataSourceSyncSchema =>+ ({+ table,+ label: null,+ rows: null,+ should_sync: false,+ sync_time_of_day: null,+ incremental_field: null,+ incremental_field_type: null,+ sync_type: null,+ incremental_fields: [],+ incremental_available: true,+ append_available: true,+ supports_webhooks: false,+ description: null,+ should_sync_default: true,+ primary_key_columns: null,+ available_columns: [],+ detected_primary_keys: null,+ permission_error: null,+ cdc_available: false,+ ...overrides,+ }) as ExternalDataSourceSyncSchema++ const dateOfBirthFields: IncrementalField[] = [+ { field: 'date_of_birth', field_type: 'date', label: 'date_of_birth', type: 'date' },+ ]++ const mountAndLoadSchemas = async (+ source: SourceConfig+ ): Promise<{ logic: ReturnType<typeof sourceWizardLogic>; unmount: () => void }> => {+ const logic = sourceWizardLogic({ availableSources: { [source.name]: source } })+ const unmount = logic.mount()+ logic.actions.selectConnector(source)+ await expectLogic(logic, () => logic.actions.getDatabaseSchemas()).toFinishAllListeners()+ return { logic, unmount }+ }++ afterEach(() => {+ jest.restoreAllMocks()+ })++ it('defaults Supabase tables without an update-tracking column to full refresh', async () => {+ jest.spyOn(api.externalDataSources, 'database_schema').mockResolvedValue([+ apiSchema('public.users', {+ incremental_fields: [+ { field: 'priority', field_type: 'integer', label: 'priority', type: 'integer' },+ ...dateOfBirthFields,+ ],+ incremental_field: 'priority',+ }),+ apiSchema('public.tasks', {+ incremental_fields: [+ { field: 'updated_at', field_type: 'timestamp', label: 'updated_at', type: 'timestamp' },+ ],+ incremental_field: 'updated_at',+ }),+ ] as ExternalDataSourceSyncSchema[])++ const { logic, unmount } = await mountAndLoadSchemas(supabaseSource)++ try {+ const byTable = Object.fromEntries(logic.values.databaseSchema.map((s) => [s.table, s]))+ expect(byTable['public.users'].sync_type).toBe('full_refresh')+ expect(byTable['public.tasks'].sync_type).toBe('incremental')+ expect(byTable['public.tasks'].incremental_field).toBe('updated_at')+ } finally {+ unmount()+ }+ })++ it('keeps the any-timestamp fallback for other database sources', async () => {+ jest.spyOn(api.externalDataSources, 'database_schema').mockResolvedValue([+ apiSchema('public.users', {+ incremental_fields: dateOfBirthFields,+ incremental_field: 'date_of_birth',+ }),+ ] as ExternalDataSourceSyncSchema[])++ const { logic, unmount } = await mountAndLoadSchemas(postgresSource)++ try {+ expect(logic.values.databaseSchema[0].sync_type).toBe('incremental')+ expect(logic.values.databaseSchema[0].incremental_field).toBe('date_of_birth')+ } finally {+ unmount()+ }+ })+ })})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.pyindex 234de902a12f..d1461ac7c44c 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@@ -62,6 +62,24 @@ class SourceSchema:schema_metadata: dict[str, Any] | None = None+def rank_incremental_fields(incremental_fields: list[IncrementalField]) -> list[IncrementalField]:+ """Stable-sort candidate cursor fields so update-tracking columns come first.++ Several surfaces default to the first candidate (the schema picker response, the sync+ settings modal), so for sources with arbitrary user columns the leading candidate must+ be one that advances on writes rather than whichever column comes first in the table+ definition. Fields not in the preference list keep their original relative order.+ """++ def preference(field: IncrementalField) -> int:+ name = (field.get("field") or "").lower()+ if name in _INCREMENTAL_FIELD_PREFERENCE:+ return _INCREMENTAL_FIELD_PREFERENCE.index(name)+ return len(_INCREMENTAL_FIELD_PREFERENCE)++ return sorted(incremental_fields, key=preference)++def _select_incremental_field(incremental_fields: list[IncrementalField]) -> IncrementalField | None:"""Pick the best incremental field for a table, preferring update-tracking columns."""candidates = [f for f in incremental_fields if f.get("field")]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/source.pyindex 60ed10a5fff0..238ae9a0aa54 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/source.py@@ -16,6 +16,10 @@ from posthog.schema import ()from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ rank_incremental_fields,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.postgres import (PostgresSourceConfig,)@@ -85,6 +89,10 @@ _SUPABASE_REALTIME_PARTITION_MESSAGE = ("the sync.")+# Supabase Vault's schema: its `decrypted_secrets` view decrypts every stored secret on read,+# so sync-enabling it by default would copy a secrets vault into the warehouse.+_VAULT_SCHEMA = "vault"+@SourceRegistry.registerclass SupabaseSource(PostgresSource):@@ -101,6 +109,43 @@ class SupabaseSource(PostgresSource):**super().get_non_retryable_errors(),}+ def get_schemas(+ self,+ config: PostgresSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ require_ssl: bool = False,+ ) -> list[SourceSchema]:+ schemas = super().get_schemas(+ config,+ team_id,+ with_counts=with_counts,+ names=names,+ force_refresh=force_refresh,+ api_version=api_version,+ require_ssl=require_ssl,+ )++ # Vault tables must never be sync-enabled by default. They stay listed rather than+ # filtered because scheduled discovery reconciles stored rows against this listing+ # and would disable a vault sync a user deliberately opted into; default-off is+ # honored by the picker, one-shot setup, and auto-sync of newly discovered schemas.+ for schema in schemas:+ if schema.source_schema == _VAULT_SCHEMA:+ schema.should_sync_default = False++ # Supabase tables carry arbitrary user columns, so the first discovered candidate+ # (column ordinal order) is often a value that never changes on update. Rank+ # update-tracking columns first so surfaces defaulting to the leading candidate+ # propose a cursor that actually advances.+ for schema in schemas:+ schema.incremental_fields = rank_incremental_fields(schema.incremental_fields)++ return schemas+@staticmethoddef _adjust_field(field: _SourceField) -> _SourceField:if isinstance(field, SourceFieldInputConfig) and field.name == "host":diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/test_supabase_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/test_supabase_source.pyindex a2edd33c2231..0c763149e1ce 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/test_supabase_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/supabase/test_supabase_source.py@@ -4,11 +4,13 @@ from unittest import mockfrom posthog.schema import ReleaseStatus, SourceFieldInputConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import (_HOST_UNREACHABLE_ERROR,PostgresSource,)from products.warehouse_sources.backend.temporal.data_imports.sources.supabase.source import SupabaseSource+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldTypedef _field(name: str) -> SourceFieldInputConfig:@@ -147,6 +149,79 @@ def test_non_direct_host_failure_uses_postgres_error(host):assert error == "postgres error"+def _incremental_field(name: str, field_type: IncrementalFieldType) -> IncrementalField:+ return {"label": name, "type": field_type, "field": name, "field_type": field_type}+++def _discovered_schema(+ name: str, source_schema: str, incremental_fields: list[IncrementalField] | None = None+) -> SourceSchema:+ return SourceSchema(+ name=name,+ supports_incremental=bool(incremental_fields),+ supports_append=bool(incremental_fields),+ incremental_fields=incremental_fields or [],+ source_schema=source_schema,+ source_table_name=name.split(".")[-1],+ )+++def _get_schemas(discovered: list[SourceSchema]) -> list[SourceSchema]:+ config = mock.MagicMock()+ config.schema = None+ with mock.patch.object(PostgresSource, "get_schemas", return_value=discovered):+ return SupabaseSource().get_schemas(config, team_id=1)+++def test_vault_tables_are_never_sync_enabled_by_default():+ # Supabase's vault.decrypted_secrets view decrypts Vault secrets on read; default-enabling+ # it proposes copying a secrets vault into the warehouse. The tables must stay listed+ # (scheduled discovery reconciles stored rows against this listing, so dropping them would+ # disable a vault sync a user deliberately opted into) but start disabled everywhere+ # should_sync_default applies.+ discovered = [+ _discovered_schema("public.orders", "public"),+ _discovered_schema("vault.secrets", "vault"),+ _discovered_schema("vault.decrypted_secrets", "vault"),+ ]++ schemas = _get_schemas(discovered)++ default_on_by_name = {schema.name: schema.should_sync_default for schema in schemas}+ assert default_on_by_name == {+ "public.orders": True,+ "vault.secrets": False,+ "vault.decrypted_secrets": False,+ }+++def test_update_tracking_column_leads_the_incremental_candidates():+ # Discovery lists candidates in column ordinal order, and several surfaces default to the+ # first one — without ranking, a table like (priority, dateOfBirth, updated_at) gets a+ # cursor that never advances and the incremental sync silently goes stale.+ discovered = [+ _discovered_schema(+ "public.tasks",+ "public",+ incremental_fields=[+ _incremental_field("priority", IncrementalFieldType.Integer),+ _incremental_field("dateOfBirth", IncrementalFieldType.Date),+ _incremental_field("updated_at", IncrementalFieldType.Timestamp),+ _incremental_field("created_at", IncrementalFieldType.Timestamp),+ ],+ )+ ]++ schemas = _get_schemas(discovered)++ assert [field["field"] for field in schemas[0].incremental_fields] == [+ "updated_at",+ "created_at",+ "priority",+ "dateOfBirth",+ ]++def _resolve_friendly_error(source: SupabaseSource, raw_error: str) -> str | None:# Mirrors external_data_job.update_external_data_job_model: first matching key wins.for pattern, friendly in source.get_non_retryable_errors().items():