:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): support multiple repositories in github source (#71274)
Tom Owers5d3a03668256
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex dd64f828cf9b..0685b422c58b 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -45067,6 +45067,10 @@"caption": {"type": "string"},+ "hidden": {+ "description": "Keep the field in the config tree (so its value parses and survives job_inputs redaction) without rendering it in the source form. Used for legacy fields that a newer field supersedes.",+ "type": "boolean"+ },"integrationField": {"description": "Name of the OAuth integration id field this account selector reads from.","type": "string"@@ -45078,6 +45082,10 @@"label": {"type": "string"},+ "multiple": {+ "description": "Allow selecting multiple values; the field's payload value becomes string[].",+ "type": "boolean"+ },"name": {"type": "string"},diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 4ffc532492e5..5cfaf4ad6cd1 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -6696,6 +6696,14 @@ export interface SourceFieldOauthAccountSelectConfig {placeholder?: stringcaption?: stringrequired?: boolean+ /** Allow selecting multiple values; the field's payload value becomes string[]. */+ multiple?: boolean+ /**+ * Keep the field in the config tree (so its value parses and survives job_inputs+ * redaction) without rendering it in the source form. Used for legacy fields that+ * a newer field supersedes.+ */+ hidden?: boolean}export type SourceFieldSelectConfigConverter = 'str_to_int' | 'str_to_bool' | 'str_to_optional_int'diff --git a/posthog/schema.py b/posthog/schema.pyindex 015927c1054e..2c932e653e95 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -2521,6 +2521,14 @@ class SourceFieldOauthAccountSelectConfig(BaseModel):extra="forbid",)caption: str | None = None+ hidden: bool | None = Field(+ default=None,+ description=(+ "Keep the field in the config tree (so its value parses and survives"+ " job_inputs redaction) without rendering it in the source form. Used for"+ " legacy fields that a newer field supersedes."+ ),+ )integrationField: str = Field(...,description=("Name of the OAuth integration id field this account selector reads from."),@@ -2530,6 +2538,10 @@ class SourceFieldOauthAccountSelectConfig(BaseModel):description="Integration kind to validate and route the account fetch through.",)label: str+ multiple: bool | None = Field(+ default=None,+ description=("Allow selecting multiple values; the field's payload value becomes string[]."),+ )name: strplaceholder: str | None = Nonerequired: bool | None = Nonediff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.pyindex 0b48a750f28e..8b45647d896f 100644--- a/products/data_warehouse/backend/facade/api.py+++ b/products/data_warehouse/backend/facade/api.py@@ -81,6 +81,8 @@ _LAZY = {"hide_direct_redshift_table": "direct_redshift","upsert_direct_redshift_table": "direct_redshift","reconcile_refresh_name_substitutions": "postgres_warehouse_migration",+ "github_repositories_for_job_inputs": "github_warehouse_repos",+ "reconcile_github_repositories": "github_warehouse_repos","apply_on_refresh": "sql_warehouse_migration","apply_on_schema_clear": "sql_warehouse_migration","detect_schema_clear_transition": "sql_warehouse_migration",diff --git a/products/data_warehouse/backend/github_warehouse_repos.py b/products/data_warehouse/backend/github_warehouse_repos.pynew file mode 100644index 000000000000..532529d19eeb--- /dev/null+++ b/products/data_warehouse/backend/github_warehouse_repos.py@@ -0,0 +1,153 @@+"""Reconcile a GitHub warehouse source after its repository list changes.++A GitHub source syncs N repos through one set of `ExternalDataSchema` rows per repo × endpoint+(the legacy pre-multi-repo repo keeps bare endpoint names; every other repo is qualified as+`owner/repo.endpoint`) and one webhook HogFunction whose `schema_mapping` routes incoming events+per repo. When a PATCH changes `job_inputs.repositories`, this module:++- creates schema rows for added repos (strict name matching, so a qualified `owner/repo.issues`+ never collapses onto the legacy bare `issues` row) with their location metadata seeded,+- disables/soft-deletes removed repos' rows via the standard discovery-removal policy,+- creates hooks in added repos (pinned to the source's existing signing secret), deletes hooks+ from removed repos, and rewrites `schema_mapping` from scratch so removed repos are pruned.++Webhook failures never fail the PATCH — job_inputs are already persisted, the 6h schema-discovery+activity self-heals missing rows, and hook drift is surfaced by the webhook status endpoint.+"""++from typing import Any, cast++import structlog++from posthog.exceptions_capture import capture_exception+from posthog.models import Team++from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.data_warehouse.backend.logic.external_data_source.webhooks import get_webhook_url+from products.warehouse_sources.backend.facade.models import (+ ExternalDataSchema,+ ExternalDataSource,+ sync_old_schemas_with_new_schemas,+)+from products.warehouse_sources.backend.facade.source_management import GithubSource, SourceRegistry+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType++logger = structlog.get_logger(__name__)+++def github_repositories_for_job_inputs(job_inputs: dict[str, Any] | None) -> list[str]:+ """The effective repo list for stored GitHub job_inputs; [] when unparseable or unset."""+ source = cast(GithubSource, SourceRegistry.get_source(ExternalDataSourceType.GITHUB))+ try:+ return GithubSource.effective_repositories(source.parse_config(job_inputs or {}))+ except Exception:+ return []+++def reconcile_github_repositories(+ *,+ source_model: ExternalDataSource,+ team: Team,+ old_repositories: list[str],+ new_config: Any,+) -> None:+ """Bring schema rows and repo webhooks in line with the (already persisted) new repo list."""+ source = cast(GithubSource, SourceRegistry.get_source(ExternalDataSourceType.GITHUB))+ try:+ new_repositories = GithubSource.effective_repositories(new_config)+ except ValueError:+ new_repositories = []+ if new_repositories == old_repositories:+ return++ source_schemas = source.get_schemas(new_config, team.pk)+ sync_old_schemas_with_new_schemas(+ {schema.name: schema.label for schema in source_schemas},+ source_id=str(source_model.id),+ team_id=team.pk,+ strict_name_match=True,+ schema_metadata_by_name={+ schema.name: schema.schema_metadata for schema in source_schemas if schema.schema_metadata+ },+ )++ try:+ _reconcile_repo_webhooks(+ source=source,+ source_model=source_model,+ team=team,+ new_config=new_config,+ source_schemas=source_schemas,+ added=[repo for repo in new_repositories if repo not in old_repositories],+ removed=[repo for repo in old_repositories if repo not in new_repositories],+ )+ except Exception as e:+ # Hook drift is recoverable (webhook status endpoint + idempotent re-create); a failed+ # PATCH after job_inputs persisted is not.+ capture_exception(e, {"source_id": str(source_model.id), "team_id": team.pk})+ logger.exception("github_repo_webhook_reconcile_failed", source_id=str(source_model.id), error=str(e))+++def _reconcile_repo_webhooks(+ *,+ source: GithubSource,+ source_model: ExternalDataSource,+ team: Team,+ new_config: Any,+ source_schemas: list[Any],+ added: list[str],+ removed: list[str],+) -> None:+ hog_function = HogFunction.objects.filter(+ team=team,+ type="warehouse_source_webhook",+ inputs__source_id__value=str(source_model.id),+ deleted=False,+ ).first()+ if hog_function is None:+ # No webhook set up for this source — nothing to create hooks against. Rows for added+ # repos stay poll-based until the user sets the webhook up, which covers every repo.+ return++ webhook_url = get_webhook_url(str(hog_function.id))+ signing_secret = ((hog_function.encrypted_inputs or {}).get("signing_secret") or {}).get("value")++ failures: list[str] = []+ if added:+ if signing_secret:+ failures.extend(+ source.ensure_webhooks_for_repositories(new_config, webhook_url, team.pk, added, signing_secret)+ )+ else:+ failures.append(+ "no signing secret is stored for this source's webhook; re-create the webhook to cover the added repositories"+ )+ if removed:+ failures.extend(source.delete_webhooks_for_repositories(new_config, webhook_url, team.pk, removed))+ if failures:+ logger.warning(+ "github_repo_webhook_reconcile_partial",+ source_id=str(source_model.id),+ failures=failures,+ )++ # Rewrite the mapping from scratch (not merge) so removed repos' keys are pruned. Newly added+ # repos' webhook-capable rows are created disabled and join the mapping when the user enables+ # them through the schema update path.+ webhook_capable = {schema.name for schema in source_schemas if schema.supports_webhooks}+ eligible_schemas = ExternalDataSchema.objects.filter(+ source_id=source_model.id,+ team_id=team.pk,+ sync_type=ExternalDataSchema.SyncType.WEBHOOK,+ should_sync=True,+ name__in=webhook_capable,+ ).exclude(deleted=True)+ schema_mapping = {source.webhook_mapping_key(schema.name): str(schema.id) for schema in eligible_schemas}+ # Re-pin the legacy repository alongside the mapping so the template's bare-key fallback stays+ # bound to it — a mixed legacy+multi-repo source is exactly the case the fallback could leak.+ hog_function.inputs = {+ **(hog_function.inputs or {}),+ "schema_mapping": {"value": schema_mapping},+ **{key: {"value": value} for key, value in source.webhook_template_inputs(new_config).items()},+ }+ hog_function.save(update_fields=["inputs", "encrypted_inputs"])diff --git a/products/data_warehouse/backend/logic/external_data_source/test/test_webhooks.py b/products/data_warehouse/backend/logic/external_data_source/test/test_webhooks.pyindex 723c6d200aba..0d913e5e823e 100644--- a/products/data_warehouse/backend/logic/external_data_source/test/test_webhooks.py+++ b/products/data_warehouse/backend/logic/external_data_source/test/test_webhooks.py@@ -86,6 +86,9 @@ def _make_webhook_source("Customers": "customer","Invoices": "invoice",}+ # Mirror the real `WebhookSource.webhook_mapping_key` default: translate via the resource+ # map, falling back to the bare schema name.+ source.webhook_mapping_key.side_effect = lambda name: source.webhook_resource_map.get(name, name)return sourcediff --git a/products/data_warehouse/backend/logic/external_data_source/webhooks.py b/products/data_warehouse/backend/logic/external_data_source/webhooks.pyindex b24274c7a47b..e77dd15b1f3a 100644--- a/products/data_warehouse/backend/logic/external_data_source/webhooks.py+++ b/products/data_warehouse/backend/logic/external_data_source/webhooks.py@@ -48,6 +48,7 @@ def get_or_create_webhook_hog_function(source_id: str,eligible_schemas: list[ExternalDataSchema],extra_inputs: dict[str, Any] | None = None,+ config: Config | None = None,) -> WebhookHogFunctionCreateResult:"""Create or update a HogFunction for webhook-based data imports."""@@ -56,19 +57,15 @@ def get_or_create_webhook_hog_function(return WebhookHogFunctionCreateResult(error="No webhook template available for this source")schema_mapping: dict[str, str] = {}- object_type_map = source.webhook_resource_mapfor schema in eligible_schemas:- schema_id_str = str(schema.id)-- # Fall back to the schema name as the object type when the resource map- # doesn't have an explicit entry (e.g. Slack channels use the channel ID- # as both the schema name and the webhook event key, so there's nothing- # to translate). Callers pre-filter `eligible_schemas` to schemas the- # source declared as webhook-eligible, so this fallback only fires for- # schemas we genuinely want events routed to.- object_type = object_type_map.get(schema.name, schema.name)- schema_mapping[object_type] = schema_id_str+ # `webhook_mapping_key` defaults to the resource-map translation, falling back to the+ # schema name when the map has no entry (e.g. Slack channels use the channel ID as both+ # the schema name and the webhook event key, so there's nothing to translate). Sources+ # with namespaced schemas (GitHub repos) override it to emit namespace-qualified keys.+ # Callers pre-filter `eligible_schemas` to schemas the source declared as+ # webhook-eligible, so this only fires for schemas we genuinely want events routed to.+ schema_mapping[source.webhook_mapping_key(schema.name)] = str(schema.id)db_template = HogFunctionTemplate.get_template(webhook_template.id)if not db_template:@@ -80,6 +77,11 @@ def get_or_create_webhook_hog_function("schema_mapping": {"value": schema_mapping},"source_id": {"value": source_id},}+ # Static template inputs the source pins on every write (GitHub's legacy_repository, which gates+ # the template's bare-event fallback). Set here rather than merged so it survives a rewrite of+ # `inputs` on update and can't drift out of sync with the schema mapping.+ if config is not None:+ inputs.update({key: {"value": value} for key, value in source.webhook_template_inputs(config).items()})if extra_inputs:inputs.update({key: {"value": value} for key, value in extra_inputs.items()})diff --git a/products/data_warehouse/backend/presentation/views/external_data_schema.py b/products/data_warehouse/backend/presentation/views/external_data_schema.pyindex 899dd3084b4d..9897ad70f93b 100644--- a/products/data_warehouse/backend/presentation/views/external_data_schema.py+++ b/products/data_warehouse/backend/presentation/views/external_data_schema.py@@ -1204,6 +1204,7 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):source=source_impl,source_id=str(source.pk),eligible_schemas=[schema],+ config=config,)if hog_fn_result.error or not hog_fn_result.hog_function:diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.pyindex be374d869e1d..90e4d63ca8b7 100644--- a/products/data_warehouse/backend/presentation/views/external_data_source.py+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py@@ -82,11 +82,13 @@ from products.data_warehouse.backend.facade.api import (get_postgres_source_location,get_redshift_source_location,get_webhook_url,+ github_repositories_for_job_inputs,is_any_external_data_schema_paused,is_cdc_enabled_for_team,is_custom_source_ai_builder_enabled_for_team,is_multi_schema_capable_sql_source,is_xmin_enabled_for_team,+ reconcile_github_repositories,reconcile_mysql_schemas,reconcile_postgres_schemas,reconcile_redshift_schemas,@@ -1027,6 +1029,18 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerelse: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.@@ -1233,8 +1247,22 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializervalidated_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)+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(+ source_model=updated_source,+ team=instance.team,+ old_repositories=github_old_repositories,+ new_config=source_config,+ )+if updated_source.is_direct_query and discovered_schemas is not None:schema_names = {schema.name: schema.label for schema in discovered_schemas}descriptions = {schema.name: schema.description for schema in discovered_schemas}@@ -2386,6 +2414,11 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiif source.supports_column_selectionelse {})+ # Sources that namespace tables outside SQL schemas (e.g. GitHub repos) attach their+ # own location keys on the discovered schema; persist them so sync-time resolution+ # never depends on parsing the row name.+ if source_schema is not None and source_schema.schema_metadata:+ schema_metadata = {**schema_metadata, **source_schema.schema_metadata}if row_filters is not None:# Only sources that push filters into their query (SQL WHERE) can honor them — a@@ -2969,11 +3002,19 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixidescriptions = {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.GITHUBschemas_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+ else None,)if instance.source_type == ExternalDataSourceType.POSTGRES:@@ -3422,6 +3463,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixisource=source,source_id=str(instance.pk),eligible_schemas=eligible_schemas,+ config=source_config,)if hog_fn_result.error or hog_fn_result.hog_function is None:return failure(hog_fn_result.error)@@ -4539,6 +4581,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixisource=source,source_id=str(instance.pk),eligible_schemas=eligible_schemas,+ config=config,)if hog_fn_result.error: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.pyindex 5568c6234661..5f54691336f5 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@@ -11630,3 +11630,151 @@ class TestGetDirectConnectionMetadata(SimpleTestCase):self.assertEqual(result, {})mock_capture.assert_called_once_with(error)+++class TestGithubMultiRepoPatch(APIBaseTest):+ def _create_github_source(self, job_inputs: dict) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type="Github",+ created_by=self.user,+ prefix="gh",+ job_inputs=job_inputs,+ )++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.source.GithubSource.validate_credentials",+ return_value=(True, None),+ )+ def test_patch_adding_repo_creates_qualified_rows_and_pins_legacy_marker(self, _mock_validate):+ source = self._create_github_source(+ {+ "auth_method": {"selection": "pat", "personal_access_token": "ghp_secret"},+ "repository": "org/repo",+ }+ )+ legacy_row = ExternalDataSchema.objects.create(+ team_id=self.team.pk, source_id=source.pk, name="issues", should_sync=True+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={+ "job_inputs": {+ "auth_method": {"selection": "pat"},+ "repositories": ["org/repo", "acme/other"],+ # A client must not be able to re-point the bare-naming marker: renaming it+ # would detach the legacy rows' tables.+ "repository": "attacker/override",+ }+ },+ )+ assert response.status_code == 200, response.json()++ source.refresh_from_db()+ assert source.job_inputs["repository"] == "org/repo"+ assert source.job_inputs["repositories"] == ["org/repo", "acme/other"]++ legacy_row.refresh_from_db()+ assert legacy_row.should_sync is True+ assert legacy_row.name == "issues"++ new_row = ExternalDataSchema.objects.get(team_id=self.team.pk, source_id=source.pk, name="acme/other.issues")+ assert new_row.should_sync is False+ assert new_row.sync_type_config.get("schema_metadata") == {+ "source_repository": "acme/other",+ "source_endpoint": "issues",+ }+ # The legacy repo keeps bare names — no qualified duplicates for it.+ assert not ExternalDataSchema.objects.filter(+ team_id=self.team.pk, source_id=source.pk, name="org/repo.issues"+ ).exists()++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.source.GithubSource.delete_webhooks_for_repositories",+ return_value=[],+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.source.GithubSource.ensure_webhooks_for_repositories",+ return_value=[],+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.source.GithubSource.validate_credentials",+ return_value=(True, None),+ )+ def test_patch_repo_change_reconciles_webhooks_and_prunes_mapping(self, _mock_validate, mock_ensure, mock_delete):+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction+ from products.warehouse_sources.backend.temporal.data_imports.sources.github.webhook_template import (+ template as github_webhook_template,+ )++ source = self._create_github_source(+ {+ "auth_method": {"selection": "pat", "personal_access_token": "ghp_secret"},+ "repository": "org/repo",+ "repositories": ["org/repo", "acme/other"],+ }+ )+ legacy_webhook_row = ExternalDataSchema.objects.create(+ team_id=self.team.pk,+ source_id=source.pk,+ name="workflow_runs",+ should_sync=True,+ sync_type=ExternalDataSchema.SyncType.WEBHOOK,+ )+ removed_webhook_row = ExternalDataSchema.objects.create(+ team_id=self.team.pk,+ source_id=source.pk,+ name="acme/other.workflow_runs",+ should_sync=True,+ sync_type=ExternalDataSchema.SyncType.WEBHOOK,+ sync_type_config={+ "schema_metadata": {"source_repository": "acme/other", "source_endpoint": "workflow_runs"}+ },+ )+ hog_function = HogFunction.objects.create(+ team=self.team,+ type="warehouse_source_webhook",+ name="GitHub webhook",+ enabled=True,+ inputs_schema=github_webhook_template.inputs_schema,+ inputs={+ "source_id": {"value": str(source.pk)},+ "schema_mapping": {+ "value": {+ "workflow_run": str(legacy_webhook_row.id),+ "acme/other.workflow_run": str(removed_webhook_row.id),+ }+ },+ "signing_secret": {"value": "sekret"},+ },+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={+ "job_inputs": {+ "auth_method": {"selection": "pat"},+ "repositories": ["org/repo", "new/repo"],+ }+ },+ )+ assert response.status_code == 200, response.json()++ # New repo's hooks are pinned to the source's existing secret; removed repo's hook deleted.+ assert mock_ensure.call_args.args[3] == ["new/repo"]+ assert mock_ensure.call_args.args[4] == "sekret"+ assert mock_delete.call_args.args[3] == ["acme/other"]++ # Mapping is rewritten, pruning the removed repo — a merge would leave its key routing+ # events into a disabled schema forever.+ hog_function.refresh_from_db()+ assert hog_function.inputs is not None+ mapping = hog_function.inputs["schema_mapping"]["value"]+ assert mapping == {"workflow_run": str(legacy_webhook_row.id)}++ removed_webhook_row.refresh_from_db()+ assert removed_webhook_row.deleted is True or removed_webhook_row.should_sync is Falsediff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsxindex 15057ead72b2..6ad7e4ec92ed 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx@@ -174,6 +174,11 @@ export const buildKeaFormDefaultFromSourceDetails = (return}+ if (field.type === 'oauth-account-select' && field.multiple) {+ obj[field.name] = []+ return+ }+// All other typesobj[field.name] = ''}@@ -1888,8 +1893,14 @@ export const getErrorsForFields = (return}- if ('required' in field && field.required && !valueObj[field.name]) {- errorsObj[field.name] = `Please enter a ${field.label.toLowerCase()}`+ // An empty array is truthy, so multi-value fields (e.g. repo pickers) need their own+ // emptiness check or `required` would pass with zero selections.+ const fieldValue = valueObj[field.name]+ const valueMissing = Array.isArray(fieldValue) ? fieldValue.length === 0 : !fieldValue+ if ('required' in field && field.required && valueMissing) {+ errorsObj[field.name] = Array.isArray(fieldValue)+ ? `Please enter at least one of your ${field.label.toLowerCase()}`+ : `Please enter a ${field.label.toLowerCase()}`}}diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardValidation.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardValidation.test.tsnew file mode 100644index 000000000000..20ca323dc94b--- /dev/null+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardValidation.test.ts@@ -0,0 +1,54 @@+import type { SourceFieldConfig } from '~/queries/schema/schema-general'++import { normalizeMultiValue } from '../../shared/components/forms/IntegrationAccountSelector'+import { getErrorsForFields } from './sourceWizardLogic'++const REPOSITORIES_FIELD: SourceFieldConfig = {+ type: 'oauth-account-select',+ name: 'repositories',+ label: 'Repositories',+ integrationField: 'github_integration_id',+ integrationKind: 'github',+ required: true,+ multiple: true,+}++describe('source wizard multi-value fields', () => {+ describe('getErrorsForFields', () => {+ // An empty array is truthy, so without the explicit length check "Next" would proceed+ // with zero repositories selected.+ it.each([+ [[], 'Please enter at least one of your repositories'],+ [undefined, 'Please enter a repositories'],+ [['posthog/posthog'], undefined],+ ])('required multi field with value %p yields error %p', (value, expectedError) => {+ const errors = getErrorsForFields([REPOSITORIES_FIELD], {+ prefix: '',+ payload: { repositories: value },+ })+ expect(errors.payload.repositories).toEqual(expectedError)+ })++ it('does not flag optional multi fields', () => {+ const errors = getErrorsForFields([{ ...REPOSITORIES_FIELD, required: false }], {+ prefix: '',+ payload: { repositories: [] },+ })+ expect(errors.payload.repositories).toBeUndefined()+ })+ })++ describe('normalizeMultiValue', () => {+ it.each([+ [undefined, undefined, []],+ ['', undefined, []],+ ['a/b', undefined, ['a/b']],+ [[' a/b ', 'a/b', '', 'c/d'], undefined, ['a/b', 'c/d']],+ // Legacy single-repo sources only store `repository`; it must seed the picker.+ [[], 'legacy/repo', ['legacy/repo']],+ [['a/b'], 'legacy/repo', ['a/b']],+ ])('value %p with legacy %p normalizes to %p', (value, legacy, expected) => {+ expect(normalizeMultiValue(value, legacy)).toEqual(expected)+ })+ })+})diff --git a/products/data_warehouse/frontend/shared/components/forms/GitHubRepositorySelector.tsx b/products/data_warehouse/frontend/shared/components/forms/GitHubRepositorySelector.tsxdeleted file mode 100644index f1f5a6ecf507..000000000000--- a/products/data_warehouse/frontend/shared/components/forms/GitHubRepositorySelector.tsx+++ /dev/null@@ -1,66 +0,0 @@-import { useActions, useValues } from 'kea'-import { useEffect } from 'react'--import { LemonInput } from '@posthog/lemon-ui'--import { githubIntegrationLogic } from 'lib/integrations/githubIntegrationLogic'-import { LemonField } from 'lib/lemon-ui/LemonField'-import { LemonSearchableSelect } from 'lib/lemon-ui/LemonSelect/LemonSearchableSelect'--import { sourceWizardLogic } from '../../../scenes/NewSourceScene/sourceWizardLogic'--export function GitHubRepositorySelector(): JSX.Element {- const { sourceConnectionDetails } = useValues(sourceWizardLogic)-- const authMethod = sourceConnectionDetails.payload?.auth_method- const isOAuth = authMethod?.selection === 'oauth'- const integrationId: number | undefined = authMethod?.github_integration_id-- if (isOAuth && integrationId) {- return <GitHubRepositoryDropdown integrationId={integrationId} />- }-- return (- <LemonField name="repository" label="Repository">- {({ value, onChange }) => (- <LemonInput- className="ph-ignore-input"- data-attr="repository"- placeholder="owner/repo"- type="text"- value={value || ''}- onChange={onChange}- disabledReason={isOAuth ? 'Connect your GitHub integration to select from repositories' : undefined}- />- )}- </LemonField>- )-}--function GitHubRepositoryDropdown({ integrationId }: { integrationId: number }): JSX.Element {- const { repositories, repositoriesLoading } = useValues(githubIntegrationLogic({ id: integrationId }))- const { loadRepositories } = useActions(githubIntegrationLogic({ id: integrationId }))-- useEffect(() => {- loadRepositories()- }, [loadRepositories])-- return (- <LemonField name="repository" label="Repository">- {({ value, onChange }) => (- <LemonSearchableSelect- data-attr="repository"- placeholder="Select a repository"- searchPlaceholder="Search repositories..."- value={value || null}- onChange={(newValue) => onChange(newValue ?? '')}- loading={repositoriesLoading}- options={repositories.map((repo) => ({- value: repo.full_name,- label: repo.full_name,- }))}- />- )}- </LemonField>- )-}diff --git a/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsx b/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsxindex 2bbe3cd3bb97..288b961660b7 100644--- a/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsx@@ -2,11 +2,12 @@ import { useActions, useValues } from 'kea'import { FormContext } from 'kea-forms'import { useContext, useEffect, useMemo } from 'react'-import { LemonInput, LemonTag } from '@posthog/lemon-ui'+import { LemonInput, LemonInputSelect, LemonTag } from '@posthog/lemon-ui'import { integrationAccountsLogic } from 'lib/integrations/integrationAccountsLogic'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { LemonField } from 'lib/lemon-ui/LemonField'+import type { LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { InputSuggestion, InputWithSuggestionsDropdown } from './InputWithSuggestionsDropdown'@@ -23,6 +24,26 @@ export interface IntegrationAccountSelectorProps {placeholder?: string/** Optional format guidance rendered under the field label. */caption?: string+ /** Multi-select mode: the field's payload value is a string[] and renders as chips. */+ multiple?: boolean+ /** Legacy single-value payload field that seeds the multi picker when it's still empty+ * (e.g. GitHub sources saved before multi-repo support store `repository`). */+ legacySingleField?: string+}++/** Coerce a form value into the multi picker's string[] shape: undefined/'' -> [],+ * a lone string -> [string], arrays get trimmed and deduped. */+export function normalizeMultiValue(value: unknown, legacySingle?: unknown): string[] {+ const raw = value === undefined || value === null || value === '' ? [] : Array.isArray(value) ? value : [value]+ const source = raw.length > 0 ? raw : legacySingle ? [legacySingle] : []+ const normalized: string[] = []+ for (const entry of source) {+ const trimmed = String(entry).trim()+ if (trimmed && !normalized.includes(trimmed)) {+ normalized.push(trimmed)+ }+ }+ return normalized}/** Generic account/resource picker for OAuth ad sources: a dropdown of the connected integration's@@ -31,7 +52,7 @@ export function IntegrationAccountSelector(props: IntegrationAccountSelectorProp// Only mount the hook-using inner component once inside a kea <Form>, to avoid a null logic.const formContext = useContext(FormContext)if (!formContext.logic) {- return <AccountTextField {...props} />+ return props.multiple ? <MultiAccountField {...props} /> : <AccountTextField {...props} />}return <IntegrationAccountSelectorInner {...props} formLogic={formContext.logic} formKey={formContext.formKey} />}@@ -42,8 +63,25 @@ function IntegrationAccountSelectorInner({...props}: IntegrationAccountSelectorProps & { formLogic: any; formKey: string }): JSX.Element {const integrationId = useFormIntegrationId(formLogic, formKey, props.integrationField)+ const legacySingleValue = useFormFieldValue(formLogic, formKey, props.legacySingleField)+ const ownValue = useFormFieldValue(formLogic, formKey, props.fieldName)const { integrations, integrationsLoading } = useValues(integrationsLogic)+ // Seed the multi field's form state from the legacy single-value field (e.g. a pre-multi-repo+ // GitHub source's `repository`) so an untouched edit still validates and saves the full list.+ const { fieldName, multiple } = props+ useEffect(() => {+ if (!multiple || normalizeMultiValue(ownValue).length > 0) {+ return+ }+ const seeded = normalizeMultiValue(undefined, legacySingleValue)+ if (seeded.length === 0) {+ return+ }+ const setValueAction = formLogic.actions[`set${formKey.charAt(0).toUpperCase()}${formKey.slice(1)}Value`]+ setValueAction?.(['payload', fieldName], seeded)+ }, [multiple, ownValue, legacySingleValue, formLogic, formKey, fieldName])+const integrationIsValid = useMemo(() => {if (!integrationId || integrationsLoading || !integrations) {return false@@ -53,6 +91,16 @@ function IntegrationAccountSelectorInner({)}, [integrationId, integrations, integrationsLoading, props.integrationKind])+ if (props.multiple) {+ return (+ <MultiAccountField+ {...props}+ integrationId={integrationIsValid && integrationId ? integrationId : undefined}+ legacySingleValue={legacySingleValue}+ />+ )+ }+if (integrationIsValid && integrationId) {return <IntegrationAccountFieldWithDropdown {...props} integrationId={integrationId} />}@@ -107,6 +155,14 @@ function findFieldValue(obj: unknown, key: string): unknown {return undefined}+function useFormFieldValue(formLogic: any, formKey: string, fieldName: string | undefined): unknown {+ const values = useValues(formLogic) as Record<string, any> | null+ if (!values || !fieldName) {+ return undefined+ }+ return findFieldValue(values[formKey]?.payload, fieldName)+}+function useFormIntegrationId(formLogic: any, formKey: string, integrationField: string): number | undefined {const values = useValues(formLogic) as Record<string, any> | nullif (!values) {@@ -118,6 +174,164 @@ function useFormIntegrationId(formLogic: any, formKey: string, integrationField:return id !== undefined && Number.isFinite(id) ? id : undefined}+const OWNER_REPO_PATTERN = /^[^/\s]+\/[^/\s]+$/++function accountOptionLabel(displayName: string, value: string, isPrimary: boolean, badges: string[]): JSX.Element {+ // When display_name === value (e.g. GSC site url), "value (value)" is redundant.+ const labelText = displayName === value ? displayName : `${displayName} (${value})`+ return (+ <div className="flex items-center gap-2">+ <span>{labelText}</span>+ {isPrimary && <LemonTag type="primary">Primary</LemonTag>}+ {badges.map((badge) => (+ <LemonTag type="muted" key={badge}>+ {badge}+ </LemonTag>+ ))}+ </div>+ )+}++/** Multi-select variant: chips of selected values, with the connected integration's accounts as+ * async-searched options (or free entry only, e.g. on the PAT path where there's no integration). */+function MultiAccountField({+ integrationId,+ sourceType,+ fieldName,+ fieldLabel,+ placeholder,+ caption,+ legacySingleValue,+}: IntegrationAccountSelectorProps & { integrationId?: number; legacySingleValue?: unknown }): JSX.Element {+ if (integrationId) {+ return (+ <MultiAccountFieldWithOptions+ integrationId={integrationId}+ sourceType={sourceType}+ fieldName={fieldName}+ fieldLabel={fieldLabel}+ placeholder={placeholder}+ caption={caption}+ legacySingleValue={legacySingleValue}+ />+ )+ }+ return (+ <MultiAccountFieldInner+ fieldName={fieldName}+ fieldLabel={fieldLabel}+ placeholder={placeholder}+ caption={caption}+ legacySingleValue={legacySingleValue}+ options={[]}+ />+ )+}++function MultiAccountFieldWithOptions({+ integrationId,+ sourceType,+ fieldName,+ fieldLabel,+ placeholder,+ caption,+ legacySingleValue,+}: {+ integrationId: number+ sourceType: string+ fieldName: string+ fieldLabel: string+ placeholder?: string+ caption?: string+ legacySingleValue?: unknown+}): JSX.Element {+ const { accounts, accountsLoading, accountsError } = useValues(+ integrationAccountsLogic({ id: integrationId, sourceType })+ )+ const { loadAccounts, setSearch } = useActions(integrationAccountsLogic({ id: integrationId, sourceType }))++ useEffect(() => {+ loadAccounts()+ }, [loadAccounts])++ const options = useMemo<LemonInputSelectOption[]>(() => {+ const sorted = [...accounts].sort((a, b) => Number(b.is_primary) - Number(a.is_primary))+ return sorted.map((account) => ({+ key: account.value,+ label:+ account.display_name === account.value ? account.value : `${account.display_name} (${account.value})`,+ labelComponent: accountOptionLabel(account.display_name, account.value, account.is_primary, account.badges),+ }))+ }, [accounts])++ return (+ <MultiAccountFieldInner+ fieldName={fieldName}+ fieldLabel={fieldLabel}+ placeholder={placeholder}+ caption={caption}+ legacySingleValue={legacySingleValue}+ options={options}+ loading={accountsLoading}+ onInputChange={setSearch}+ error={accountsError ?? undefined}+ />+ )+}++function MultiAccountFieldInner({+ fieldName,+ fieldLabel,+ placeholder,+ caption,+ legacySingleValue,+ options,+ loading,+ onInputChange,+ error,+}: {+ fieldName: string+ fieldLabel: string+ placeholder?: string+ caption?: string+ legacySingleValue?: unknown+ options: LemonInputSelectOption[]+ loading?: boolean+ onInputChange?: (value: string) => void+ error?: string+}): JSX.Element {+ return (+ <LemonField name={fieldName} label={fieldLabel} help={captionHelp(caption)}>+ {({ value, onChange }) => {+ const selected = normalizeMultiValue(value, legacySingleValue)+ const malformed = selected.filter((entry) => !OWNER_REPO_PATTERN.test(entry))+ return (+ <div className="flex flex-col gap-2">+ <LemonInputSelect+ data-attr={fieldName}+ mode="multiple"+ allowCustomValues+ placeholder={placeholder}+ value={selected}+ onChange={(newValues) => onChange(normalizeMultiValue(newValues))}+ options={options}+ loading={loading}+ onInputChange={onInputChange}+ />+ {error && <p className="m-0 text-xs text-warning">{error}</p>}+ {malformed.length > 0 && (+ <p className="m-0 text-xs text-warning">+ These entries don't look like <code>owner/repo</code>:{' '}+ {malformed.map((entry) => `"${entry}"`).join(', ')}. Double-check them before saving.+ </p>+ )}+ </div>+ )+ }}+ </LemonField>+ )+}+function IntegrationAccountFieldWithDropdown({integrationId,sourceType,@@ -138,28 +352,13 @@ function IntegrationAccountFieldWithDropdown({const suggestions = useMemo<InputSuggestion[]>(() => {const sorted = [...accounts].sort((a, b) => Number(b.is_primary) - Number(a.is_primary))return sorted.map((account) => {- // When display_name === value (e.g. GSC site url), "value (value)" is redundant.- const labelText =- account.display_name === account.value- ? account.display_name- : `${account.display_name} (${account.value})`const searchText =account.display_name === account.value? `${account.value} ${account.secondary_text ?? ''}`: `${account.display_name} ${account.value} ${account.secondary_text ?? ''}`return {value: account.value,- label: (- <div className="flex items-center gap-2">- <span>{labelText}</span>- {account.is_primary && <LemonTag type="primary">Primary</LemonTag>}- {account.badges.map((badge) => (- <LemonTag type="muted" key={badge}>- {badge}- </LemonTag>- ))}- </div>- ),+ label: accountOptionLabel(account.display_name, account.value, account.is_primary, account.badges),searchText,}})diff --git a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsxindex 84b87ca18dcb..ecee8ebcf0aa 100644--- a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx@@ -116,6 +116,11 @@ export const sourceFieldToElement = (setSourceConnectionDetailsValue?: (key: FieldName, value: any) => void,oauthRedirectUrl?: string): JSX.Element => {+ // Hidden fields stay in the config tree (their stored values parse and prefill) but never render.+ if ('hidden' in field && field.hidden) {+ return <React.Fragment key={field.name} />+ }+// It doesn't make sense for this to show on an update to an existing connection since we likely just want to change// a field or two. There is also some divergence in creates vs. updates that make this a bit more complex to handle.if (field.type === 'text' && field.name === 'connection_string') {@@ -283,6 +288,14 @@ export const sourceFieldToElement = (// contract: once the OAuth integration is picked, the text input becomes a dropdown of the// accounts the integration can access (one component, one logic, one endpoint shape for all).if (field.type === 'oauth-account-select') {+ // A hidden sibling of the same type is a legacy single-value field this multi field+ // superseded (e.g. GitHub `repository` -> `repositories`); its saved value seeds the+ // picker when the multi field is still empty.+ const legacySingleField = field.multiple+ ? sourceConfig.fields.find(+ (sibling) => sibling.type === 'oauth-account-select' && sibling.hidden && sibling.name !== field.name+ )?.name+ : undefinedreturn (<IntegrationAccountSelectorkey={field.name}@@ -293,6 +306,8 @@ export const sourceFieldToElement = (sourceType={sourceConfig.name}placeholder={field.placeholder}caption={field.caption}+ multiple={field.multiple}+ legacySingleField={legacySingleField}/>)}diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.pyindex 212feb81c07d..08948db52d52 100644--- a/products/warehouse_sources/backend/facade/source_management.py+++ b/products/warehouse_sources/backend/facade/source_management.py@@ -53,6 +53,8 @@ _LAZY = {"CustomSource": "sources.custom.source","manifest_request_hosts": "sources.custom.source","CustomSourceConfig": "sources.generated_configs",+ "GithubSource": "sources.github.source",+ "GithubSourceConfig": "sources.generated_configs","MySQLSourceConfig": "sources.generated_configs","PostgresSourceConfig": "sources.generated_configs","SnowflakeSourceConfig": "sources.generated_configs",diff --git a/products/warehouse_sources/backend/management/commands/generate_source_configs.py b/products/warehouse_sources/backend/management/commands/generate_source_configs.pyindex 1a0c3a611162..1cef7363f511 100644--- a/products/warehouse_sources/backend/management/commands/generate_source_configs.py+++ b/products/warehouse_sources/backend/management/commands/generate_source_configs.py@@ -292,8 +292,19 @@ class SourceConfigGenerator:def _process_oauth_account_select_field(self, field: SourceFieldOauthAccountSelectConfig) -> str:# The selected account/property is persisted as a plain string on the config (e.g. Bing Ads# account_id, GSC site_url); the OAuth integration it's scoped to lives in its own field.+ # With `multiple=True` the selection is a list of strings instead (e.g. GitHub repositories).python_field_name, should_alias = self._make_python_identifier(field.name)+ if field.multiple:+ # Always optional on the dataclass, even when the form field is required: configs+ # stored before the field existed (e.g. single-repo GitHub sources) must keep parsing.+ # "At least one value" is the source's job (validate_credentials / effective_* helpers).+ field_parts = ["converter=config.str_to_optional_list"]+ if should_alias:+ field_parts.append(f'alias="{field.name}"')+ field_parts.append("default_factory=lambda: None")+ return f" {python_field_name}: list[str] | None = config.value({', '.join(field_parts)})"+if field.required:if should_alias:return f' {python_field_name}: str = config.value(alias="{field.name}")'diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 594a0171552d..28550e93c3b1 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -842,6 +842,8 @@ def sync_old_schemas_with_new_schemas(source_id: str,team_id: int,descriptions: dict[str, str | None] | None = None,+ strict_name_match: bool = False,+ schema_metadata_by_name: dict[str, dict] | None = None,) -> tuple[list[str], list[str]]:old_schemas = get_all_schemas_for_source_id(source_id=source_id, team_id=team_id)old_schemas_names = [schema.name for schema in old_schemas]@@ -861,7 +863,12 @@ def sync_old_schemas_with_new_schemas(# Discovery names a table qualified (`schema.table`) or bare (`table`) depending on config, so# bare and qualified mean the same table — else a live row is wrongly disabled/duplicated. Two# qualified names still need exact equality so same-named tables in different schemas stay distinct.+ # `strict_name_match` disables the bare↔qualified equivalence for sources where bare and+ # qualified rows coexist by design (GitHub keeps its legacy repo's rows bare forever, so+ # `owner/other.issues` must NOT match the legacy bare `issues` row).def _same_table(a: str, b: str) -> bool:+ if strict_name_match:+ return a == bone_qualified = ("." in a) != ("." in b)return a == b or (one_qualified and a.rpartition(".")[2] == b.rpartition(".")[2])@@ -879,6 +886,7 @@ def sync_old_schemas_with_new_schemas(actually_created: list[str] = []for schema in schemas_to_create:+ seeded_metadata = (schema_metadata_by_name or {}).get(schema)deleted_obj = (ExternalDataSchema.objects.filter(team_id=team_id, source_id=source_id, name=schema, deleted=True).order_by("-updated_at", "-created_at")@@ -889,7 +897,14 @@ def sync_old_schemas_with_new_schemas(deleted_obj.deleted_at = Nonedeleted_obj.description = descriptions.get(schema) if descriptions else Nonedeleted_obj.label = new_schemas.get(schema)- deleted_obj.save(update_fields=["deleted", "deleted_at", "description", "label", "updated_at"])+ update_fields = ["deleted", "deleted_at", "description", "label", "updated_at"]+ if seeded_metadata:+ existing_config = deleted_obj.sync_type_config or {}+ existing_metadata = existing_config.get("schema_metadata")+ merged = {**(existing_metadata if isinstance(existing_metadata, dict) else {}), **seeded_metadata}+ deleted_obj.sync_type_config = {**existing_config, "schema_metadata": merged}+ update_fields.append("sync_type_config")+ deleted_obj.save(update_fields=update_fields)actually_created.append(schema)continue@@ -902,6 +917,7 @@ def sync_old_schemas_with_new_schemas("should_sync": False,"description": descriptions.get(schema) if descriptions else None,"label": new_schemas.get(schema),+ **({"sync_type_config": {"schema_metadata": seeded_metadata}} if seeded_metadata else {}),},)if created:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/helpers.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/helpers.pyindex 79807f61e667..e17c04ff16d7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/helpers.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/helpers.py@@ -68,7 +68,9 @@ def build_table_name(source: ExternalDataSource, schema_name: str):# Dots in `schema_name` would parse as `<table>.<column>` in HogQL, so any source that ever# produces a dotted schema name (today: Postgres multi-schema like `public.auth_group`) needs# them rewritten. No-op for pre-existing single-schema sources whose names never contained dots.- safe_schema_name = schema_name.replace(".", "__")+ # Slashes appear in GitHub's repo-qualified names (`owner/repo.issues`) and aren't a valid+ # identifier character at all, so they flatten to a single underscore.+ safe_schema_name = schema_name.replace("/", "_").replace(".", "__")return f"{source.prefix or ''}{source.source_type}_{safe_schema_name}".lower()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.pyindex 40e1c0065f9f..38c308bae1c9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py@@ -61,6 +61,24 @@ class TestResolveTableAndFolderNames:table_storage_name, _ = resolve_table_and_folder_names("BalanceTransaction", "balance_transaction")assert build_table_name(source, table_storage_name) == "stripe_balancetransaction"+ @parameterized.expand(+ [+ # Repo-qualified GitHub rows: the slash must flatten (it's not a valid identifier+ # char anywhere downstream) while the dot dunders like SQL multi-schema — yielding+ # HogQL `github.posthog_posthog__issues`. A bare slash surviving here produces an+ # unqueryable table name.+ ("github_qualified", "GitHub", "posthog/posthog.issues", "github_posthog_posthog__issues"),+ ("github_legacy_bare", "GitHub", "issues", "github_issues"),+ ("github_dotted_repo", "GitHub", "posthog/next.js.issues", "github_posthog_next__js__issues"),+ ]+ )+ def test_build_table_name_flattens_repo_qualifiers(+ self, _name: str, source_type: str, schema_name: str, expected: str+ ) -> None:+ source = ExternalDataSource(source_type=source_type, prefix="")+ table_storage_name, _ = resolve_table_and_folder_names(schema_name, None)+ assert build_table_name(source, table_storage_name) == expected+def _register_companion_sync(run_id: str,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.pyindex 293c067c943a..c581c021c020 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@@ -418,6 +418,21 @@ class WebhookSource(_BaseSource[ConfigType], Generic[ConfigType]):table name mapped to the Stripe object type"""raise NotImplementedError()+ def webhook_mapping_key(self, schema_name: str) -> str:+ """The `schema_mapping` key incoming webhooks are routed by for one schema row.++ Defaults to the `webhook_resource_map` translation (schema name -> provider event type).+ Sources whose schema names carry a namespace (e.g. GitHub's `owner/repo.workflow_runs`)+ override this to emit namespace-qualified keys, so two namespaces' rows for the same+ event type don't collide in the mapping."""+ return self.webhook_resource_map.get(schema_name, schema_name)++ def webhook_template_inputs(self, config: ConfigType) -> dict[str, Any]:+ """Extra static `inputs` to persist on the webhook HogFunction beyond `schema_mapping` and+ `source_id`. None by default; GitHub uses it to pin the legacy repository so the template's+ bare-event-key fallback can't route a secondary repo's events into the legacy repo's schema."""+ return {}+def get_external_webhook_info(self, config: ConfigType, webhook_url: str, team_id: int) -> ExternalWebhookInfo | None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.pyindex 7bf5a3f55a30..864804bfd898 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py@@ -689,6 +689,32 @@ def str_to_optional_int(s: str | int | float | None) -> int | None:return int(s)+def str_to_optional_list(s: str | list[typing.Any] | None) -> list[str] | None:+ """A converter to return an optional list of strings from a list, a JSON-array string,+ or a comma-separated string. Empty inputs normalize to None."""+ if s is None:+ return None+ if isinstance(s, list):+ values = [str(item).strip() for item in s]+ else:+ stripped = s.strip()+ if stripped == "":+ return None+ if stripped.startswith("["):+ try:+ parsed = json.loads(stripped)+ except json.JSONDecodeError:+ parsed = None+ if isinstance(parsed, list):+ values = [str(item).strip() for item in parsed]+ else:+ values = [stripped]+ else:+ values = [item.strip() for item in stripped.split(",")]+ values = [value for value in values if value]+ return values or None++_DefaultType = typing.TypeVar("_DefaultType")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 46c48fd9487e..5f671dd88027 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@@ -1,4 +1,5 @@from dataclasses import dataclass, field+from typing import Anyfrom products.warehouse_sources.backend.types import IncrementalField@@ -50,6 +51,12 @@ class SourceSchema:# this so each incremental run re-reads a trailing window instead of freezing a day# at its first-imported value. Only consumed for schemas synced incrementally.default_incremental_lookback_seconds: int | None = None+ # Source-specific keys merged into the persisted `sync_type_config.schema_metadata` at+ # schema creation, for sources that namespace tables by something other than a SQL+ # schema (e.g. GitHub stores {"source_repository", "source_endpoint"} per repo table).+ # The SQL sources' location keys above (source_catalog/source_schema/source_table_name)+ # stay separate: their persistence is gated on column-selection/direct-query paths.+ schema_metadata: dict[str, Any] | None = Nonedef _select_incremental_field(incremental_fields: list[IncrementalField]) -> IncrementalField | None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_config.pyindex f724f55a725d..253b055dc357 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_config.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_config.py@@ -78,6 +78,28 @@ def test_str_to_optional_int(value, expected):assert config.str_to_optional_int(value) == expected+ "value,expected",+ [+ (None, None),+ ("", None),+ (" ", None),+ ([], None),+ (["a/b", " c/d ", ""], ["a/b", "c/d"]),+ # job_inputs are JSON so lists usually arrive natively, but double-encoded configs+ # (the same failure mode from_dict guards elsewhere) arrive as a JSON-array string.+ ('["a/b", "c/d"]', ["a/b", "c/d"]),+ ("a/b, c/d", ["a/b", "c/d"]),+ ("a/b", ["a/b"]),+ # A malformed bracket-prefixed string must fall back to a single value, not crash.+ ("[not-json", ["[not-json"]),+ ],+)+def test_str_to_optional_list(value, expected):+ """`str_to_optional_list` must accept lists, JSON-array strings, and comma-separated strings."""+ assert config.str_to_optional_list(value) == expected++@pytest.mark.parametrize("value,expected",[diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_config_generator.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_config_generator.pyindex 13217f298de3..469d2c9366fb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_config_generator.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_config_generator.py@@ -10,6 +10,7 @@ from posthog.schema import (SourceFieldFileUploadJsonFormatConfig,SourceFieldInputConfig,SourceFieldInputConfigType,+ SourceFieldOauthAccountSelectConfig,SourceFieldOauthConfig,SourceFieldSelectConfig,SourceFieldSelectConfigOption,@@ -290,6 +291,35 @@ class TestSourceConfigGenerator(ClickhouseTestMixin):in output)+ @pytest.mark.parametrize("required", [True, False])+ def test_source_config_oauth_account_select_multiple_emits_optional_list(self, required):+ # `multiple` fields must generate an optional list even when the form field is required:+ # configs stored before the field existed (legacy single-repo GitHub sources) must keep+ # parsing, so requiredness is enforced by the source, not the dataclass.+ config = SourceConfig(+ name=SchemaExternalDataSourceType.GITHUB,+ iconPath="",+ fields=cast(+ list[FieldType],+ [+ SourceFieldOauthAccountSelectConfig(+ name="repositories",+ label="Repositories",+ integrationField="github_integration_id",+ integrationKind="github",+ required=required,+ multiple=True,+ ),+ ],+ ),+ )++ output = self._run({ExternalDataSourceType.GITHUB: config})+ assert (+ "repositories: list[str] | None = config.value(converter=config.str_to_optional_list, default_factory=lambda: None)"+ in output+ )+def test_source_config_ssh_tunnel_non_python_identifier(self):config = SourceConfig(name=SchemaExternalDataSourceType.STRIPE,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 8eab3fc864a5..a5885e9d64e5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -1678,7 +1678,8 @@ class GitguardianSourceConfig(config.Config):@config.configclass GithubSourceConfig(config.Config):auth_method: GithubAuthMethodConfig- repository: str+ repositories: list[str] | None = config.value(converter=config.str_to_optional_list, default_factory=lambda: None)+ repository: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.pyindex 1b5db439f2ed..d7c8a9b8e3fb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py@@ -902,6 +902,7 @@ def github_source(incremental_field: str | None = None,webhook_source_manager: Optional[WebhookSourceManager] = None,egress_identity: GithubEgressIdentity | None = None,+ response_name: str | None = None,) -> SourceResponse:endpoint_config = GITHUB_ENDPOINTS[endpoint]@@ -987,7 +988,9 @@ def github_source()return SourceResponse(- name=endpoint,+ # The storage identity (Delta subdir / queryable folder). Repo-qualified schemas pass a+ # normalized `owner_repo_endpoint`; legacy bare schemas default to the endpoint, today's value.+ name=response_name or endpoint,items=items,primary_keys=_normalize_primary_key(endpoint_config.primary_key),sort_mode=actual_sort_mode,@@ -1054,6 +1057,77 @@ def create_repo_webhook()+def ensure_repo_webhook(+ token: str,+ repo: str,+ webhook_url: str,+ events: list[str],+ secret: str,+ egress_identity: GithubEgressIdentity | None = None,+) -> WebhookCreationResult:+ """Idempotently ensure a repo webhook pointing at ``webhook_url`` exists with ``secret``.++ A hook already matching the URL is PATCHed (secret re-pinned, events unioned) instead of+ re-created — a bare POST would 422 with "Hook already exists on this repository", which+ matters both for retried creates and for reconciling a multi-repo source where some repos+ already carry the hook. No match falls through to the plain create."""+ hooks, error = _list_repo_hooks(token, repo, egress_identity)+ if error == "permission":+ return WebhookCreationResult(+ success=False,+ error=(+ f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT} needed to create a repository webhook. "+ "Add it and reconnect, or set up the webhook manually following the steps below."+ ),+ )+ if error is not None:+ return WebhookCreationResult(success=False, error=f"Failed to create webhook automatically: {error}")++ hook = _match_hook_by_url(hooks or [], webhook_url)+ if hook is None:+ return create_repo_webhook(token, repo, webhook_url, events, secret=secret)++ merged_events = sorted(set(hook.get("events") or []) | set(events))+ try:+ response = github_request(+ "PATCH",+ f"{GITHUB_BASE_URL}/repos/{repo}/hooks/{hook['id']}",+ source="warehouse",+ headers=_get_headers(token),+ installation_id=egress_identity.installation_id if egress_identity is not None else None,+ priority=Priority.NORMAL,+ timeout=30,+ session=make_tracked_session(),+ json={+ "active": True,+ "events": merged_events,+ "config": {"url": webhook_url, "content_type": "json", "secret": secret},+ },+ )+ raise_if_github_rate_limited(response)+ except (GitHubEgressBudgetExhausted, GitHubRateLimitError):+ return WebhookCreationResult(+ success=False,+ error="GitHub rate limit reached while updating the repository webhook; please retry shortly.",+ )+ except requests.exceptions.RequestException as e:+ return WebhookCreationResult(success=False, error=f"Failed to update webhook automatically: {e}")++ if response.ok:+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})+ if _is_repo_hook_permission_error(response):+ return WebhookCreationResult(+ success=False,+ error=(+ f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT} needed to update the repository webhook. "+ "Add it and reconnect, or set up the webhook manually following the steps below."+ ),+ )+ return WebhookCreationResult(+ success=False, error=f"Failed to update webhook automatically: {response.status_code} {response.text}"+ )++def _list_repo_hooks(token: str, repo: str, egress_identity: GithubEgressIdentity | None = None) -> tuple[list[dict[str, Any]] | None, str | None]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/naming.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/naming.pynew file mode 100644index 000000000000..25defa238bec--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/naming.py@@ -0,0 +1,73 @@+"""Repo-qualified schema naming for the multi-repo GitHub source.++Multi-repo sources name their schema rows `owner/repo.endpoint` (e.g. `posthog/posthog.issues`),+mirroring the SQL sources' `schema.table` qualified naming. The persisted+`sync_type_config.schema_metadata` (`source_repository` / `source_endpoint`) is the authoritative+source of a row's location — repo names may themselves contain dots, so name parsing is only a+fallback and always matches against the known endpoint catalog rather than splitting blindly.+Legacy single-repo sources keep bare endpoint names (`issues`); those resolve to the config's+`repository` field.+"""++from typing import TYPE_CHECKING, Any++from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import ENDPOINTS++if TYPE_CHECKING:+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GithubSourceConfig++SCHEMA_METADATA_REPOSITORY_KEY = "source_repository"+SCHEMA_METADATA_ENDPOINT_KEY = "source_endpoint"++# Longest first so `pull_requests` wins over any shorter overlapping endpoint name.+_ENDPOINT_SUFFIXES = sorted(ENDPOINTS, key=lambda name: len(name), reverse=True)+++def qualified_schema_name(repository: str, endpoint: str) -> str:+ return f"{repository}.{endpoint}"+++def split_schema_name(schema_name: str) -> tuple[str | None, str]:+ """`(repository | None, endpoint)` for a schema row name.++ Matches the longest known endpoint suffix (`.endswith(".issues")` etc.) so repo names+ containing dots parse deterministically. Bare or unrecognized names return them unchanged+ with no repository.+ """+ for endpoint in _ENDPOINT_SUFFIXES:+ if schema_name.endswith(f".{endpoint}"):+ repository = schema_name[: -(len(endpoint) + 1)]+ if repository:+ return repository, endpoint+ return None, schema_name+++def resolve_schema_repo_endpoint(+ schema_metadata: dict[str, Any] | None,+ schema_name: str,+ config: "GithubSourceConfig",+) -> tuple[str, str]:+ """`(repository, endpoint)` for a schema row: metadata first, qualified-name parse second,+ the config's legacy `repository` for bare rows last."""+ metadata = schema_metadata if isinstance(schema_metadata, dict) else {}+ repository = metadata.get(SCHEMA_METADATA_REPOSITORY_KEY)+ endpoint = metadata.get(SCHEMA_METADATA_ENDPOINT_KEY)+ if isinstance(repository, str) and repository and isinstance(endpoint, str) and endpoint:+ return repository.strip().lower(), endpoint++ parsed_repository, parsed_endpoint = split_schema_name(schema_name)+ if parsed_repository is not None:+ return parsed_repository.strip().lower(), parsed_endpoint++ if not config.repository:+ # Phrase matches get_non_retryable_errors so an unresolvable row fails permanently+ # with the curated message instead of retrying forever.+ raise ValueError(f"No repositories configured for schema '{schema_name}'")+ return config.repository.strip().lower(), parsed_endpoint+++def schema_metadata_for(repository: str, endpoint: str) -> dict[str, str]:+ return {+ SCHEMA_METADATA_REPOSITORY_KEY: repository,+ SCHEMA_METADATA_ENDPOINT_KEY: endpoint,+ }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.pyindex c51842b88401..38581f310133 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@@ -1,5 +1,5 @@import secrets-from typing import TYPE_CHECKING, Optional, cast+from typing import TYPE_CHECKING, Any, Optional, castif TYPE_CHECKING:from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC@@ -19,6 +19,7 @@ from posthog.schema import (from posthog.models.integration import GitHubIntegration+from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConventionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (SourceInputs,SourceResponse,@@ -50,13 +51,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.github.gitGithubEgressIdentity,GithubResumeConfig,check_org_endpoint_permission,- create_repo_webhook,delete_repo_webhook,+ ensure_repo_webhook,get_repo_webhook_info,github_source,update_repo_webhook,validate_credentials as validate_github_credentials,)+from products.warehouse_sources.backend.temporal.data_imports.sources.github.naming import (+ qualified_schema_name,+ resolve_schema_repo_endpoint,+ schema_metadata_for,+ split_schema_name,+)from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import (ENDPOINTS,GITHUB_ENDPOINTS,@@ -153,19 +160,32 @@ class GithubSource(),],),+ SourceFieldOauthAccountSelectConfig(+ name="repositories",+ label="Repositories",+ integrationField="github_integration_id",+ integrationKind="github",+ placeholder="owner/repo",+ required=True,+ multiple=True,+ ),+ # Legacy single-repo field. Kept in the config tree so pre-multi-repo sources'+ # `job_inputs.repository` still parses (and survives read-side redaction), and+ # doubles as the marker for the repo whose schemas keep bare, unqualified names.SourceFieldOauthAccountSelectConfig(name="repository",label="Repository",integrationField="github_integration_id",integrationKind="github",placeholder="owner/repo",- required=True,+ required=False,+ hidden=True,),],),- webhookSetupCaption="""To set up the webhook manually:+ webhookSetupCaption="""To set up the webhook manually, repeat these steps for **each selected repository**, using the **same Secret** every time:-1. Go to your repository's **Settings > Webhooks** on GitHub+1. Go to the repository's **Settings > Webhooks** on GitHub2. Click **Add webhook**3. Paste the webhook URL shown below into the **Payload URL** field4. Set **Content type** to **application/json**@@ -221,6 +241,9 @@ If automatic creation failed, your token needs webhook permissions — the **adm# These never resolve on retry — the source needs reconfiguring or reconnecting."Missing GitHub integration ID": "No GitHub account is connected. Please reconnect your GitHub account.","Missing personal access token": "GitHub personal access token is not configured. Please update the source configuration.",+ "No repositories configured": "No repositories are selected for this source. Please update the source configuration.",+ "resolve to the same warehouse table": "Two selected repositories resolve to the same warehouse table. Please remove or rename one.",+ "Too many repositories configured": "Too many repositories are selected for this source. Please reduce the list and try again.","GitHub access token not found": "GitHub OAuth access token is missing. Please reconnect your GitHub account.","Integration not found": "The linked GitHub integration no longer exists. Please reconnect your GitHub account.","Missing integration ID": "Integration ID is not configured. Please reconnect your GitHub account.",@@ -250,6 +273,57 @@ If automatic creation failed, your token needs webhook permissions — the **admif repo.get("full_name")]+ # One schema row per repository × endpoint, and — when a webhook exists — one hook per+ # repository, both fan out linearly over this list. Bound it so a single oversized/malformed+ # config (the update path accepts a large JSON body) can't drive unbounded schema creation or+ # a serial stream of GitHub hook operations. Generous versus any real use.+ MAX_REPOSITORIES = 100++ @staticmethod+ def effective_repositories(config: GithubSourceConfig) -> list[str]:+ """The repos this source syncs. `repositories` wins when set; legacy sources fall back to+ the single `repository`. Deduped, stripped, lowercased (GitHub full names are+ case-insensitive and the repo half of schema names/webhook keys must compare stably).++ Rejects a config that would resolve two repositories to the same warehouse storage, or that+ exceeds `MAX_REPOSITORIES`, so a malformed/oversized list fails fast with a curated,+ non-retryable message rather than mixing repos' data or exhausting a worker."""+ raw = config.repositories if config.repositories else ([config.repository] if config.repository else [])+ seen: set[str] = set()+ # Storage identifier (table name + S3 folder) -> the repo that claimed it. Two repositories+ # that collapse to the same identifier — the classic case is `owner/repo.name` vs+ # `owner/repo__name`, which the separator flattening isn't injective over — would share one+ # table and folder, silently mixing their data. Reject rather than merge.+ storage_owners: dict[str, str] = {}+ repositories: list[str] = []+ for repo in raw:+ normalized = repo.strip().lower()+ if not normalized or normalized in seen:+ continue+ storage_key = NamingConvention.normalize_identifier(normalized)+ if storage_key in storage_owners:+ raise ValueError(+ f"Repositories '{storage_owners[storage_key]}' and '{normalized}' resolve to the "+ "same warehouse table; remove or rename one."+ )+ storage_owners[storage_key] = normalized+ seen.add(normalized)+ repositories.append(normalized)+ if not repositories:+ raise ValueError("No repositories configured")+ if len(repositories) > GithubSource.MAX_REPOSITORIES:+ raise ValueError(+ f"Too many repositories configured ({len(repositories)}); the maximum is "+ f"{GithubSource.MAX_REPOSITORIES}."+ )+ return repositories++ @staticmethod+ def is_legacy_bare_repo(config: GithubSourceConfig, repository: str) -> bool:+ """True when `repository` is the pre-multi-repo repo whose schemas keep bare, unqualified+ names (`issues`, not `owner/repo.issues`)."""+ return bool(config.repository) and repository == (config.repository or "").strip().lower()+def _get_access_token(self, config: GithubSourceConfig, team_id: int) -> str:if config.auth_method.selection == "pat":if not config.auth_method.personal_access_token:@@ -280,7 +354,7 @@ If automatic creation failed, your token needs webhook permissions — the **admreturn GithubEgressIdentity(installation_id=GitHubIntegration(integration).github_installation_id)@staticmethod- def _schema_for_endpoint(endpoint: str) -> SourceSchema:+ def _schema_for_endpoint(endpoint: str, repository: str | None = None) -> SourceSchema:webhook_capable = endpoint in GITHUB_WEBHOOK_RESOURCE_MAP# An endpoint whose poll does no first-sync backfill (initial_lookback_days == 0:# workflow_jobs, workflow_runs, reviews) can only ever be populated by the webhook —@@ -290,13 +364,15 @@ If automatic creation failed, your token needs webhook permissions — the **admwebhook_only = webhook_capable and GITHUB_ENDPOINTS[endpoint].initial_lookback_days == 0supports_poll = bool(INCREMENTAL_FIELDS.get(endpoint)) and not webhook_onlyreturn SourceSchema(- name=endpoint,+ name=endpoint if repository is None else qualified_schema_name(repository, endpoint),supports_incremental=supports_poll,supports_append=supports_poll,supports_webhooks=webhook_capable,webhook_only=webhook_only,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),should_sync_default=GITHUB_ENDPOINTS[endpoint].should_sync_default,+ label=None if repository is None else f"{repository} · {endpoint}",+ schema_metadata=None if repository is None else schema_metadata_for(repository, endpoint),)def get_schemas(@@ -307,7 +383,14 @@ If automatic creation failed, your token needs webhook permissions — the **admnames: list[str] | None = None,force_refresh: bool = False,) -> list[SourceSchema]:- schemas = [self._schema_for_endpoint(endpoint) for endpoint in list(ENDPOINTS)]+ # One row per repo × endpoint. The legacy single-repo repo (pre-multi-repo sources)+ # keeps bare endpoint names so its existing rows, tables, and saved queries never+ # change; every other repo gets `owner/repo.endpoint` qualified names.+ schemas = [+ self._schema_for_endpoint(endpoint, repository=None if self.is_legacy_bare_repo(config, repo) else repo)+ for repo in self.effective_repositories(config)+ for endpoint in list(ENDPOINTS)+ ]if names is not None:names_set = set(names)schemas = [s for s in schemas if s.name in names_set]@@ -317,11 +400,17 @@ If automatic creation failed, your token needs webhook permissions — the **admself, config: GithubSourceConfig, team_id: int, endpoints: list[str]) -> dict[str, str | None]:# Only the org-scoped tables (teams, team_members) can be denied by a missing org grant; the- # repo-scoped tables are already covered by validate_credentials at create. Probe the org- # endpoint once and report the same reason for whichever org tables were requested, so a- # repo-scoped connection sees exactly which tables need the extra grant and can deselect them.+ # repo-scoped tables are already covered by validate_credentials at create. Inputs may be+ # bare (`teams`) or repo-qualified (`owner/repo.teams`); probe the org endpoint once per+ # unique owner and fan the reason back per input name, so a repo-scoped connection sees+ # exactly which tables need the extra grant and can deselect them.result: dict[str, str | None] = dict.fromkeys(endpoints)- org_endpoints = [name for name in endpoints if name in ORG_SCOPED_ENDPOINTS]+ org_endpoints: dict[str, str] = {} # input name -> repository to probe through+ for name in endpoints:+ repository, endpoint = split_schema_name(name)+ if endpoint not in ORG_SCOPED_ENDPOINTS:+ continue+ org_endpoints[name] = (repository or config.repository or "").strip().lower()if not org_endpoints:return resulttry:@@ -345,17 +434,36 @@ If automatic creation failed, your token needs webhook permissions — the **admfor name in org_endpoints:result[name] = credential_reasonreturn result- reason = check_org_endpoint_permission(access_token, config.repository, egress_identity)- for name in org_endpoints:- result[name] = reason+ reason_by_owner: dict[str, str | None] = {}+ for name, repository in org_endpoints.items():+ owner = repository.split("/", 1)[0]+ if owner not in reason_by_owner:+ reason_by_owner[owner] = check_org_endpoint_permission(access_token, repository, egress_identity)+ result[name] = reason_by_owner[owner]return result+ # Bound so a source with hundreds of repos doesn't turn the wizard's validate round-trip+ # into hundreds of serial GitHub calls; repos beyond the cap fail at sync time instead.+ MAX_VALIDATED_REPOSITORIES = 20+def validate_credentials(self, config: GithubSourceConfig, team_id: int, schema_name: Optional[str] = None) -> tuple[bool, str | None]:try:access_token = self._get_access_token(config, team_id)- return validate_github_credentials(access_token, config.repository)+ repositories = self.effective_repositories(config)+ failures: list[str] = []+ for repository in repositories[: self.MAX_VALIDATED_REPOSITORIES]:+ is_valid, message = validate_github_credentials(access_token, repository)+ if is_valid:+ continue+ # A 401 is token-level — probing further repos yields the same answer.+ if message == "Invalid personal access token":+ return False, message+ failures.append(message or f"Repository '{repository}' not found or not accessible")+ if failures:+ return False, "; ".join(failures)+ return True, Noneexcept Exception as e:# `_get_access_token` and the OAuth mixin raise deterministic config/credential errors# (missing integration ID, missing token, integration deleted). The user-facing wording@@ -373,25 +481,102 @@ If automatic creation failed, your token needs webhook permissions — the **admdef get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:return WebhookSourceManager(inputs, inputs.logger)+ def webhook_mapping_key(self, schema_name: str) -> str:+ # Legacy bare rows keep the bare event key (`workflow_run`); repo-qualified rows get+ # `owner/repo.event` so two repos' rows for the same event don't collide. The hog template+ # looks up `lower(repository.full_name) + '.' + eventType` first, then the bare event.+ repository, endpoint = split_schema_name(schema_name)+ event = GITHUB_WEBHOOK_RESOURCE_MAP.get(endpoint, endpoint)+ if repository is None:+ return event+ return f"{repository.strip().lower()}.{event}"++ def webhook_template_inputs(self, config: GithubSourceConfig) -> dict[str, Any]:+ # Pin the legacy repository (the one whose rows keep bare event keys) so the template's+ # bare-key fallback only fires for its events. Empty when there's no legacy repo (pure+ # multi-repo sources have no bare keys, so nothing to bind).+ return {"legacy_repository": (config.repository or "").strip().lower()}+def get_desired_webhook_events(self, config: GithubSourceConfig, eligible_schema_names: list[str]) -> list[str] | None:- # Map the eligible schemas to GitHub event names (e.g. ["workflow_job", "workflow_run"]).- return [- GITHUB_WEBHOOK_RESOURCE_MAP[name] for name in eligible_schema_names if name in GITHUB_WEBHOOK_RESOURCE_MAP- ]+ # Map the eligible schemas — bare or repo-qualified — to GitHub event names+ # (e.g. ["workflow_job", "workflow_run"]), deduped since every repo shares one event set.+ events: list[str] = []+ for name in eligible_schema_names:+ _, endpoint = split_schema_name(name)+ event = GITHUB_WEBHOOK_RESOURCE_MAP.get(endpoint)+ if event is not None and event not in events:+ events.append(event)+ return events++ def _webhook_repositories(self, config: GithubSourceConfig) -> list[str]:+ return self.effective_repositories(config)++ def ensure_webhooks_for_repositories(+ self, config: GithubSourceConfig, webhook_url: str, team_id: int, repositories: list[str], secret: str+ ) -> list[str]:+ """Idempotently create/update hooks in the given repos, pinned to the source's existing+ signing secret. Used by the repo-list reconcile for newly added repos. Returns per-repo+ failure messages (empty on full success)."""+ access_token = self._get_access_token(config, team_id)+ egress_identity = self._egress_identity(config, team_id)+ events = self.get_desired_webhook_events(config, list(GITHUB_WEBHOOK_RESOURCE_MAP.keys())) or []+ failures: list[str] = []+ for repository in repositories:+ result = ensure_repo_webhook(+ access_token, repository, webhook_url, events, secret=secret, egress_identity=egress_identity+ )+ if not result.success:+ failures.append(f"{repository}: {result.error}")+ return failures++ def delete_webhooks_for_repositories(+ self, config: GithubSourceConfig, webhook_url: str, team_id: int, repositories: list[str]+ ) -> list[str]:+ """Delete this source's hook from the given repos (repo-list reconcile, removed repos).+ Returns per-repo failure messages (empty on full success)."""+ access_token = self._get_access_token(config, team_id)+ egress_identity = self._egress_identity(config, team_id)+ failures: list[str] = []+ for repository in repositories:+ result = delete_repo_webhook(access_token, repository, webhook_url, egress_identity=egress_identity)+ if not result.success:+ failures.append(f"{repository}: {result.error}")+ return failuresdef create_webhook(self, config: GithubSourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:access_token = self._get_access_token(config, team_id)+ egress_identity = self._egress_identity(config, team_id)# GitHub's webhook secret is creator-supplied, so we mint one, hand it to GitHub as the# hook's config.secret, and return it via extra_inputs so it lands on the hog function for# signature verification. (Contrast Stripe, which generates and returns its own secret.)+ # One secret is shared by every repo's hook — the source has a single hog function with a+ # single signing_secret input, and repos added later are pinned to the same secret.secret = secrets.token_hex(32)# Always subscribe to every webhook-capable event, not just the enabled schemas: jobs fan# out under runs so the workflow pair travels together, and an unmapped event no-ops in the# hog function anyway, so over-subscribing is harmless while enabling a table later is free.events = self.get_desired_webhook_events(config, list(GITHUB_WEBHOOK_RESOURCE_MAP.keys())) or []- return create_repo_webhook(access_token, config.repository, webhook_url, events, secret=secret)+ failures: list[str] = []+ any_success = False+ for repository in self._webhook_repositories(config):+ result = ensure_repo_webhook(+ access_token, repository, webhook_url, events, secret=secret, egress_identity=egress_identity+ )+ if result.success:+ any_success = True+ else:+ failures.append(f"{repository}: {result.error}")+ if not failures:+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})+ # Partial success still persists the secret: the repos that did get a hook must verify+ # against it, and the failed repos' manual setup instructions tell the user to reuse it.+ return WebhookCreationResult(+ success=False,+ error="Failed to create the webhook in some repositories — " + "; ".join(failures),+ extra_inputs={"signing_secret": secret} if any_success else {},+ )def sync_webhook_events(self,@@ -401,32 +586,76 @@ If automatic creation failed, your token needs webhook permissions — the **admeligible_schema_names: list[str],) -> WebhookSyncResult:access_token = self._get_access_token(config, team_id)+ egress_identity = self._egress_identity(config, team_id)# Every mapped event, not just the enabled schemas': mirrors create_webhook's stance# (over-subscribing is harmless, unmapped events no-op in the hog function) and auto-heals# webhooks created before GITHUB_WEBHOOK_RESOURCE_MAP gained new events. Thread the# installation identity so the hook list and PATCH draw from the same shared egress# budget as the data plane; PAT sources resolve to an empty identity (record-only).desired_events = self.get_desired_webhook_events(config, list(GITHUB_WEBHOOK_RESOURCE_MAP.keys())) or []- return update_repo_webhook(- access_token,- config.repository,- webhook_url,- desired_events,- egress_identity=self._egress_identity(config, team_id),- )+ failures: list[str] = []+ for repository in self._webhook_repositories(config):+ result = update_repo_webhook(+ access_token, repository, webhook_url, desired_events, egress_identity=egress_identity+ )+ if not result.success:+ failures.append(f"{repository}: {result.error}")+ if not failures:+ return WebhookSyncResult(success=True)+ return WebhookSyncResult(success=False, error="; ".join(failures))def delete_webhook(self, config: GithubSourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:access_token = self._get_access_token(config, team_id)- return delete_repo_webhook(- access_token, config.repository, webhook_url, egress_identity=self._egress_identity(config, team_id)- )+ egress_identity = self._egress_identity(config, team_id)+ failures: list[str] = []+ for repository in self._webhook_repositories(config):+ result = delete_repo_webhook(access_token, repository, webhook_url, egress_identity=egress_identity)+ if not result.success:+ failures.append(f"{repository}: {result.error}")+ if not failures:+ return WebhookDeletionResult(success=True)+ return WebhookDeletionResult(success=False, error="; ".join(failures))def get_external_webhook_info(self, config: GithubSourceConfig, webhook_url: str, team_id: int) -> ExternalWebhookInfo:access_token = self._get_access_token(config, team_id)- return get_repo_webhook_info(- access_token, config.repository, webhook_url, egress_identity=self._egress_identity(config, team_id)+ egress_identity = self._egress_identity(config, team_id)+ # exists=True only when every repo carries the hook; partial coverage surfaces the+ # missing repos so the UI can prompt a re-create (which is idempotent per repo).+ missing: list[str] = []+ errors: list[str] = []+ merged_events: set[str] = set()+ first_info: ExternalWebhookInfo | None = None+ for repository in self._webhook_repositories(config):+ info = get_repo_webhook_info(access_token, repository, webhook_url, egress_identity=egress_identity)+ if info.error:+ errors.append(f"{repository}: {info.error}")+ elif not info.exists:+ missing.append(repository)+ else:+ merged_events.update(info.enabled_events or [])+ if first_info is None:+ first_info = info+ if errors:+ return ExternalWebhookInfo(exists=False, error="; ".join(errors))+ if missing:+ if first_info is None:+ return ExternalWebhookInfo(exists=False)+ return ExternalWebhookInfo(+ exists=False,+ url=webhook_url,+ enabled_events=sorted(merged_events),+ error="Webhook missing in repositories: " + ", ".join(missing),+ )+ if first_info is None:+ return ExternalWebhookInfo(exists=False)+ return ExternalWebhookInfo(+ exists=True,+ url=webhook_url,+ enabled_events=sorted(merged_events),+ status=first_info.status,+ created_at=first_info.created_at,)def source_for_pipeline(@@ -437,16 +666,25 @@ If automatic creation failed, your token needs webhook permissions — the **adm) -> SourceResponse:access_token = self._get_access_token(config, inputs.team_id)egress_identity = self._egress_identity(config, inputs.team_id)+ repository, endpoint = resolve_schema_repo_endpoint(inputs.schema_metadata, inputs.schema_name, config)# Only the workflow schemas can be webhook-fed, so skip building the manager — and its# webhook_enabled() DB lookup — for the poll-only endpoints (issues, commits, etc.).webhook_source_manager = (- self.get_webhook_source_manager(inputs) if inputs.schema_name in GITHUB_WEBHOOK_RESOURCE_MAP else None+ self.get_webhook_source_manager(inputs) if endpoint in GITHUB_WEBHOOK_RESOURCE_MAP else None+ )++ # Storage identity mirrors the SQL sources' resolve_source_location: prefer the row's+ # pinned s3_folder_name so a rename never orphans Delta data; normalize the (possibly+ # repo-qualified) schema name otherwise. Legacy bare rows normalize to today's value.+ storage_key = (+ inputs.s3_folder_name if isinstance(inputs.s3_folder_name, str) and inputs.s3_folder_name else None)+ response_name = NamingConvention.normalize_identifier(storage_key or inputs.schema_name)return github_source(personal_access_token=access_token,- repository=config.repository,- endpoint=inputs.schema_name,+ repository=repository,+ endpoint=endpoint,logger=inputs.logger,resumable_source_manager=resumable_source_manager,should_use_incremental_field=inputs.should_use_incremental_field,@@ -456,4 +694,5 @@ If automatic creation failed, your token needs webhook permissions — the **admincremental_field=inputs.incremental_field,webhook_source_manager=webhook_source_manager,egress_identity=egress_identity,+ response_name=response_name,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.pyindex 7e6341421beb..77ef1d174795 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py@@ -8,6 +8,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_GithubAuthMethodConfig,GithubSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.github.naming import (+ resolve_schema_repo_endpoint,+ split_schema_name,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.github.source import GithubSourcefrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -16,6 +21,14 @@ _GITHUB_INTEGRATION_PATH = ()+def _pat_config(repository: str | None = None, repositories: list[str] | None = None) -> GithubSourceConfig:+ return GithubSourceConfig(+ auth_method=GithubAuthMethodConfig(github_integration_id=None, selection="pat", personal_access_token="t"),+ repository=repository,+ repositories=repositories,+ )++class TestGithubSource:def setup_method(self):self.source = GithubSource()@@ -252,3 +265,208 @@ class TestGithubSource:# The wizard surfaces this string directly, so it must be the friendly copy, not the# internal "Missing ..." developer string raised by `_get_access_token`.assert message == expected_message++ @pytest.mark.parametrize(+ "repository,repositories,expected",+ [+ # Legacy single-repo sources fall back to `repository` — breaking this breaks+ # sync routing for every pre-multi-repo source.+ ("PostHog/posthog", None, ["posthog/posthog"]),+ (None, ["PostHog/posthog", "posthog/posthog", " Other/Repo "], ["posthog/posthog", "other/repo"]),+ # A non-empty `repositories` is the authoritative set; `repository` only marks bare naming.+ ("posthog/posthog", ["a/b"], ["a/b"]),+ ],+ )+ def test_effective_repositories(self, repository, repositories, expected):+ assert GithubSource.effective_repositories(_pat_config(repository, repositories)) == expected++ def test_effective_repositories_raises_without_any_repo(self):+ with pytest.raises(ValueError, match="No repositories configured"):+ GithubSource.effective_repositories(_pat_config(None, None))+ assert "No repositories configured" in self.source.get_non_retryable_errors()++ def test_effective_repositories_rejects_storage_collision(self):+ # `acme/repo.name` and `acme/repo__name` collapse to the same table/folder identifier; the+ # source must reject the pair rather than silently mix two repos' data into one table.+ with pytest.raises(ValueError, match="resolve to the same warehouse table"):+ GithubSource.effective_repositories(_pat_config(None, ["acme/repo.name", "acme/repo__name"]))+ assert "resolve to the same warehouse table" in self.source.get_non_retryable_errors()++ def test_effective_repositories_rejects_over_the_maximum(self):+ too_many = [f"acme/repo{i}" for i in range(GithubSource.MAX_REPOSITORIES + 1)]+ with pytest.raises(ValueError, match="Too many repositories configured"):+ GithubSource.effective_repositories(_pat_config(None, too_many))+ assert "Too many repositories configured" in self.source.get_non_retryable_errors()++ @pytest.mark.parametrize(+ "name,expected",+ [+ ("issues", (None, "issues")),+ ("posthog/posthog.issues", ("posthog/posthog", "issues")),+ # Repo names can contain dots — a naive rpartition('.') would split `next.js` wrong.+ ("posthog/next.js.issues", ("posthog/next.js", "issues")),+ ("posthog/next.js.pull_requests", ("posthog/next.js", "pull_requests")),+ # Unrecognized suffixes stay whole so unknown rows don't get misrouted.+ ("posthog/posthog.not_an_endpoint", (None, "posthog/posthog.not_an_endpoint")),+ ],+ )+ def test_split_schema_name(self, name, expected):+ assert split_schema_name(name) == expected++ def test_resolve_schema_repo_endpoint_metadata_wins_over_name(self):+ # A repo rename edge or hand-edited row name must never override the persisted location.+ config = _pat_config(repository="legacy/repo")+ assert resolve_schema_repo_endpoint(+ {"source_repository": "Real/Repo", "source_endpoint": "issues"},+ "misleading/name.pull_requests",+ config,+ ) == ("real/repo", "issues")+ assert resolve_schema_repo_endpoint(None, "other/repo.issues", config) == ("other/repo", "issues")+ assert resolve_schema_repo_endpoint(None, "issues", config) == ("legacy/repo", "issues")++ def test_resolve_schema_repo_endpoint_bare_without_config_repo_raises_non_retryable(self):+ with pytest.raises(ValueError, match="No repositories configured"):+ resolve_schema_repo_endpoint(None, "issues", _pat_config(None, ["a/b"]))++ def test_get_schemas_legacy_single_repo_stays_bare(self):+ # Pre-multi-repo sources must keep their exact schema names or existing rows,+ # tables, and saved queries all detach.+ schemas = self.source.get_schemas(_pat_config(repository="acme/widgets"), self.team_id)+ assert [s.name for s in schemas] == list(ENDPOINTS)+ assert all(s.schema_metadata is None for s in schemas)++ def test_get_schemas_legacy_source_with_added_repo_mixes_bare_and_qualified(self):+ config = _pat_config(repository="acme/widgets", repositories=["acme/widgets", "acme/other"])+ schemas = self.source.get_schemas(config, self.team_id)++ names = [s.name for s in schemas]+ assert names == [*ENDPOINTS, *[f"acme/other.{endpoint}" for endpoint in ENDPOINTS]]+ qualified = {s.name: s for s in schemas if s.schema_metadata}+ assert set(qualified) == {f"acme/other.{endpoint}" for endpoint in ENDPOINTS}+ assert qualified["acme/other.issues"].schema_metadata == {+ "source_repository": "acme/other",+ "source_endpoint": "issues",+ }+ assert qualified["acme/other.issues"].label == "acme/other · issues"++ def test_get_schemas_new_format_source_is_fully_qualified_even_with_one_repo(self):+ # New sources always qualify so adding repo #2 later never renames anything.+ schemas = self.source.get_schemas(_pat_config(repositories=["acme/widgets"]), self.team_id)+ assert [s.name for s in schemas] == [f"acme/widgets.{endpoint}" for endpoint in ENDPOINTS]+ assert all(s.schema_metadata for s in schemas)++ @pytest.mark.parametrize(+ "schema_name,expected_key",+ [+ ("workflow_runs", "workflow_run"),+ ("workflow_jobs", "workflow_job"),+ ("reviews", "pull_request_review"),+ # Qualified rows get repo-qualified keys — two repos' workflow_runs would otherwise+ # collide on one "workflow_run" key and route all events to a single schema.+ ("acme/Widgets.workflow_runs", "acme/widgets.workflow_run"),+ ("acme/other.reviews", "acme/other.pull_request_review"),+ ],+ )+ def test_webhook_mapping_key(self, schema_name, expected_key):+ assert self.source.webhook_mapping_key(schema_name) == expected_key++ def test_get_desired_webhook_events_handles_qualified_names_and_dedupes(self):+ config = _pat_config(repositories=["a/b", "c/d"])+ events = self.source.get_desired_webhook_events(+ config, ["a/b.workflow_runs", "c/d.workflow_runs", "a/b.reviews", "a/b.issues"]+ )+ assert events == ["workflow_run", "pull_request_review"]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.source.validate_github_credentials"+ )+ def test_validate_credentials_aggregates_per_repo_failures(self, mock_validate):+ mock_validate.side_effect = [+ (True, None),+ (False, "Repository 'a/missing' not found or not accessible"),+ ]++ valid, message = self.source.validate_credentials(_pat_config(repositories=["a/ok", "a/missing"]), self.team_id)++ assert valid is False+ assert message is not None and "a/missing" in message++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.source.validate_github_credentials"+ )+ def test_validate_credentials_short_circuits_on_bad_token(self, mock_validate):+ # A 401 is token-level; probing the remaining repos would produce N identical failures.+ mock_validate.side_effect = [(False, "Invalid personal access token")]++ valid, message = self.source.validate_credentials(_pat_config(repositories=["a/b", "c/d", "e/f"]), self.team_id)++ assert valid is False+ assert message == "Invalid personal access token"+ assert mock_validate.call_count == 1++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.github.source.github_source")+ def test_source_for_pipeline_resolves_repo_from_metadata(self, mock_github_source):+ config = _pat_config(repository="legacy/repo", repositories=["legacy/repo", "acme/other"])+ inputs = mock.MagicMock()+ inputs.team_id = self.team_id+ inputs.schema_name = "acme/other.issues"+ inputs.schema_metadata = {"source_repository": "acme/other", "source_endpoint": "issues"}+ inputs.s3_folder_name = "acme_other_issues"+ inputs.should_use_incremental_field = False++ self.source.source_for_pipeline(config, mock.MagicMock(), inputs)++ kwargs = mock_github_source.call_args.kwargs+ assert kwargs["repository"] == "acme/other"+ assert kwargs["endpoint"] == "issues"+ assert kwargs["response_name"] == "acme_other_issues"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.github.source.github_source")+ def test_source_for_pipeline_bare_row_falls_back_to_legacy_repo(self, mock_github_source):+ config = _pat_config(repository="legacy/repo", repositories=["legacy/repo", "acme/other"])+ inputs = mock.MagicMock()+ inputs.team_id = self.team_id+ inputs.schema_name = "issues"+ inputs.schema_metadata = None+ inputs.s3_folder_name = "issues"+ inputs.should_use_incremental_field = False++ self.source.source_for_pipeline(config, mock.MagicMock(), inputs)++ kwargs = mock_github_source.call_args.kwargs+ assert kwargs["repository"] == "legacy/repo"+ assert kwargs["endpoint"] == "issues"+ assert kwargs["response_name"] == "issues"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.github.source.ensure_repo_webhook")+ def test_create_webhook_shares_one_secret_across_repos(self, mock_ensure):+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import WebhookCreationResult++ mock_ensure.return_value = WebhookCreationResult(success=True, extra_inputs={"signing_secret": "ignored"})+ config = _pat_config(repositories=["a/b", "c/d"])++ result = self.source.create_webhook(config, "https://hooks/x", self.team_id)++ assert result.success is True+ secrets_used = {call.kwargs["secret"] for call in mock_ensure.call_args_list}+ # One hog function has one signing_secret input, so every repo's hook must share it.+ assert len(mock_ensure.call_args_list) == 2+ assert len(secrets_used) == 1+ assert result.extra_inputs == {"signing_secret": secrets_used.pop()}++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.github.source.ensure_repo_webhook")+ def test_create_webhook_partial_failure_keeps_secret_and_reports_repos(self, mock_ensure):+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import WebhookCreationResult++ mock_ensure.side_effect = [+ WebhookCreationResult(success=True, extra_inputs={"signing_secret": "x"}),+ WebhookCreationResult(success=False, error="boom"),+ ]+ config = _pat_config(repositories=["a/b", "c/d"])++ result = self.source.create_webhook(config, "https://hooks/x", self.team_id)++ assert result.success is False+ assert result.error is not None and "c/d: boom" in result.error+ # The repo that did get a hook verifies against this secret, so it must still persist.+ assert result.extra_inputs.get("signing_secret")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_template.pyindex bf010b8bfde1..e97c4fd61659 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_template.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_template.py@@ -41,9 +41,22 @@ class TestGithubWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):data["request"].update(globals["request"])return data- def _run(self, event_type: str, body: dict[str, Any], schema_mapping: dict[str, str]) -> Any:+ def _run(+ self,+ event_type: str,+ body: dict[str, Any],+ schema_mapping: dict[str, str],+ legacy_repository: str | None = None,+ ) -> Any:+ inputs: dict[str, Any] = {+ "signing_secret": "",+ "bypass_signature_check": True,+ "schema_mapping": schema_mapping,+ }+ if legacy_repository is not None:+ inputs["legacy_repository"] = legacy_repositoryreturn self.run_function(- {"signing_secret": "", "bypass_signature_check": True, "schema_mapping": schema_mapping},+ inputs,globals={"request": {"method": "POST",@@ -95,3 +108,54 @@ class TestGithubWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):assert res.result["httpResponse"]["status"] == 200self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_repo_qualified_mapping_routes_by_repository_full_name(self):+ # Multi-repo sources key the mapping by 'owner/repo.event' — without the qualified lookup+ # two repos' workflow events would all land in whichever schema owns the bare key.+ job = {"id": 1, "status": "completed"}+ body = {"action": "completed", "workflow_job": job, "repository": {"full_name": "Acme/Widgets"}}+ mapping = {"acme/widgets.workflow_job": "schema_widgets_jobs", "workflow_job": "schema_legacy_jobs"}++ self._run("workflow_job", body, mapping)++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(job, "schema_widgets_jobs")++ def test_unqualified_repo_falls_back_to_bare_event_mapping(self):+ # Legacy single-repo mappings only carry bare event keys; a payload from any repo must+ # keep routing through them.+ job = {"id": 1, "status": "completed"}+ body = {"action": "completed", "workflow_job": job, "repository": {"full_name": "acme/other"}}++ self._run("workflow_job", body, {"workflow_job": "schema_legacy_jobs"})++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(job, "schema_legacy_jobs")++ def test_unmapped_repo_and_event_no_ops(self):+ body = {"action": "completed", "workflow_job": {"id": 1}, "repository": {"full_name": "acme/unknown"}}+ res = self._run("workflow_job", body, {"acme/widgets.workflow_job": "schema_widgets_jobs"})++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_bare_key_fallback_is_bound_to_legacy_repository(self):+ # A mixed source keeps the legacy repo's rows on the bare event key and other repos' rows+ # qualified. An event from a secondary repo whose qualified schema is disabled/removed must+ # NOT fall back to the legacy repo's bare key — that would write one repo's data into+ # another repo's schema. With legacy_repository pinned, the fallback is skipped.+ job = {"id": 1, "status": "completed"}+ body = {"action": "completed", "workflow_job": job, "repository": {"full_name": "acme/secondary"}}++ res = self._run("workflow_job", body, {"workflow_job": "schema_legacy_jobs"}, legacy_repository="acme/legacy")++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_legacy_repository_event_still_routes_through_bare_key(self):+ # The legacy repo's own events (its rows stay bare) keep routing through the bare key; the+ # repo comparison is case-insensitive to match GitHub's case-insensitive full names.+ job = {"id": 2, "status": "completed"}+ body = {"action": "completed", "workflow_job": job, "repository": {"full_name": "Acme/Legacy"}}++ self._run("workflow_job", body, {"workflow_job": "schema_legacy_jobs"}, legacy_repository="acme/legacy")++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(job, "schema_legacy_jobs")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/webhook_template.pyindex fd913181f978..23cb9a8ca6ed 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/webhook_template.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/webhook_template.py@@ -67,7 +67,21 @@ if (empty(eventType)) {}}-let schemaId := inputs.schema_mapping?.[eventType]+// Multi-repo sources key their mapping by 'owner/repo.event' (the payload's+// repository.full_name, lowercased) so two repos' events route to their own schemas.+// The bare event-type key remains as the fallback for legacy single-repo mappings.+let repoFullName := request.body?.repository?.full_name+let schemaId := null+if (not empty(repoFullName)) {+ schemaId := inputs.schema_mapping?.[concat(lower(repoFullName), '.', eventType)]+}+// The bare event-type key belongs to the legacy repository only. Restricting the fallback to the+// legacy repo (or to functions with no legacy binding — pure multi-repo mappings have no bare key,+// and pre-multi-repo functions predate this input) stops a secondary repo whose qualified schema+// is disabled/removed from leaking its events into the legacy repo's schema.+if (empty(schemaId) and (empty(inputs.legacy_repository) or lower(repoFullName) = lower(inputs.legacy_repository))) {+ schemaId := inputs.schema_mapping?.[eventType]+}if (empty(schemaId)) {return {@@ -152,7 +166,7 @@ produceToWarehouseWebhooks(row, schemaId)""","type": "json","key": "schema_mapping","label": "Schema mapping",- "description": "Maps GitHub event types (workflow_job, workflow_run, pull_request_review) to ExternalDataSchema IDs",+ "description": "Maps GitHub event types to ExternalDataSchema IDs. Keys are either a bare event type (workflow_job, workflow_run, pull_request_review) for legacy single-repo sources, or 'owner/repo.event_type' for multi-repo sources.","required": True,"secret": False,"hidden": True,@@ -166,5 +180,14 @@ produceToWarehouseWebhooks(row, schemaId)""","secret": False,"hidden": True,},+ {+ "type": "string",+ "key": "legacy_repository",+ "label": "Legacy repository",+ "description": "For multi-repo GitHub sources, the 'owner/repo' whose schema rows keep bare event keys. The bare-key fallback only routes events from this repository, so other repos can't leak into it. Empty for single-repo or pure multi-repo sources.",+ "required": False,+ "secret": False,+ "hidden": True,+ },],)diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.pyindex 48af94a3a700..ba364dae3827 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py@@ -90,10 +90,18 @@ def sync_new_schemas_activity(inputs: SyncNewSchemasActivityInputs) -> None:# TODO: this could cause a race condition where each schema worker creates the missing schema+ # 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+ # per-repo location metadata on newly created rows.+ is_github = source_type_enum == ExternalDataSourceType.GITHUBschemas_created, schemas_deleted = sync_old_schemas_with_new_schemas(schemas_to_sync,source_id=inputs.source_id,team_id=inputs.team_id,+ 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+ else None,)if len(schemas_created) > 0:diff --git a/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py b/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.pyindex 1553936cdb95..fa947bb3d92e 100644--- a/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py+++ b/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py@@ -87,3 +87,54 @@ class TestSchemaDiscoveryReconcile(BaseTest):assert existing.should_sync is Trueassert "analytics.users" in createdassert ExternalDataSchema.objects.filter(source_id=source.pk, name="analytics.users").exists()++ def test_strict_match_creates_qualified_row_alongside_legacy_bare_row(self) -> None:+ # GitHub keeps its legacy repo's rows bare forever, so a second repo's qualified rows+ # coexist with them. Without strict matching, `acme/other.issues` tail-matches the bare+ # `issues` row and repo #2's rows are silently never created.+ source = self._make_source()+ legacy = self._make_synced_schema(source, "issues")++ created, _deleted = sync_old_schemas_with_new_schemas(+ {"issues": None, "acme/other.issues": "acme/other · issues"},+ source_id=str(source.pk),+ team_id=self.team.pk,+ strict_name_match=True,+ schema_metadata_by_name={+ "acme/other.issues": {"source_repository": "acme/other", "source_endpoint": "issues"}+ },+ )++ legacy.refresh_from_db()+ assert legacy.should_sync is True+ assert created == ["acme/other.issues"]+ new_row = ExternalDataSchema.objects.get(source_id=source.pk, name="acme/other.issues")+ assert new_row.sync_type_config.get("schema_metadata") == {+ "source_repository": "acme/other",+ "source_endpoint": "issues",+ }++ def test_strict_match_retires_removed_repo_rows(self) -> None:+ # Removing a repo drops its names from discovery: synced rows keep their table but stop+ # syncing; never-synced rows soft-delete. The legacy bare row must survive untouched.+ source = self._make_source()+ legacy = self._make_synced_schema(source, "issues")+ synced_removed = self._make_synced_schema(source, "acme/other.issues")+ unsynced_removed = ExternalDataSchema.objects.create(+ team_id=self.team.pk, source_id=source.pk, name="acme/other.commits", should_sync=False+ )++ sync_old_schemas_with_new_schemas(+ {"issues": None},+ source_id=str(source.pk),+ team_id=self.team.pk,+ strict_name_match=True,+ )++ legacy.refresh_from_db()+ synced_removed.refresh_from_db()+ unsynced_removed.refresh_from_db()+ assert legacy.should_sync is True+ assert synced_removed.should_sync is False+ assert synced_removed.deleted is False+ assert unsynced_removed.deleted is True