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.

chore(data-warehouse): finish source-agnostic presentation layer (#71574)

Tom Owers0af45f1e051f
diff --git a/.github/scripts/check-dwh-source-agnostic.py b/.github/scripts/check-dwh-source-agnostic.py
index 29cf0583f9c0..0ac608d431e6 100644
--- a/.github/scripts/check-dwh-source-agnostic.py
+++ b/.github/scripts/check-dwh-source-agnostic.py
@@ -62,8 +62,9 @@ BASELINE_HEADER = (
"# Auto-generated by .github/scripts/check-dwh-source-agnostic.py\n"
"# Regenerate: python .github/scripts/check-dwh-source-agnostic.py --regenerate-baseline\n"
"#\n"
- "# Each line is `<count>\\t<token>\\t<relpath>`. Migrate a family to a capability\n"
- "# mixin (see .../sources/common/capabilities.py), then regenerate to shrink.\n"
+ "# Each line is `<count>\\t<token>\\t<relpath>`. Migrate a family onto a source capability or\n"
+ "# engine adapter (see products/data_warehouse/backend/presentation/README.md), then regenerate\n"
+ "# to shrink. Empty means the presentation layer is fully source-agnostic — keep it that way.\n"
)
diff --git a/products/data_warehouse/backend/direct_query_engines.py b/products/data_warehouse/backend/direct_query_engines.py
index e8fea31c4f06..d182b49fbd52 100644
--- a/products/data_warehouse/backend/direct_query_engines.py
+++ b/products/data_warehouse/backend/direct_query_engines.py
@@ -1,12 +1,12 @@
-"""Engine-keyed adapters for direct-query table materialization.
-
-The presentation layer must not branch on source type. Direct-query behaviour varies by SQL
-*engine* (postgres/mysql/snowflake/redshift), not by source type, and the same engine can back
-more than one source type, so it dispatches here via ``source.direct_engine``
-(``DIRECT_ENGINE_BY_SOURCE_TYPE``). Each adapter bundles the engine-specific pieces of building a
-live-query ``DataWarehouseTable``: resolving the upstream location, mapping columns, and
-creating / reprojecting / hiding the row. Warehouse-domain orchestration (filtering enabled
-columns, saving the row) stays in the view.
+"""Engine-keyed adapters for SQL-source engine behaviour.
+
+The presentation layer must not branch on source type. This behaviour varies by SQL *engine*
+(postgres/mysql/snowflake/redshift), not by source type, and the same engine can back more than
+one source type, so it dispatches here via ``source.direct_engine`` (``DIRECT_ENGINE_BY_SOURCE_TYPE``,
+defined for every SQL source regardless of access method). Each adapter bundles the engine-specific
+pieces of: building a live-query ``DataWarehouseTable`` (resolving the upstream location, mapping
+columns, creating / reprojecting / hiding the row) and reconciling schema rows on refresh. Warehouse
+-domain orchestration (filtering enabled columns, saving the row) stays in the view.
"""
from abc import ABC, abstractmethod
@@ -16,16 +16,26 @@ from products.data_warehouse.backend.direct_mysql import hide_direct_mysql_table
from products.data_warehouse.backend.direct_postgres import hide_direct_postgres_table, upsert_direct_postgres_table
from products.data_warehouse.backend.direct_redshift import hide_direct_redshift_table, upsert_direct_redshift_table
from products.data_warehouse.backend.direct_snowflake import hide_direct_snowflake_table, upsert_direct_snowflake_table
-from products.data_warehouse.backend.mysql_helpers import get_mysql_source_location, reproject_direct_mysql_table
+from products.data_warehouse.backend.mysql_helpers import (
+ get_mysql_source_location,
+ reconcile_mysql_schemas,
+ reproject_direct_mysql_table,
+)
from products.data_warehouse.backend.postgres_helpers import (
get_postgres_source_location,
+ reconcile_postgres_schemas,
reproject_direct_postgres_table,
)
+from products.data_warehouse.backend.postgres_warehouse_migration import reconcile_refresh_name_substitutions
from products.data_warehouse.backend.redshift_helpers import (
get_redshift_source_location,
+ reconcile_redshift_schemas,
reproject_direct_redshift_table,
)
-from products.data_warehouse.backend.snowflake_helpers import reproject_direct_snowflake_table
+from products.data_warehouse.backend.snowflake_helpers import (
+ reconcile_snowflake_schemas,
+ reproject_direct_snowflake_table,
+)
from products.warehouse_sources.backend.facade.api import (
mysql_columns_to_dwh_columns,
postgres_columns_to_dwh_columns,
@@ -92,6 +102,21 @@ class DirectQueryEngine(ABC):
def hide_table(self, table: Any) -> None:
raise NotImplementedError()
+ @abstractmethod
+ def reconcile_schemas(self, *, source: Any, source_schemas: list[Any], team_id: int) -> list[str]:
+ """Dedupe/rebuild this engine's schema rows against discovered schemas on refresh; returns
+ the extra schema names deleted during reconciliation."""
+ raise NotImplementedError()
+
+ def refresh_name_substitutions(
+ self, *, source: Any, source_schemas: list[Any], team_id: int
+ ) -> dict[str, str] | None:
+ """Engine-specific legacy-row name remapping applied before schema sync. ``None`` means the
+ engine has none, so the caller falls back to the generic multi-schema migration. Only
+ Postgres overrides this (its bespoke legacy-dedup); an empty dict from Postgres still counts
+ as "handled" and suppresses the generic path."""
+ return None
+
class _PostgresEngine(DirectQueryEngine):
engine = "postgres"
@@ -124,6 +149,12 @@ class _PostgresEngine(DirectQueryEngine):
def hide_table(self, table):
hide_direct_postgres_table(table)
+ def reconcile_schemas(self, *, source, source_schemas, team_id):
+ return reconcile_postgres_schemas(source=source, source_schemas=source_schemas, team_id=team_id)
+
+ def refresh_name_substitutions(self, *, source, source_schemas, team_id):
+ return reconcile_refresh_name_substitutions(source=source, source_schemas=source_schemas, team_id=team_id)
+
class _MySQLEngine(DirectQueryEngine):
engine = "mysql"
@@ -159,6 +190,9 @@ class _MySQLEngine(DirectQueryEngine):
def hide_table(self, table):
hide_direct_mysql_table(table)
+ def reconcile_schemas(self, *, source, source_schemas, team_id):
+ return reconcile_mysql_schemas(source=source, source_schemas=source_schemas, team_id=team_id)
+
class _SnowflakeEngine(DirectQueryEngine):
engine = "snowflake"
@@ -199,6 +233,9 @@ class _SnowflakeEngine(DirectQueryEngine):
def hide_table(self, table):
hide_direct_snowflake_table(table)
+ def reconcile_schemas(self, *, source, source_schemas, team_id):
+ return reconcile_snowflake_schemas(source=source, source_schemas=source_schemas, team_id=team_id)
+
class _RedshiftEngine(DirectQueryEngine):
engine = "redshift"
@@ -234,6 +271,9 @@ class _RedshiftEngine(DirectQueryEngine):
def hide_table(self, table):
hide_direct_redshift_table(table)
+ def reconcile_schemas(self, *, source, source_schemas, team_id):
+ return reconcile_redshift_schemas(source=source, source_schemas=source_schemas, team_id=team_id)
+
_ENGINES: dict[str, DirectQueryEngine] = {
engine.engine: engine for engine in (_PostgresEngine(), _MySQLEngine(), _SnowflakeEngine(), _RedshiftEngine())
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.py
index fc286d0ee021..73fadcc3ccbb 100644
--- a/products/data_warehouse/backend/facade/api.py
+++ b/products/data_warehouse/backend/facade/api.py
@@ -80,7 +80,9 @@ _LAZY = {
"upsert_direct_snowflake_table": "direct_snowflake",
"hide_direct_redshift_table": "direct_redshift",
"upsert_direct_redshift_table": "direct_redshift",
+ "DirectQueryEngine": "direct_query_engines",
"get_direct_query_engine": "direct_query_engines",
+ "get_namespaced_resource_adapter": "namespaced_resources",
"reconcile_refresh_name_substitutions": "postgres_warehouse_migration",
"github_repositories_for_job_inputs": "github_warehouse_repos",
"reconcile_github_repositories": "github_warehouse_repos",
diff --git a/products/data_warehouse/backend/namespaced_resources.py b/products/data_warehouse/backend/namespaced_resources.py
new file mode 100644
index 000000000000..f479b4afb402
--- /dev/null
+++ b/products/data_warehouse/backend/namespaced_resources.py
@@ -0,0 +1,60 @@
+"""Registry for sources whose schema rows are namespaced by an external resource set.
+
+GitHub is the current example: its tables are namespaced per repository, the repo list lives in
+``job_inputs``, and editing it adds/retires schema rows and reconciles per-repo webhooks. Like the
+direct-query engine registry, the presentation layer dispatches through this registry keyed on the
+source type (resolved here, never named inline) so it stays source-agnostic. The reconciliation
+touches ``DataWarehouseTable`` / schema rows, so it is data_warehouse-domain and lives here.
+"""
+
+from abc import ABC, abstractmethod
+from typing import Any
+
+from products.data_warehouse.backend.github_warehouse_repos import (
+ github_repositories_for_job_inputs,
+ reconcile_github_repositories,
+)
+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
+
+
+class NamespacedResourceAdapter(ABC):
+ """How a namespaced-resource source syncs its schema rows to an external resource set."""
+
+ # These sources keep the legacy resource's rows bare alongside qualified rows for the others
+ # (GitHub: the legacy repo stays unqualified), so bare<->qualified tail matching would wrongly
+ # collapse them. Match schema names exactly instead.
+ uses_strict_schema_name_match: bool = True
+
+ @abstractmethod
+ def resources_for_job_inputs(self, job_inputs: dict[str, Any] | None) -> list[str]:
+ """The effective resource list encoded in stored ``job_inputs``."""
+ raise NotImplementedError()
+
+ @abstractmethod
+ def reconcile_resources(self, *, source_model: Any, team: Any, old_resources: list[str], new_config: Any) -> None:
+ """Bring schema rows and per-resource webhooks in line with the persisted new resource list."""
+ raise NotImplementedError()
+
+ def schema_metadata_by_name(self, schemas: list[Any]) -> dict[str, Any] | None:
+ """Per-resource location metadata to seed on newly created schema rows."""
+ return {schema.name: schema.schema_metadata for schema in schemas if schema.schema_metadata}
+
+
+class _GithubNamespacedResources(NamespacedResourceAdapter):
+ def resources_for_job_inputs(self, job_inputs):
+ return github_repositories_for_job_inputs(job_inputs)
+
+ def reconcile_resources(self, *, source_model, team, old_resources, new_config):
+ reconcile_github_repositories(
+ source_model=source_model, team=team, old_repositories=old_resources, new_config=new_config
+ )
+
+
+_ADAPTERS: dict[str, NamespacedResourceAdapter] = {
+ ExternalDataSourceType.GITHUB: _GithubNamespacedResources(),
+}
+
+
+def get_namespaced_resource_adapter(source_type: str) -> NamespacedResourceAdapter | None:
+ """Adapter for a namespaced-resource source, or None for sources without namespaced schemas."""
+ return _ADAPTERS.get(source_type)
diff --git a/products/data_warehouse/backend/presentation/README.md b/products/data_warehouse/backend/presentation/README.md
index 695ffbd85a81..3fd372009e0a 100644
--- a/products/data_warehouse/backend/presentation/README.md
+++ b/products/data_warehouse/backend/presentation/README.md
@@ -52,6 +52,8 @@ the baseline:
python .github/scripts/check-dwh-source-agnostic.py --regenerate-baseline
```
-The baseline only shrinks. When it hits zero, delete the guard.
+The baseline only shrinks. It is now empty: the presentation layer is fully source-agnostic, so
+the guard acts as a hard regression check — any new `ExternalDataSourceType.<NAME>` /
+`is_direct_<engine>` reference here fails CI. Keep it that way.
See `implementing-warehouse-sources` for how to add behaviour to a source.
diff --git a/products/data_warehouse/backend/presentation/source_agnostic_baseline.txt b/products/data_warehouse/backend/presentation/source_agnostic_baseline.txt
index f9becda19849..47226674d63f 100644
--- a/products/data_warehouse/backend/presentation/source_agnostic_baseline.txt
+++ b/products/data_warehouse/backend/presentation/source_agnostic_baseline.txt
@@ -7,12 +7,6 @@
# Auto-generated by .github/scripts/check-dwh-source-agnostic.py
# Regenerate: python .github/scripts/check-dwh-source-agnostic.py --regenerate-baseline
#
-# Each line is `<count>\t<token>\t<relpath>`. Migrate a family to a capability
-# mixin (see .../sources/common/capabilities.py), then regenerate to shrink.
-1 ExternalDataSourceType.MYSQL products/data_warehouse/backend/presentation/views/external_data_source.py
-2 ExternalDataSourceType.POSTGRES products/data_warehouse/backend/presentation/views/external_data_schema.py
-2 ExternalDataSourceType.REDSHIFT products/data_warehouse/backend/presentation/views/external_data_source.py
-2 ExternalDataSourceType.SNOWFLAKE products/data_warehouse/backend/presentation/views/external_data_source.py
-4 ExternalDataSourceType.GITHUB products/data_warehouse/backend/presentation/views/external_data_source.py
-5 ExternalDataSourceType.POSTGRES products/data_warehouse/backend/presentation/views/external_data_source.py
-6 ExternalDataSourceType.CUSTOM products/data_warehouse/backend/presentation/views/external_data_source.py
+# Each line is `<count>\t<token>\t<relpath>`. Migrate a family onto a source capability or
+# engine adapter (see products/data_warehouse/backend/presentation/README.md), then regenerate
+# to shrink. Empty means the presentation layer is fully source-agnostic — keep it that way.
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 4b5f7a3749fd..5ed035a6f0c7 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_schema.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_schema.py
@@ -707,7 +707,7 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
# actually advertises xmin support — otherwise a raw PATCH would persist an xmin schema that
# silently degrades to full_refresh.
if sync_type == ExternalDataSchema.SyncType.XMIN:
- if instance.source.source_type != ExternalDataSourceType.POSTGRES:
+ if not SourceRegistry.get_source(ExternalDataSourceType(instance.source.source_type)).supports_xmin:
raise ValidationError("xmin replication is only available for Postgres sources.")
if not self._xmin_available_for_schema(instance):
raise ValidationError(
@@ -1584,8 +1584,12 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# strings, so bool(...) would treat "False" as truthy. str_to_bool decodes both.
source_cdc_enabled = str_to_bool(source.job_inputs.get("cdc_enabled"))
cdc_available = schema.supports_cdc if is_cdc_enabled_for_team(self.team) and source_cdc_enabled else None
- # xmin is Postgres-only, mirroring the database_schema endpoint.
- xmin_available = schema.supports_xmin if source.source_type == ExternalDataSourceType.POSTGRES else None
+ # xmin is source-capability-gated, mirroring the database_schema endpoint.
+ xmin_available = (
+ schema.supports_xmin
+ if SourceRegistry.get_source(ExternalDataSourceType(source.source_type)).supports_xmin
+ else None
+ )
data = {
"incremental_fields": schema.incremental_fields,
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 cf500138680a..25a8be80010a 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_source.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py
@@ -65,6 +65,7 @@ from products.cdp.backend.facade.api import HogFunctionSerializer
from products.cdp.backend.facade.models import HogFunction
from products.data_modeling.backend.facade.models import DataWarehouseManagedViewSet
from products.data_warehouse.backend.facade.api import (
+ DirectQueryEngine,
apply_on_refresh as apply_sql_warehouse_refresh_migration,
apply_on_schema_clear as apply_sql_warehouse_schema_clear_migration,
bulk_create_external_data_job_schedules,
@@ -78,21 +79,15 @@ from products.data_warehouse.backend.facade.api import (
detect_schema_clear_transition as detect_sql_schema_clear_transition,
ensure_cdc_slot_cleanup_schedule,
get_direct_query_engine,
+ get_namespaced_resource_adapter,
get_or_create_webhook_hog_function,
get_postgres_source_location,
get_webhook_url,
- github_repositories_for_job_inputs,
is_any_external_data_schema_paused,
is_cdc_enabled_for_team,
is_cdc_extraction_schedule_paused,
is_custom_source_ai_builder_enabled_for_team,
is_multi_schema_capable_sql_source,
- reconcile_github_repositories,
- reconcile_mysql_schemas,
- reconcile_postgres_schemas,
- reconcile_redshift_schemas,
- reconcile_refresh_name_substitutions as reconcile_postgres_refresh_name_substitutions,
- reconcile_snowflake_schemas,
source_namespace_is_blank,
sync_cdc_extraction_schedule,
sync_discover_schemas_schedule,
@@ -116,7 +111,6 @@ from products.data_warehouse.backend.presentation.views.source_api_versions impo
from products.revenue_analytics.backend.facade.api import ensure_person_join, remove_person_join
from products.warehouse_sources.backend.facade.api import validate_source_prefix
from products.warehouse_sources.backend.facade.models import (
- CustomOAuth2Integration,
DataWarehouseTable,
ExternalDataJob,
ExternalDataSchema,
@@ -129,7 +123,6 @@ from products.warehouse_sources.backend.facade.models import (
from products.warehouse_sources.backend.facade.source_management import (
DEFAULT_LAG_CRITICAL_THRESHOLD_MB,
DEFAULT_LAG_WARNING_THRESHOLD_MB,
- MAX_CUSTOM_SOURCES_PER_TEAM,
PREVIEW_DEFAULT_ROWS,
PREVIEW_MAX_ROWS,
AnySource,
@@ -162,7 +155,6 @@ from products.warehouse_sources.backend.facade.source_management import (
filter_integration_accounts,
get_cdc_adapter,
get_primary_key_columns,
- manifest_request_hosts,
repair_cdc_source,
source_requires_ssl,
source_type_supports_cdc,
@@ -473,7 +465,6 @@ def get_postgres_source_table_location(
)
-CUSTOM_SOURCE_LIMIT_MESSAGE = f"You can create at most {MAX_CUSTOM_SOURCES_PER_TEAM} custom sources per project."
DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE = (
"Direct query mode is currently supported only for Postgres, MySQL, Snowflake, and Redshift sources."
)
@@ -481,12 +472,24 @@ DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE = (
DIRECT_CONNECTION_ENGINE_CHOICES = ["duckdb", "postgres", "mysql", "snowflake", "redshift"]
-def count_active_custom_sources(team_id: int) -> int:
- return (
- ExternalDataSource.objects.filter(team_id=team_id, source_type=ExternalDataSourceType.CUSTOM)
- .exclude(deleted=True)
- .count()
- )
+def count_active_sources(team_id: int, source_type: str) -> int:
+ return ExternalDataSource.objects.filter(team_id=team_id, source_type=source_type).exclude(deleted=True).count()
+
+
+def _refresh_name_substitutions(
+ engine: DirectQueryEngine | None, *, source: ExternalDataSource, source_schemas: list[Any], team_id: int
+) -> dict[str, str]:
+ """Legacy-row name remapping applied before schema sync on refresh. The engine adapter's
+ remapping wins when it has one (Postgres's bespoke dedup — an empty dict still counts as
+ "handled" and suppresses the fallback); otherwise a multi-schema-capable SQL source with a
+ blank namespace gets the generic migration. Neither applies to any other source."""
+ if engine is not None:
+ engine_subs = engine.refresh_name_substitutions(source=source, source_schemas=source_schemas, team_id=team_id)
+ if engine_subs is not None:
+ return engine_subs
+ if source_namespace_is_blank(source) and is_multi_schema_capable_sql_source(source.source_type):
+ return apply_sql_warehouse_refresh_migration(source=source, team_id=team_id)
+ return {}
class ExternalDataSourceRevenueAnalyticsConfigSerializer(serializers.ModelSerializer):
@@ -1019,27 +1022,16 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
else:
new_job_inputs.pop(key, None)
- # GitHub's legacy `repository` is a server-managed marker once the multi-repo field is in
- # play: it defines which repo's schema rows keep bare (unqualified) names, so an edit can
- # never rename or re-point it. Legacy-only PATCHes (no `repositories` anywhere) keep the
- # original single-repo swap semantics.
- if source_type_model == ExternalDataSourceType.GITHUB and (
- "repositories" in incoming_job_inputs or "repositories" in existing_job_inputs
- ):
- if existing_job_inputs.get("repository"):
- new_job_inputs["repository"] = existing_job_inputs["repository"]
- else:
- new_job_inputs.pop("repository", None)
-
- # The OAuth2 integration row pointer is server-managed: pin it to the stored value so an
- # editor can't repoint the source at a different row (and through it, different credentials).
- # Re-entered auth_oauth2_* secrets flow into the pinned row during credential validation.
- if source_type_model == ExternalDataSourceType.CUSTOM:
- existing_oauth2_pointer = existing_job_inputs.get("auth_oauth2_integration_id")
- if existing_oauth2_pointer:
- new_job_inputs["auth_oauth2_integration_id"] = existing_oauth2_pointer
+ # Server-managed job_inputs (Custom's OAuth2 row pointer, GitHub's legacy `repository`
+ # marker): pin each to the stored value so an editor can't repoint the source at a different
+ # row/marker (and through it, different credentials). Re-entered auth_oauth2_* secrets flow
+ # into the pinned row during credential validation. The source declares which fields these
+ # are — the API never names the source type.
+ for field in source.server_managed_job_input_fields(incoming_job_inputs, existing_job_inputs):
+ if existing_job_inputs.get(field):
+ new_job_inputs[field] = existing_job_inputs[field]
else:
- new_job_inputs.pop("auth_oauth2_integration_id", None)
+ new_job_inputs.pop(field, None)
# If the connection target changed, require credentials to be re-entered. Covers
# both the generic `host` field and source-specific URL fields like ServiceNow's
@@ -1065,52 +1057,27 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
incoming_job_inputs.get("ssh_tunnel"),
)
- # The custom source's connection target lives inside the manifest, not a top-level `host`.
- # A manifest edit that introduces a new request host would send the preserved credential
- # somewhere it wasn't going before — the same exfiltration risk, so require re-entry too.
- manifest_host_added = False
- if source_type_model == ExternalDataSourceType.CUSTOM and "manifest_json" in incoming_job_inputs:
- new_hosts = manifest_request_hosts(incoming_job_inputs.get("manifest_json"))
- existing_hosts = manifest_request_hosts(existing_job_inputs.get("manifest_json"))
- manifest_host_added = bool(new_hosts - existing_hosts)
-
- # A row-backed OAuth2 custom source carries no secret in job_inputs — the client secret +
- # tokens live in the bound CustomOAuth2Integration row and are injected at sync time. So
- # `has_preserved_credentials` never sees a preserved secret for it, yet a host change would
- # still redirect the row's injected token to the new host. Re-entering every secret the row
- # holds satisfies the gate the same way typing a password does for other sources: because a
- # config change makes adoption replace the row's secrets with the typed ones outright (see
- # _apply_oauth2_material — the rotated-token keep-rule is suspended on config change), only
- # material the editor provably possesses is ever sent to the new host.
- bound_integration = None
- if source_type_model == ExternalDataSourceType.CUSTOM:
- bound_integration = (
- CustomOAuth2Integration.objects.for_team(instance.team_id).filter(external_data_source=instance).first()
- )
- reentered_oauth2_secrets = False
- if bound_integration is not None:
- held_secret_fields = [
- incoming_field
- for row_key, incoming_field in (
- ("client_secret", "auth_oauth2_client_secret"),
- ("refresh_token", "auth_oauth2_refresh_token"),
- )
- if bound_integration.sensitive_config.get(row_key)
- ]
- reentered_oauth2_secrets = bool(held_secret_fields) and all(
- bool(incoming_job_inputs.get(field)) for field in held_secret_fields
- )
- preserved_oauth2_integration = bound_integration is not None and not reentered_oauth2_secrets
+ # Some sources keep their connection target somewhere other than a named field — Custom's
+ # lives inside its manifest. An edit that introduces a new request host would send the
+ # preserved credential somewhere it wasn't going before, the same exfiltration risk, so
+ # require re-entry too. The source decides; the API never names the source type.
+ job_inputs_host_added = source.job_inputs_add_connection_host(incoming_job_inputs, existing_job_inputs)
+
+ # Some sources keep their secrets in a bound row, not job_inputs (Custom's
+ # CustomOAuth2Integration) — the generic preserved-credentials check can't see those, yet a
+ # host change would still redirect the row's injected token. The source reports whether such
+ # row-backed secrets are preserved (not re-entered) on this update.
+ preserved_row_backed_credentials = source.has_preserved_row_backed_credentials(instance, incoming_job_inputs)
- if connection_host_changed or ssh_tunnel_changed or manifest_host_added:
+ if connection_host_changed or ssh_tunnel_changed or job_inputs_host_added:
gate_sensitive_fields = sensitive_fields - _CREATION_ONLY_SECRET_FIELDS
preserved_credentials = has_preserved_credentials(
existing_job_inputs, incoming_job_inputs, gate_sensitive_fields
)
- if preserved_credentials or preserved_oauth2_integration:
+ if preserved_credentials or preserved_row_backed_credentials:
if ssh_tunnel_changed:
raise ValidationError("Changing the SSH tunnel requires re-entering your database credentials.")
- if manifest_host_added:
+ if job_inputs_host_added:
raise ValidationError("Changing the manifest's request host requires re-entering your credentials.")
raise ValidationError("Changing the connection host requires re-entering your credentials.")
@@ -1237,19 +1204,22 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
validated_job_inputs[key] = existing_job_inputs[key]
validated_data["job_inputs"] = validated_job_inputs
- github_old_repositories: list[str] = []
- if source_type_model == ExternalDataSourceType.GITHUB and job_inputs_were_submitted:
- github_old_repositories = github_repositories_for_job_inputs(existing_job_inputs)
+ # Namespaced-resource sources (GitHub repos) track their schema rows against a resource
+ # set in job_inputs; capture the old set before the write so we can reconcile after.
+ namespaced_adapter = get_namespaced_resource_adapter(source_type_model)
+ old_namespaced_resources: list[str] = []
+ if namespaced_adapter is not None and job_inputs_were_submitted:
+ old_namespaced_resources = namespaced_adapter.resources_for_job_inputs(existing_job_inputs)
updated_source: ExternalDataSource = super().update(instance, validated_data)
- if source_type_model == ExternalDataSourceType.GITHUB and job_inputs_were_submitted:
- # Adds schema rows for added repos, retires removed repos' rows, and reconciles the
- # per-repo webhooks. No-op when the effective repo list didn't change.
- reconcile_github_repositories(
+ if namespaced_adapter is not None and job_inputs_were_submitted:
+ # Adds schema rows for added resources, retires removed ones, and reconciles their
+ # webhooks. No-op when the effective resource list didn't change.
+ namespaced_adapter.reconcile_resources(
source_model=updated_source,
team=instance.team,
- old_repositories=github_old_repositories,
+ old_resources=old_namespaced_resources,
new_config=source_config,
)
@@ -1259,20 +1229,10 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
with transaction.atomic():
ExternalDataSource._base_manager.filter(pk=updated_source.pk).select_for_update().get()
- name_substitutions: dict[str, str] = {}
- if updated_source.source_type == ExternalDataSourceType.POSTGRES:
- name_substitutions = reconcile_postgres_refresh_name_substitutions(
- source=updated_source,
- source_schemas=discovered_schemas,
- team_id=instance.team_id,
- )
- elif source_namespace_is_blank(updated_source) and is_multi_schema_capable_sql_source(
- updated_source.source_type
- ):
- name_substitutions = apply_sql_warehouse_refresh_migration(
- source=updated_source,
- team_id=instance.team_id,
- )
+ engine = get_direct_query_engine(updated_source.direct_engine)
+ name_substitutions = _refresh_name_substitutions(
+ engine, source=updated_source, source_schemas=discovered_schemas, team_id=instance.team_id
+ )
if name_substitutions:
schema_names = {name_substitutions.get(name, name): label for name, label in schema_names.items()}
descriptions = {
@@ -1284,31 +1244,11 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
team_id=instance.team_id,
descriptions=descriptions,
)
- # Direct call (not via hook) so tests mocking `SourceRegistry.get_source` still
- # exercise the real direct-query DataWarehouseTable rebuild.
- if updated_source.source_type == ExternalDataSourceType.POSTGRES:
- reconcile_postgres_schemas(
- source=updated_source,
- source_schemas=discovered_schemas,
- team_id=instance.team_id,
- )
- elif updated_source.source_type == ExternalDataSourceType.SNOWFLAKE:
- reconcile_snowflake_schemas(
- source=updated_source,
- source_schemas=discovered_schemas,
- team_id=instance.team_id,
- )
- elif updated_source.source_type == ExternalDataSourceType.REDSHIFT:
- reconcile_redshift_schemas(
- source=updated_source,
- source_schemas=discovered_schemas,
- team_id=instance.team_id,
- )
- else:
- reconcile_mysql_schemas(
- source=updated_source,
- source_schemas=discovered_schemas,
- team_id=instance.team_id,
+ # Direct call on the engine adapter (not the source hook) so tests mocking
+ # `SourceRegistry.get_source` still exercise the real DataWarehouseTable rebuild.
+ if engine is not None:
+ engine.reconcile_schemas(
+ source=updated_source, source_schemas=discovered_schemas, team_id=instance.team_id
)
schemas = list(
@@ -2122,15 +2062,13 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
if isinstance(value, str):
payload[key] = value.strip()
source_type_model = ExternalDataSourceType(source_type)
- if (
- source_type_model == ExternalDataSourceType.CUSTOM
- and count_active_custom_sources(self.team_id) >= MAX_CUSTOM_SOURCES_PER_TEAM
- ):
+ source = SourceRegistry.get_source(source_type_model)
+ max_instances = source.max_instances_per_team
+ if max_instances is not None and count_active_sources(self.team_id, source_type_model) >= max_instances:
return Response(
status=status.HTTP_400_BAD_REQUEST,
- data={"message": CUSTOM_SOURCE_LIMIT_MESSAGE},
+ data={"message": f"You can create at most {max_instances} sources of this type per project."},
)
- source = SourceRegistry.get_source(source_type_model)
if skip_credential_validation:
source_config: Config = source.parse_config(payload)
else:
@@ -2158,16 +2096,8 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
direct_query_enabled=direct_query_enabled,
)
- if source_type_model == ExternalDataSourceType.CUSTOM:
- # Claim the OAuth2 integration row for the new source right away instead of waiting for the
- # first sync's trust-on-first-use claim, closing the window where another create by the same
- # user (matching the same unbound row) could adopt it. The guarded filter makes a lost race
- # a no-op; sync-time authorization remains the backstop.
- oauth2_integration_id = (new_source_model.job_inputs or {}).get("auth_oauth2_integration_id")
- if oauth2_integration_id:
- CustomOAuth2Integration.objects.for_team(self.team_id).filter(
- id=oauth2_integration_id, external_data_source__isnull=True
- ).update(external_data_source=new_source_model)
+ # Post-create hook (Custom claims its bound OAuth2 integration row here). No-op otherwise.
+ source.on_source_created(new_source_model, self.team_id)
# CDC: gate per-source-type adapter availability up front so downstream blocks
# can `if cdc_enabled` without repeating the source-type check.
@@ -2912,65 +2842,34 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
instance.connection_metadata = connection_metadata
instance.save(update_fields=["connection_metadata", "updated_at"])
# Migrate/dedupe legacy rows before sync_old_schemas; non-Postgres only once namespace cleared.
- name_substitutions: dict[str, str] = {}
- if instance.source_type == ExternalDataSourceType.POSTGRES:
- name_substitutions = reconcile_postgres_refresh_name_substitutions(
- source=instance,
- source_schemas=schemas,
- team_id=self.team_id,
- )
- elif source_namespace_is_blank(instance) and is_multi_schema_capable_sql_source(instance.source_type):
- name_substitutions = apply_sql_warehouse_refresh_migration(source=instance, team_id=self.team_id)
+ engine = get_direct_query_engine(instance.direct_engine)
+ name_substitutions = _refresh_name_substitutions(
+ engine, source=instance, source_schemas=schemas, team_id=self.team_id
+ )
if name_substitutions:
schema_names = {name_substitutions.get(name, name): label for name, label in schema_names.items()}
descriptions = {
name_substitutions.get(name, name): description for name, description in descriptions.items()
}
- # GitHub keeps its legacy repo's rows bare alongside qualified rows for added repos, so
- # bare↔qualified tail matching would wrongly collapse them; match names exactly and seed
- # the per-repo location metadata on newly created rows.
- is_github = instance.source_type == ExternalDataSourceType.GITHUB
+ # Namespaced-resource sources (GitHub) keep the legacy resource's rows bare alongside
+ # qualified rows for the others, so bare↔qualified tail matching would wrongly collapse
+ # them; match names exactly and seed per-resource location metadata on new rows.
+ namespaced_adapter = get_namespaced_resource_adapter(instance.source_type)
schemas_created, schemas_deleted = sync_old_schemas_with_new_schemas(
schema_names,
source_id=str(instance.id),
team_id=self.team_id,
descriptions=descriptions,
- strict_name_match=is_github,
- schema_metadata_by_name={s.name: s.schema_metadata for s in schemas if s.schema_metadata}
- if is_github
+ strict_name_match=namespaced_adapter is not None and namespaced_adapter.uses_strict_schema_name_match,
+ schema_metadata_by_name=namespaced_adapter.schema_metadata_by_name(schemas)
+ if namespaced_adapter is not None
else None,
)
- if instance.source_type == ExternalDataSourceType.POSTGRES:
- reconciled_deleted_schemas = reconcile_postgres_schemas(
- source=instance,
- source_schemas=schemas,
- team_id=self.team_id,
- )
- if reconciled_deleted_schemas:
- schemas_deleted = list({*schemas_deleted, *reconciled_deleted_schemas})
- elif instance.source_type == ExternalDataSourceType.MYSQL:
- reconciled_deleted_schemas = reconcile_mysql_schemas(
- source=instance,
- source_schemas=schemas,
- team_id=self.team_id,
- )
- if reconciled_deleted_schemas:
- schemas_deleted = list({*schemas_deleted, *reconciled_deleted_schemas})
- elif instance.source_type == ExternalDataSourceType.SNOWFLAKE:
- reconciled_deleted_schemas = reconcile_snowflake_schemas(
- source=instance,
- source_schemas=schemas,
- team_id=self.team_id,
- )
- if reconciled_deleted_schemas:
- schemas_deleted = list({*schemas_deleted, *reconciled_deleted_schemas})
- elif instance.source_type == ExternalDataSourceType.REDSHIFT:
- reconciled_deleted_schemas = reconcile_redshift_schemas(
- source=instance,
- source_schemas=schemas,
- team_id=self.team_id,
+ if engine is not None:
+ reconciled_deleted_schemas = engine.reconcile_schemas(
+ source=instance, source_schemas=schemas, team_id=self.team_id
)
if reconciled_deleted_schemas:
schemas_deleted = list({*schemas_deleted, *reconciled_deleted_schemas})
@@ -3088,8 +2987,9 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
# which makes a network round-trip per call. With large schema lists (e.g. Slack workspaces with
# thousands of channels) the per-iteration call inflated the response loop past the 120s gateway.
cdc_enabled = is_cdc_enabled_for_team(self.team)
- # xmin is Postgres-only — gate on the source type so the capability never leaks to another SQL source.
- is_postgres = source_type_model == ExternalDataSourceType.POSTGRES
+ # xmin is gated at the source-type level by the source's capability flag so it never
+ # leaks to another SQL source.
+ xmin_capable = source.supports_xmin
data = [
{
"table": schema.name,
@@ -3099,7 +2999,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
"incremental_available": schema.supports_incremental,
"append_available": schema.supports_append,
"cdc_available": schema.supports_cdc if cdc_enabled else None,
- "xmin_available": schema.supports_xmin if is_postgres else None,
+ "xmin_available": schema.supports_xmin if xmin_capable else None,
"incremental_field": schema.incremental_fields[0]["field"]
if len(schema.incremental_fields) > 0 and len(schema.incremental_fields[0]["field"]) > 0
else None,
diff --git a/products/data_warehouse/backend/test/test_direct_query_engines.py b/products/data_warehouse/backend/test/test_direct_query_engines.py
index ca10698f0749..e46fed18eafa 100644
--- a/products/data_warehouse/backend/test/test_direct_query_engines.py
+++ b/products/data_warehouse/backend/test/test_direct_query_engines.py
@@ -82,6 +82,14 @@ class TestDirectQueryEngineRegistry:
)
assert location == ("WAREHOUSE", "analytics", "events")
+ @parameterized.expand(["mysql", "snowflake", "redshift"])
+ def test_non_postgres_engines_return_no_name_substitutions(self, engine: str):
+ # Returning None (not {}) is the sentinel that makes the view fall through to the generic
+ # multi-schema migration path; only Postgres has bespoke legacy-row remapping.
+ adapter = get_direct_query_engine(engine)
+ assert adapter is not None
+ assert adapter.refresh_name_substitutions(source=None, source_schemas=[], team_id=1) is None
+
def test_snowflake_default_schema_takes_precedence_over_dot_split(self):
adapter = get_direct_query_engine("snowflake")
assert adapter is not None
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 8688db8771dd..482c81a33ec2 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
@@ -115,9 +115,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads
def _configure_source_mock_versioning(mock_get_source) -> None:
"""Tests that patch `SourceRegistry.get_source` with a bare MagicMock must give the versioning
attributes real values: the create path persists `default_version` into the `api_version`
- column, and the serializer renders `get_version_deprecation` into the response."""
+ column, and the serializer renders `get_version_deprecation` into the response. The create path
+ also reads `max_instances_per_team` to enforce the per-team source limit — leave it unset so the
+ limit check is skipped rather than comparing against a MagicMock.
+
+ The update path also asks the source whether an edit introduces a new connection host or leaves
+ row-backed credentials preserved; a bare MagicMock returns truthy for both, which would wrongly
+ trip the credential-reentry gate. Stub them to their real (falsy) defaults."""
mock_get_source.return_value.default_version = "v1"
mock_get_source.return_value.get_version_deprecation.return_value = None
+ mock_get_source.return_value.max_instances_per_team = None
+ mock_get_source.return_value.connection_host_fields = []
+ mock_get_source.return_value.server_managed_job_input_fields.return_value = []
+ mock_get_source.return_value.job_inputs_add_connection_host.return_value = False
+ mock_get_source.return_value.has_preserved_row_backed_credentials.return_value = False
class TestExternalDataSource(APIBaseTest):
@@ -7810,7 +7821,7 @@ class TestExternalDataSource(APIBaseTest):
# Every case 400s; only the at-limit case is blocked *by the per-team limit* — the
# excluded cases stay under the limit and fail later on the (empty) manifest instead.
- limit_message = f"You can create at most {MAX_CUSTOM_SOURCES_PER_TEAM} custom sources per project."
+ limit_message = f"You can create at most {MAX_CUSTOM_SOURCES_PER_TEAM} sources of this type per project."
assert response.status_code == status.HTTP_400_BAD_REQUEST
if expect_blocked:
assert response.json()["message"] == limit_message
diff --git a/products/data_warehouse/backend/tests/api/test_postgres_warehouse_migration.py b/products/data_warehouse/backend/tests/api/test_postgres_warehouse_migration.py
index b0d9018f3734..921d0942eefc 100644
--- a/products/data_warehouse/backend/tests/api/test_postgres_warehouse_migration.py
+++ b/products/data_warehouse/backend/tests/api/test_postgres_warehouse_migration.py
@@ -17,6 +17,16 @@ from products.warehouse_sources.backend.facade.models import DataWarehouseTable,
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+def _stub_source_security_gate(source_mock) -> None:
+ """The update path asks the source whether an edit introduces a new connection host or leaves
+ row-backed credentials preserved; a bare MagicMock returns truthy for both, which would wrongly
+ trip the credential-reentry gate. Stub them to their real (falsy) defaults."""
+ source_mock.connection_host_fields = []
+ source_mock.server_managed_job_input_fields.return_value = []
+ source_mock.job_inputs_add_connection_host.return_value = False
+ source_mock.has_preserved_row_backed_credentials.return_value = False
+
+
class TestPostgresWarehouseMigration(APIBaseTest):
@patch("products.data_warehouse.backend.presentation.views.external_data_source.SourceRegistry.get_source")
def test_refresh_schemas_qualifies_legacy_warehouse_rows_in_place(self, mock_get_source):
@@ -319,6 +329,7 @@ class TestPostgresWarehouseMigration(APIBaseTest):
source_mock.validate_config.return_value = (True, [])
source_mock.validate_credentials_for_access_method.return_value = (True, None)
source_mock.validate_credentials.return_value = (True, None)
+ _stub_source_security_gate(source_mock)
source = ExternalDataSource.objects.create(
team_id=self.team.pk,
@@ -403,6 +414,7 @@ class TestPostgresWarehouseMigration(APIBaseTest):
source_mock.validate_config.return_value = (True, [])
source_mock.validate_credentials_for_access_method.return_value = (True, None)
source_mock.validate_credentials.return_value = (True, None)
+ _stub_source_security_gate(source_mock)
source = ExternalDataSource.objects.create(
team_id=self.team.pk,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index ed710af5e2e2..b900268f75f6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
@@ -140,6 +140,12 @@ class _BaseSource(ABC, Generic[ConfigType]):
# `get_schemas` with a placeholder config could connect, hang, or close the DB session.
lists_tables_without_credentials: bool = False
+ # `True` only for sources whose engine supports xmin-based incremental replication
+ # (Postgres). Gates the xmin sync type at the source-type level; per-table availability is
+ # still decided by `SourceSchema.supports_xmin` at discovery. The API branches on this flag
+ # instead of naming the source type.
+ supports_xmin: bool = False
+
# Vendor API versions this source implements, as opaque vendor labels (Stripe date
# versions, semver, names) — never parsed or ordered by the framework. Sources whose
# vendor has no meaningful API versioning keep the `UNVERSIONED_API_VERSION` default.
@@ -311,6 +317,41 @@ class _BaseSource(ABC, Generic[ConfigType]):
a differently named field (e.g. Okta's ``okta_domain``) should list it here."""
return []
+ def server_managed_job_input_fields(
+ self, incoming_job_inputs: dict[str, Any], existing_job_inputs: dict[str, Any]
+ ) -> list[str]:
+ """``job_inputs`` fields the client may not set/repoint on update — the server pins them
+ to the stored value (or drops them when unset). Used for server-owned markers and pointers
+ (Custom's ``auth_oauth2_integration_id``, GitHub's legacy ``repository``). Given both the
+ incoming and existing inputs so a source can gate on context. Default: none."""
+ return []
+
+ # Cap on how many active sources of this type a team may have (``None`` = unlimited). Custom
+ # sources are capped; everything else is open. The API enforces this at create.
+ max_instances_per_team: int | None = None
+
+ def job_inputs_add_connection_host(
+ self, incoming_job_inputs: dict[str, Any], existing_job_inputs: dict[str, Any]
+ ) -> bool:
+ """Whether an update introduces a new outbound connection host that isn't a named
+ ``connection_host_fields`` change — e.g. Custom's target lives inside its manifest. When
+ ``True`` the API requires credential re-entry (same exfiltration gate as a host change).
+ Default: no such field."""
+ return False
+
+ def has_preserved_row_backed_credentials(
+ self, source_model: "ExternalDataSource", incoming_job_inputs: dict[str, Any]
+ ) -> bool:
+ """For sources whose secrets live in a bound row (not ``job_inputs``) — Custom's
+ ``CustomOAuth2Integration``: whether the row still holds secrets the editor did NOT re-enter
+ on this update. ``has_preserved_credentials`` can't see those, so a host change would still
+ redirect the row's injected token. Default: no row-backed credentials."""
+ return False
+
+ def on_source_created(self, source_model: "ExternalDataSource", team_id: int) -> None:
+ """Post-create hook. Custom claims its OAuth2 integration row here. No-op by default."""
+ return None
+
def cleanup_cdc_resources_on_deletion(self, source: "ExternalDataSource") -> None:
"""Best-effort teardown of CDC resources tied to the source. No-op by default."""
return None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
index 10b0933269f6..aedfc7c66faa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
@@ -663,6 +663,62 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CUSTOM
+ # Custom REST sources are capped per team to keep abuse of the arbitrary-URL fetcher bounded.
+ max_instances_per_team = MAX_CUSTOM_SOURCES_PER_TEAM
+
+ def server_managed_job_input_fields(self, incoming_job_inputs, existing_job_inputs):
+ # The OAuth2 integration row pointer is server-managed: pin it so an editor can't repoint
+ # the source at a different row (and through it, different credentials). Re-entered
+ # auth_oauth2_* secrets flow into the pinned row during credential validation.
+ return ["auth_oauth2_integration_id"]
+
+ def job_inputs_add_connection_host(self, incoming_job_inputs, existing_job_inputs):
+ # The custom source's connection target lives inside the manifest, not a top-level `host`.
+ # A manifest edit that introduces a new request host would send the preserved credential
+ # somewhere it wasn't going before — the same exfiltration risk, so require re-entry.
+ if "manifest_json" not in incoming_job_inputs:
+ return False
+ new_hosts = manifest_request_hosts(incoming_job_inputs.get("manifest_json"))
+ existing_hosts = manifest_request_hosts(existing_job_inputs.get("manifest_json"))
+ return bool(new_hosts - existing_hosts)
+
+ def has_preserved_row_backed_credentials(self, source_model, incoming_job_inputs):
+ # A row-backed OAuth2 custom source carries no secret in job_inputs — the client secret +
+ # tokens live in the bound CustomOAuth2Integration row and are injected at sync time, so the
+ # generic preserved-credentials check never sees them. A host change would still redirect the
+ # row's injected token, so treat the row's secrets as preserved unless the editor re-entered
+ # every one the row holds (adoption on config change replaces them with the typed values).
+ bound_integration = (
+ CustomOAuth2Integration.objects.for_team(source_model.team_id)
+ .filter(external_data_source=source_model)
+ .first()
+ )
+ if bound_integration is None:
+ return False
+ held_secret_fields = [
+ incoming_field
+ for row_key, incoming_field in (
+ ("client_secret", "auth_oauth2_client_secret"),
+ ("refresh_token", "auth_oauth2_refresh_token"),
+ )
+ if bound_integration.sensitive_config.get(row_key)
+ ]
+ reentered_oauth2_secrets = bool(held_secret_fields) and all(
+ bool(incoming_job_inputs.get(field)) for field in held_secret_fields
+ )
+ return not reentered_oauth2_secrets
+
+ def on_source_created(self, source_model, team_id):
+ # Claim the OAuth2 integration row for the new source right away instead of waiting for the
+ # first sync's trust-on-first-use claim, closing the window where another create by the same
+ # user (matching the same unbound row) could adopt it. The guarded filter makes a lost race
+ # a no-op; sync-time authorization remains the backstop.
+ oauth2_integration_id = (source_model.job_inputs or {}).get("auth_oauth2_integration_id")
+ if oauth2_integration_id:
+ CustomOAuth2Integration.objects.for_team(team_id).filter(
+ id=oauth2_integration_id, external_data_source__isnull=True
+ ).update(external_data_source=source_model)
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
index d466e3313cf6..dd05e0714f93 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
@@ -99,6 +99,15 @@ class GithubSource(
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GITHUB
+ def server_managed_job_input_fields(self, incoming_job_inputs, existing_job_inputs):
+ # The legacy `repository` is a server-managed marker once the multi-repo `repositories`
+ # field is in play: it defines which repo's schema rows keep bare (unqualified) names, so an
+ # edit can't rename or re-point it. Legacy-only PATCHes (no `repositories`) keep the original
+ # single-repo swap semantics, so it isn't pinned then.
+ if "repositories" in incoming_job_inputs or "repositories" in existing_job_inputs:
+ return ["repository"]
+ return []
+
@property
def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
from products.warehouse_sources.backend.temporal.data_imports.sources.github.webhook_template import template
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
index 690eee55be12..917a64fb31ac 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
@@ -206,6 +206,10 @@ _SSH_GATEWAY_UNREACHABLE_MESSAGE = (
@SourceRegistry.register
class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):
+ # xmin replication is Postgres-only; per-table availability is still decided by
+ # `SourceSchema.supports_xmin` at discovery.
+ supports_xmin = True
+
def __init__(self, source_name: str = "Postgres"):
super().__init__()
self.source_name = source_name