: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(warehouse sources): sync github teams and team members (#69582)
Julian Bez845519802007
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 e2655525a6d0..46c48fd9487e 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@@ -67,17 +67,20 @@ def _select_incremental_field(incremental_fields: list[IncrementalField]) -> Incdef build_default_schemas(source_schemas: list[SourceSchema]) -> list[dict]:"""Build a default ``schemas`` payload for one-shot source creation.- Enables every discovered table and picks a sync type per table: ``incremental`` when the- source supports it and a tracking column exists (cheapest ongoing sync), else ``append``- when supported, else ``full_refresh``. Never defaults to ``cdc`` — that needs Postgres- prerequisites and explicit opt-in. Webhook-only tables start disabled because webhook- registration needs the created source; the setup flow attempts it right after creation- and, on success, switches webhook-capable tables to the webhook sync method. These- polling defaults are also the fallback when that registration fails.+ Enables every discovered table the source marks as default-on and picks a sync type per+ table: ``incremental`` when the source supports it and a tracking column exists (cheapest+ ongoing sync), else ``append`` when supported, else ``full_refresh``. Never defaults to+ ``cdc`` — that needs Postgres prerequisites and explicit opt-in. Webhook-only tables start+ disabled because webhook registration needs the created source; the setup flow attempts it+ right after creation and, on success, switches webhook-capable tables to the webhook sync+ method. These polling defaults are also the fallback when that registration fails. Tables+ with ``should_sync_default=False`` also start disabled: sources use it for tables whose+ sync needs grants beyond what source creation validated, and the schema picker already+ honors it, so one-shot setup must not force-enable what the picker would leave off."""schemas: list[dict] = []for source_schema in source_schemas:- if source_schema.webhook_only:+ if source_schema.webhook_only or not source_schema.should_sync_default:schemas.append({"name": source_schema.name, "should_sync": False})continuediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.pyindex 9825fb89bab8..59277d3f87ad 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py@@ -103,6 +103,22 @@ class TestBuildDefaultSchemas:)assert schemas == [{"name": "discounts", "should_sync": False}]+ def test_default_off_table_left_disabled(self) -> None:+ # A source marks a table should_sync_default=False when syncing it needs grants beyond+ # what source creation validated (e.g. GitHub org tables). One-shot setup force-enabling+ # it would make the first sync fail; it must start disabled like the picker leaves it.+ schemas = build_default_schemas(+ [+ SourceSchema(+ name="teams",+ supports_incremental=False,+ supports_append=False,+ should_sync_default=False,+ )+ ]+ )+ assert schemas == [{"name": "teams", "should_sync": False}]+def test_never_defaults_to_cdc(self) -> None:schemas = build_default_schemas([diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/canonical_descriptions.pyindex 83e4f43373f0..f79108509084 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/canonical_descriptions.py@@ -139,4 +139,40 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"created_at": "Time at which the job was created.",},},+ "teams": {+ "description": "A team within the repository's organization.",+ "docs_url": "https://docs.github.com/en/rest/teams/teams",+ "columns": {+ "id": "Unique identifier for the team.",+ "node_id": "Global node ID for the team.",+ "name": "The team's display name.",+ "slug": "URL-friendly identifier for the team, unique within the organization.",+ "description": "The team's description.",+ "privacy": "The level of privacy the team should have (closed or secret).",+ "notification_setting": "Whether team members are notified of activity on team-mentioned threads.",+ "permission": "The default repository permission granted to the team.",+ "parent": "The parent team this team is nested under, if any.",+ "url": "API URL for the team.",+ "html_url": "Web URL for the team on GitHub.",+ "members_url": "Templated API URL for the team's members.",+ "repositories_url": "API URL for the team's repositories.",+ },+ },+ "team_members": {+ "description": "A user who is a member of a team in the repository's organization. One row per team membership, with the team's id, slug, and name attached.",+ "docs_url": "https://docs.github.com/en/rest/teams/members",+ "columns": {+ "id": "Unique identifier for the member user.",+ "team_id": "Identifier of the team this membership belongs to (injected from the parent team).",+ "team_slug": "URL-friendly identifier of the team this membership belongs to (injected from the parent team).",+ "team_name": "Display name of the team this membership belongs to (injected from the parent team).",+ "login": "Username of the member.",+ "node_id": "Global node ID for the member user.",+ "type": "Type of account (User or Bot).",+ "site_admin": "Whether the member is a GitHub site administrator.",+ "avatar_url": "URL of the member's avatar image.",+ "url": "API URL for the member user.",+ "html_url": "Web URL for the member's GitHub profile.",+ },+ },}diff --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 2be8254e41aa..4fa01cf196c5 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@@ -132,8 +132,15 @@ def _build_initial_params(return params+def _organization_from_repository(repository: str) -> str:+ """Org-scoped endpoints (teams) derive the org from the repo owner: "owner/repo" -> "owner".+ The source config only carries the repository, so the owner is the only org signal we have."""+ return repository.split("/")[0]++def _build_initial_url(config: GithubEndpointConfig, repository: str, params: dict[str, Any]) -> str:- path = config.path.format(repository=repository)+ # str.format ignores extra kwargs, so passing organization is safe for repo-only paths too.+ path = config.path.format(repository=repository, organization=_organization_from_repository(repository))if not params:return f"{GITHUB_BASE_URL}{path}"return f"{GITHUB_BASE_URL}{path}?{urlencode(params)}"@@ -276,6 +283,52 @@ def validate_credentials(personal_access_token: str, repository: str) -> tuple[breturn False, str(e)+# Endpoints that read organization data (not repo data). They need the GitHub App "Members: Read"+# org permission (or the read:org PAT scope) and an org-owned repo; a user-owned repo has no org,+# so /orgs/{owner}/teams 404s. Repo-scoped connections may legitimately lack this, so it must be+# reported per-table in the schema picker, never block source-create.+ORG_SCOPED_ENDPOINTS = frozenset({"teams", "team_members"})++_ORG_PERMISSION_REASON = (+ "Requires the 'Members: Read' organization permission on the GitHub App, or the read:org scope "+ "on a personal access token, and an organization-owned repository"+)+++def check_org_endpoint_permission(+ personal_access_token: str, repository: str, egress_identity: GithubEgressIdentity | None = None+) -> str | None:+ """Probe the org teams endpoint once. Returns None when reachable, or a short reason when the+ org grant is missing. Only a real denial (401/403/404) is a missing scope; rate limits, 5xx,+ egress-budget denials, and network errors mean we could not tell, so treat those as reachable+ (the sync will surface a real failure if there is one) rather than mislabeling a transient blip+ as a permission problem."""+ organization = _organization_from_repository(repository)+ url = f"{GITHUB_BASE_URL}/orgs/{organization}/teams?per_page=1"+ installation_id = egress_identity.installation_id if egress_identity is not None else None+ try:+ # Same gated + recorded transport as the data plane. NORMAL, not BATCH: a single interactive+ # schema-picker probe is not deferrable bulk; if the limiter sheds it anyway, that maps to+ # "could not tell" below rather than a wrong permission verdict.+ response = github_request(+ "GET",+ url,+ source="warehouse",+ headers=_get_headers(personal_access_token),+ installation_id=installation_id,+ priority=Priority.NORMAL,+ timeout=10,+ session=make_tracked_session(),+ )+ # A rate-limited 403 carries limit markers; without this check it would read as a missing grant.+ raise_if_github_rate_limited(response)+ except (GitHubEgressBudgetExhausted, GitHubRateLimitError, requests.exceptions.RequestException):+ return None+ if response.status_code in (401, 403, 404):+ return _ORG_PERMISSION_REASON+ return None++def _flatten_commit(item: dict[str, Any]) -> dict[str, Any]:"""Flatten commit data by extracting nested author/committer info."""if "commit" in item and isinstance(item["commit"], dict):@@ -323,6 +376,21 @@ def _is_issue_not_pr(item: dict[str, Any]) -> bool:return "pull_request" not in item or item["pull_request"] is None+def _make_parent_field_injector(+ parent: dict[str, Any], field_map: dict[str, str]+) -> Callable[[dict[str, Any]], dict[str, Any]]:+ """Copy the mapped parent fields onto each child row (e.g. team id/slug/name onto a member),+ so a fan-out child carries the parent context its own API response omits. Direct access on the+ parent fields: the injected columns feed the child's composite primary key, so a parent missing+ one is a broken response that must fail loudly, not corrupt the key with None."""+ injected = {child_column: parent[parent_field] for parent_field, child_column in field_map.items()}++ def inject(item: dict[str, Any]) -> dict[str, Any]:+ return {**item, **injected}++ return inject++def _get_item_mapper(endpoint: str) -> Callable[[dict[str, Any]], dict[str, Any]] | None:if endpoint == "commits":return _flatten_commit@@ -468,27 +536,34 @@ def _iter_pages(url = next_url-def _iter_jobs_for_run(+def _iter_child_for_parent(repository: str,- run_id: Any,+ parent_value: Any,headers: dict[str, str],logger: FilteringBoundLogger,config: GithubEndpointConfig,egress_identity: GithubEgressIdentity | None = None,) -> Iterator[dict[str, Any]]:- path = config.path.format(repository=repository, run_id=run_id)+ """Walk a fan-out child endpoint for one parent, substituting the parent's value into the+ child path placeholder (e.g. {run_id} for workflow_jobs, {team_slug} for team_members)."""+ fan_out_param = config.fan_out_path_param+ path = config.path.format(+ repository=repository,+ organization=_organization_from_repository(repository),+ **{fan_out_param: parent_value},+ )params: dict[str, Any] = {"per_page": config.page_size, **(config.extra_params or {})}url = f"{GITHUB_BASE_URL}{path}?{urlencode(params)}"- for jobs, _page_url in _iter_pages(+ for items, _page_url in _iter_pages(url,headers,config.response_data_path,logger,max_pages=config.max_pages_per_parent,- page_cap_context={"repository": repository, "run_id": run_id},+ page_cap_context={"repository": repository, fan_out_param: parent_value},egress_identity=egress_identity,):- yield from jobs+ yield from itemsdef _fan_out_get_rows(@@ -502,18 +577,19 @@ def _fan_out_get_rows(incremental_field: str | None,egress_identity: GithubEgressIdentity | None = None,) -> Iterator[Any]:- """Single-hop parent->child fan-out: walk the parent endpoint newest-first and- emit every child row for each parent. Incremental bounding happens on the- parent's created_at cursor (the same desc early-stop workflow_runs uses).-- The child cursor value (max job created_at) is compared against the parent's- created_at — they coincide closely since a job is created when its run starts,- so the watermark sits slightly above the newest run's timestamp. Re-reading a- boundary parent is harmless (jobs upsert by id), but note the inverse: a run- that was in_progress when first synced drops below the watermark once it- finishes, so its terminal job conclusions and any later-added jobs are not- re-fetched. This is the same created_at-cursor staleness workflow_runs carries;- the workflow_run webhook (followup) is the fix, not re-scanning history.+ """Single-hop parent->child fan-out: walk the parent endpoint and emit every child row for each+ parent, substituting the parent's field into the child path (workflow_jobs -> {run_id},+ team_members -> {team_slug}) and optionally injecting parent fields onto each child row.++ Incremental bounding only applies when the parent endpoint has its own cursor. workflow_runs+ carries a created_at cursor, so its jobs fan-out stops early once a page predates the watermark+ (the same desc early-stop the run poll uses); a boundary re-read is harmless since jobs upsert by+ id. Full-refresh parents (teams) have no cursor, so every parent is walked each sync; the data+ volume is tiny, and there is no timestamp to bound on anyway.++ Same created_at-cursor staleness workflow_runs carries applies to its jobs: a run that was+ in_progress when first synced drops below the watermark once it finishes, so later job state is+ not re-fetched by the poll; the workflow_run webhook is the fix, not re-scanning history."""child_config = GITHUB_ENDPOINTS[endpoint]assert child_config.fan_out_parent is not None # guarded by the get_rows dispatch@@ -521,15 +597,20 @@ def _fan_out_get_rows(headers = _get_headers(personal_access_token, endpoint)batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)- parent_field = incremental_field or parent_config.default_incremental_field or "created_at"- parent_cutoff = db_incremental_field_last_value if should_use_incremental_field else None+ # A parent with no incremental fields (teams) has no cursor to bound on, so walk it whole.+ parent_is_incremental = bool(parent_config.incremental_fields)+ parent_cursor_field = incremental_field or parent_config.default_incremental_field or "created_at"+ parent_cutoff = (+ db_incremental_field_last_value if (should_use_incremental_field and parent_is_incremental) else None+ )# First incremental sync (watermark set up, but nothing synced yet): floor the- # backfill at a recent window instead of fanning out over the repo's entire run+ # backfill at a recent window instead of fanning out over the parent's entire# history. Scoped to the incremental first run on purpose — an explicit full# refresh still pulls everything, and later syncs advance from their watermark.if (- should_use_incremental_field+ parent_is_incremental+ and should_use_incremental_fieldand db_incremental_field_last_value is Noneand child_config.initial_lookback_days is not None):@@ -543,23 +624,30 @@ def _fan_out_get_rows(else:parent_url = _build_initial_url(parent_config, repository, {"per_page": parent_config.page_size})- for runs, page_url in _iter_pages(+ for parents, page_url in _iter_pages(parent_url, headers, parent_config.response_data_path, logger, egress_identity=egress_identity):- stop_after_this_page = _should_stop_desc(runs, "desc", parent_field, parent_cutoff)+ stop_after_this_page = _should_stop_desc(parents, "desc", parent_cursor_field, parent_cutoff)- for run in runs:- # Direct access on the run's id (its primary key): a run without one is a broken+ for parent in parents:+ # Direct access on the parent's fan-out field (id/slug): a parent missing it is a broken# response that should fail loudly, not get silently dropped.- run_id = run["id"]+ parent_value = parent[child_config.fan_out_parent_field]# Only fan out parents at/above the watermark; older ones were synced before.- if parent_cutoff is not None and _is_older_than_cutoff(run.get(parent_field), parent_cutoff):+ if parent_cutoff is not None and _is_older_than_cutoff(parent.get(parent_cursor_field), parent_cutoff):continue- for job in _iter_jobs_for_run(repository, run_id, headers, logger, child_config, egress_identity):- batcher.batch(job)+ inject = (+ _make_parent_field_injector(parent, child_config.fan_out_include_parent_fields)+ if child_config.fan_out_include_parent_fields+ else None+ )+ for item in _iter_child_for_parent(+ repository, parent_value, headers, logger, child_config, egress_identity+ ):+ batcher.batch(inject(item) if inject else item)if batcher.should_yield():yield batcher.get_table()- # Checkpoint the parent page; resume re-fans it out and dedupes by id.+ # Checkpoint the parent page; resume re-fans it out and dedupes by primary key.if not stop_after_this_page:resumable_source_manager.save_state(GithubResumeConfig(next_url=page_url))@@ -673,6 +761,12 @@ def get_rows(yield py_table+def _normalize_primary_key(primary_key: str | list[str]) -> list[str]:+ """A config primary_key is a single column str or a composite list; SourceResponse always wants+ a list, so normalize here rather than storing the shape difference downstream."""+ return [primary_key] if isinstance(primary_key, str) else list(primary_key)++def _make_webhook_dedupe_transformer(primary_key: str, version_keys: list[str]) -> Callable[[pa.Table], pa.Table]:"""Collapse a webhook batch to one row per ``primary_key`` — the one ranking newest by``version_keys`` (newest first, NULLs last). GitHub emits a single run/job as separate@@ -761,8 +855,13 @@ def github_source(# Each event for an id arrives as its own row (queued -> in_progress -> completed);# collapse them to the latest per id here, since the delta merge doesn't dedupe a# source batch. Same pattern as the Stripe webhook source.+ # Webhook-capable endpoints all key on a single column; the dedupe transformer+ # collapses one pk column, so pass the first (only) key. Fan-out children with+ # composite keys have no version_keys, so this branch never runs for them.transformer = (- _make_webhook_dedupe_transformer(endpoint_config.primary_key, endpoint_config.version_keys)+ _make_webhook_dedupe_transformer(+ _normalize_primary_key(endpoint_config.primary_key)[0], endpoint_config.version_keys+ )if endpoint_config.version_keyselse None)@@ -783,7 +882,7 @@ def github_source(return SourceResponse(name=endpoint,items=items,- primary_keys=[endpoint_config.primary_key],+ primary_keys=_normalize_primary_key(endpoint_config.primary_key),sort_mode=actual_sort_mode,partition_count=1,partition_size=1,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.pyindex 1ec3d83eabff..b2910dd0fabf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py@@ -7,13 +7,20 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment@dataclassclass GithubEndpointConfig:name: str- path: str # Path template with {repository} placeholder+ path: str # Path template with {repository}, {organization}, and fan-out placeholdersincremental_fields: list[IncrementalField]default_incremental_field: Optional[str] = Nonepartition_key: Optional[str] = Nonepage_size: int = 100 # GitHub default, max is 100sort_mode: Literal["asc", "desc"] = "asc"- primary_key: str = "id" # Primary key for upsert operations+ # Primary key for upsert operations. A list declares a composite key, required for+ # fan-out children whose row id is only unique within a parent (a user can belong to+ # two teams, so team_members keys on ["team_id", "id"] to stay unique table-wide).+ primary_key: str | list[str] = "id"+ # False leaves the table deselected in the schema picker and disabled by one-shot setup.+ # Use for tables needing grants beyond the repo scope validated at source-create, so a+ # default connection doesn't enable a table whose first sync would 403.+ should_sync_default: bool = True# Ordered columns (compared newest-first, NULLs last) that rank webhook events sharing a# primary key, so the source collapses a batch to the latest state per id before it reaches the# delta merge (which doesn't dedupe within a batch). GitHub emits one run/job as separate@@ -27,8 +34,16 @@ class GithubEndpointConfig:# Fan-out: name of the parent endpoint whose rows seed this child's path.# When set, the endpoint is fetched by walking the parent (reusing its# pagination/incremental bounding) and calling this child once per parent- # row, substituting the parent id into the {run_id} path placeholder.+ # row, substituting a parent field into the child path placeholder.fan_out_parent: Optional[str] = None+ # Fan-out path placeholder to fill from the parent (e.g. "run_id" -> {run_id},+ # "team_slug" -> {team_slug}) and the parent field to read for it.+ fan_out_path_param: str = "run_id"+ fan_out_parent_field: str = "id"+ # Parent fields to copy onto each child row, mapped to the child column name+ # (e.g. {"id": "team_id", "slug": "team_slug"}). Gives fan-out children the+ # parent context the child API omits; team_members rows are plain users.+ fan_out_include_parent_fields: Optional[dict[str, str]] = None# Extra static query params for the request (e.g. {"filter": "all"}).extra_params: Optional[dict[str, str]] = None# Hard cap on pages fetched per parent in a fan-out, to bound runaway@@ -188,6 +203,37 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {# the job reaches that stage, so NULLs-last ordering keeps the latest state.version_keys=["completed_at", "started_at", "created_at"],),+ "teams": GithubEndpointConfig(+ name="teams",+ # Org-scoped: {organization} is derived from the repository owner (owner/repo -> owner).+ path="/orgs/{organization}/teams",+ # The teams endpoint exposes no timestamps or server-side time filter, so there is no+ # cursor to sync incrementally on, so full refresh each sync (data volume is tiny).+ incremental_fields=[],+ # Needs the org Members: Read grant (read:org on PATs), which repo-scoped connections+ # lack, and 404s on user-owned repos. Off by default so a fresh source doesn't enable+ # a table whose first sync fails; the picker's permission probe explains the grant.+ should_sync_default=False,+ ),+ "team_members": GithubEndpointConfig(+ name="team_members",+ # Child of teams: {team_slug} is filled per parent team during fan-out.+ path="/orgs/{organization}/teams/{team_slug}/members",+ incremental_fields=[], # Member list has no timestamps either; full refresh only.+ # Composite key: a user in two teams must be two distinct rows, and a fan-out child's+ # key must be unique table-wide or the delta merge multi-matches and degrades every sync.+ primary_key=["team_id", "id"],+ fan_out_parent="teams",+ fan_out_path_param="team_slug",+ fan_out_parent_field="slug",+ # Member rows are plain user objects with no team context, so inject it from the parent team.+ fan_out_include_parent_fields={"id": "team_id", "slug": "team_slug", "name": "team_name"},+ should_sync_default=False, # Same org grant requirement as teams.+ # The default cap (50 pages, sized for per-run job lists) would silently truncate a team+ # past 5,000 members at 100/page. 400 pages bounds a runaway paginator at 40,000+ # memberships per team while clearing any plausible real team; the cap still logs.+ max_pages_per_parent=400,+ ),}ENDPOINTS = tuple(GITHUB_ENDPOINTS.keys())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 d4422f428673..88592fd209e6 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@@ -40,8 +40,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GithubSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.github.github import (+ ORG_SCOPED_ENDPOINTS,GithubEgressIdentity,GithubResumeConfig,+ check_org_endpoint_permission,create_repo_webhook,delete_repo_webhook,get_repo_webhook_info,@@ -259,6 +261,7 @@ If automatic creation failed, your token needs webhook permissions — the **admsupports_webhooks=webhook_capable,webhook_only=webhook_only,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=GITHUB_ENDPOINTS[endpoint].should_sync_default,)def get_schemas(@@ -275,6 +278,43 @@ If automatic creation failed, your token needs webhook permissions — the **admschemas = [s for s in schemas if s.name in names_set]return schemas+ def get_endpoint_permissions(+ self, 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.+ result: dict[str, str | None] = dict.fromkeys(endpoints)+ org_endpoints = [name for name in endpoints if name in ORG_SCOPED_ENDPOINTS]+ if not org_endpoints:+ return result+ try:+ access_token = self._get_access_token(config, team_id)+ egress_identity = self._egress_identity(config, team_id)+ except Exception as e:+ # A broken credential (deleted integration, suspended installation) must become a+ # per-table reason here rather than propagate: the schema-picker caller swallows+ # exceptions and falls back to "all reachable", which would show the org tables as+ # available and defer the failure to sync time. Reuse the curated wording, like+ # validate_credentials does.+ raw = str(e)+ credential_reason = next(+ (+ friendly+ for pattern, friendly in self.get_non_retryable_errors().items()+ if friendly and pattern in raw+ ),+ raw,+ )+ for name in org_endpoints:+ result[name] = credential_reason+ return result+ reason = check_org_endpoint_permission(access_token, config.repository, egress_identity)+ for name in org_endpoints:+ result[name] = reason+ return result+def validate_credentials(self, config: GithubSourceConfig, team_id: int, schema_name: Optional[str] = None) -> tuple[bool, str | None]: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 38048eb00974..511940a5e784 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@@ -72,6 +72,53 @@ class TestGithubSource:assert expected_error in self.source.get_non_retryable_errors()+ def test_endpoint_permissions_surface_credential_errors_per_table(self):+ # The schema-picker caller swallows exceptions from get_endpoint_permissions and falls back+ # to "all reachable", so a raising token fetch must be mapped to a per-table reason here or+ # a broken integration shows the org tables as available and fails only at sync time.+ config = GithubSourceConfig(+ auth_method=GithubAuthMethodConfig(github_integration_id=None, selection="oauth", personal_access_token=""),+ repository="acme/widgets",+ )++ result = self.source.get_endpoint_permissions(config, self.team_id, ["teams", "team_members", "issues"])++ assert result["issues"] is None+ assert result["teams"] == "No GitHub account is connected. Please reconnect your GitHub account."+ assert result["team_members"] == result["teams"]++ @pytest.mark.parametrize("endpoint", ["teams", "team_members"])+ def test_org_schemas_are_full_refresh_only_and_off_by_default(self, endpoint):+ # teams / team_members expose no timestamps, so they must never advertise incremental,+ # append, or webhook sync; otherwise the picker would offer a mode that syncs nothing.+ # And they need an org grant repo-scoped connections lack, so they must start+ # deselected; default-on would make a fresh source's first sync fail with 403/404.+ config = GithubSourceConfig(+ auth_method=GithubAuthMethodConfig(github_integration_id=None, selection="pat", personal_access_token="t"),+ repository="acme/widgets",+ )+ schemas = {s.name: s for s in self.source.get_schemas(config, self.team_id)}++ assert endpoint in schemas+ schema = schemas[endpoint]+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.supports_webhooks is False+ assert schema.webhook_only is False+ assert schema.should_sync_default is False++ def test_existing_workflow_schemas_stay_webhook_capable(self):+ # Guard that adding the org endpoints didn't disturb the webhook-capable schemas.+ config = GithubSourceConfig(+ auth_method=GithubAuthMethodConfig(github_integration_id=None, selection="pat", personal_access_token="t"),+ repository="acme/widgets",+ )+ schemas = {s.name: s for s in self.source.get_schemas(config, self.team_id)}++ assert schemas["workflow_runs"].supports_webhooks is True+ assert schemas["workflow_jobs"].supports_webhooks is True+ assert all(s.should_sync_default for s in schemas.values() if s.name not in ("teams", "team_members"))+def test_get_access_token_returns_pat(self):config = GithubSourceConfig(auth_method=GithubAuthMethodConfig(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_teams.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_teams.pynew file mode 100644index 000000000000..3e7b5f051b99--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_teams.py@@ -0,0 +1,165 @@+from typing import Any++import pytest+from unittest import mock++import pyarrow as pa+import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.github import github+++def _response(rows: list[dict[str, Any]], next_url: str | None = None) -> mock.Mock:+ response = mock.Mock()+ response.json.return_value = rows+ response.headers = {"Link": f'<{next_url}>; rel="next"'} if next_url else {}+ return response+++def _fetch_page_by_url(responses_by_url: dict[str, mock.Mock]):+ def fetch_page(url: str, *_args: Any, **_kwargs: Any) -> mock.Mock:+ for needle, response in responses_by_url.items():+ if needle in url:+ return response+ raise AssertionError(f"Unexpected URL requested: {url}")++ return fetch_page+++def _no_resume() -> mock.Mock:+ manager = mock.Mock()+ manager.can_resume.return_value = False+ return manager+++def _collect(endpoint: str, responses_by_url: dict[str, mock.Mock]) -> list[dict[str, Any]]:+ with mock.patch.object(github, "_fetch_page", side_effect=_fetch_page_by_url(responses_by_url)):+ tables = list(+ github.get_rows(+ personal_access_token="tok",+ repository="acme/widgets",+ endpoint=endpoint,+ logger=mock.Mock(),+ resumable_source_manager=_no_resume(),+ )+ )+ rows: list[dict[str, Any]] = []+ for table in tables:+ assert isinstance(table, pa.Table)+ rows.extend(table.to_pylist())+ return rows+++def test_teams_derives_org_from_repository_and_yields_rows() -> None:+ # The org must come from the repo owner (acme/widgets -> acme). A regression in that derivation+ # would request /orgs/widgets/... or a repo-scoped path and sync nothing.+ responses = {"/orgs/acme/teams": _response([{"id": 1, "slug": "core", "name": "Core"}])}++ with mock.patch.object(github, "_fetch_page", side_effect=_fetch_page_by_url(responses)) as fetch:+ tables = list(+ github.get_rows(+ personal_access_token="tok",+ repository="acme/widgets",+ endpoint="teams",+ logger=mock.Mock(),+ resumable_source_manager=_no_resume(),+ )+ )++ assert any("/orgs/acme/teams" in call.args[0] for call in fetch.call_args_list)+ assert [row["id"] for table in tables for row in table.to_pylist()] == [1]+++def test_team_members_fan_out_injects_parent_fields_and_keeps_composite_rows() -> None:+ # The same user (id 7) belongs to two teams. Each membership must become its own row carrying+ # its team's id/slug/name, so ["team_id", "id"] stays unique table-wide. If parent injection or+ # the per-team fan-out regressed, the user would collapse to one row or lose team context.+ # Member URLs first: substring matching would otherwise route them to the teams list, since+ # "/orgs/acme/teams" is a prefix of "/orgs/acme/teams/core/members".+ responses = {+ "/orgs/acme/teams/core/members": _response([{"id": 7, "login": "ada"}]),+ "/orgs/acme/teams/growth/members": _response([{"id": 7, "login": "ada"}]),+ "/orgs/acme/teams": _response(+ [+ {"id": 1, "slug": "core", "name": "Core"},+ {"id": 2, "slug": "growth", "name": "Growth"},+ ]+ ),+ }++ rows = _collect("team_members", responses)++ keyed = {(row["team_id"], row["id"]): row for row in rows}+ assert set(keyed) == {(1, 7), (2, 7)}+ assert keyed[(1, 7)]["team_slug"] == "core"+ assert keyed[(1, 7)]["team_name"] == "Core"+ assert keyed[(2, 7)]["team_slug"] == "growth"+ # The user's own fields pass through untouched.+ assert keyed[(1, 7)]["login"] == "ada"+++def test_team_members_fan_out_respects_per_parent_page_cap() -> None:+ # A team whose member list paginates forever must be bounded by max_pages_per_parent, or a+ # broken Link header would loop the child walk indefinitely.+ child_page = _response(+ [{"id": 7, "login": "ada"}], next_url="https://api.github.com/orgs/acme/teams/core/members?page=2"+ )++ def fetch_page(url: str, *_args: Any, **_kwargs: Any) -> mock.Mock:+ if "/orgs/acme/teams/core/members" in url:+ return child_page+ if "/orgs/acme/teams" in url:+ return _response([{"id": 1, "slug": "core", "name": "Core"}])+ raise AssertionError(f"Unexpected URL: {url}")++ with mock.patch.object(github.GITHUB_ENDPOINTS["team_members"], "max_pages_per_parent", 3):+ with mock.patch.object(github, "_fetch_page", side_effect=fetch_page) as fetch:+ list(+ github.get_rows(+ personal_access_token="tok",+ repository="acme/widgets",+ endpoint="team_members",+ logger=mock.Mock(),+ resumable_source_manager=_no_resume(),+ )+ )++ child_calls = [c for c in fetch.call_args_list if "/orgs/acme/teams/core/members" in c.args[0]]+ assert len(child_calls) == 3++[email protected]("status_code", [401, 403, 404])+def test_org_permission_probe_reports_missing_grant(status_code: int) -> None:+ # A denial on the org teams probe must surface the friendly reason naming the grant, so the+ # schema picker can flag the org tables instead of the whole source failing. The probe must ride+ # the gated egress transport (github_request) like the data plane, not a raw session.+ response = mock.Mock(status_code=status_code, headers={}, text="Forbidden")+ with mock.patch.object(github, "github_request", return_value=response) as request:+ reason = github.check_org_endpoint_permission("tok", "acme/widgets")++ assert reason is not None+ assert "Members: Read" in reason+ assert "read:org" in reason+ assert "/orgs/acme/teams" in request.call_args.args[1]+++ "request_behavior",+ [+ pytest.param({"return_value": mock.Mock(status_code=200, headers={}, text="")}, id="ok"),+ pytest.param({"return_value": mock.Mock(status_code=500, headers={}, text="")}, id="server-error"),+ pytest.param({"return_value": mock.Mock(status_code=429, headers={}, text="")}, id="secondary-rate-limit"),+ pytest.param(+ {"return_value": mock.Mock(status_code=403, headers={"x-ratelimit-remaining": "0"}, text="")},+ id="primary-rate-limit-403",+ ),+ pytest.param({"side_effect": github.GitHubEgressBudgetExhausted("deferring")}, id="egress-budget-shed"),+ pytest.param({"side_effect": requests.exceptions.ConnectionError()}, id="network-error"),+ ],+)+def test_org_permission_probe_treats_non_denial_as_reachable(request_behavior: dict[str, Any]) -> None:+ # Only a real denial is a missing scope; a success, rate limit (even a 403-shaped one), 5xx,+ # egress-budget shed, or network error must not be mislabeled as a permission problem (which+ # would wrongly block the org tables).+ with mock.patch.object(github, "github_request", **request_behavior):+ assert github.check_org_endpoint_permission("tok", "acme/widgets") is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.pyindex 2c4d79335a45..6e386230c75b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py@@ -32,7 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.github.git_is_empty_repository_response,_is_issue_not_pr,_is_older_than_cutoff,- _iter_jobs_for_run,+ _iter_child_for_parent,_iter_pages,_parse_next_url,_should_stop_desc,@@ -1366,7 +1366,7 @@ class TestIterPages:assert logger.warning.call_args.kwargs["max_pages"] == 2assert logger.warning.call_args.kwargs["run_id"] == 1001- def test_iter_jobs_for_run_builds_path_and_passes_cap(self) -> None:+ def test_iter_child_for_parent_builds_path_and_passes_cap(self) -> None:config = dataclasses.replace(GITHUB_ENDPOINTS["workflow_jobs"], max_pages_per_parent=1)responses = [_make_response(@@ -1379,7 +1379,7 @@ class TestIterPages:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get:mock_get.return_value.request.side_effect = responses- jobs = list(_iter_jobs_for_run("owner/repo", 1001, {}, logger, config))+ jobs = list(_iter_child_for_parent("owner/repo", 1001, {}, logger, config))assert [job["id"] for job in jobs] == [1]url = mock_get.return_value.request.call_args_list[0].args[1]