:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(github): skip org-scoped 404s instead of failing the sync (#69864)
Tom Owersc459877552bf
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 4fa01cf196c5..cc1d888e7cb1 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@@ -60,6 +60,16 @@ class GithubEmptyRepositoryError(Exception):pass+class GithubOrgNotFoundError(Exception):+ """GitHub returns 404 on the org-scoped endpoints (``/orgs/{org}/teams`` and the members+ fan-out) when the repository owner is a personal account rather than an organization, or the+ token has no org access. There is nothing to sync in that case, so ``_fetch_page`` raises this on+ org-scoped endpoints and the caller syncs zero rows — a benign skip, not a "repository not found"+ that should fail the schema."""++ pass++@dataclasses.dataclassclass GithubResumeConfig:next_url: str@@ -460,6 +470,7 @@ def _fetch_page(headers: dict[str, str],logger: FilteringBoundLogger,egress_identity: GithubEgressIdentity | None = None,+ skip_on_not_found: bool = False,) -> requests.Response:# One gated + recorded GET through the shared egress client. The App path bills the shared# per-installation budget at BATCH (deferrable bulk); the PAT path (installation_id None) skips the@@ -493,6 +504,12 @@ def _fetch_page(if _is_empty_repository_response(response):raise GithubEmptyRepositoryError()+ # An org-scoped endpoint 404s when the repo owner is a user (no org) or the token lacks org+ # access. Signal it so the caller syncs zero rows rather than failing the schema — a benign skip+ # like an empty repository, not a real "repository not found".+ if skip_on_not_found and response.status_code == 404:+ raise GithubOrgNotFoundError()+if not response.ok:logger.error(f"Github API error: status={response.status_code}, body={response.text}, url={page_url}")response.raise_for_status()@@ -508,6 +525,7 @@ def _iter_pages(max_pages: int | None = None,page_cap_context: dict[str, Any] | None = None,egress_identity: GithubEgressIdentity | None = None,+ skip_on_not_found: bool = False,) -> Iterator[tuple[list[dict[str, Any]], str]]:"""Yield (items, page_url) for each page of a paginated GitHub list,unwrapping the envelope and following the Link header. Stops at ``max_pages``,@@ -515,7 +533,11 @@ def _iter_pages(envelope body simply ends iteration — there is nothing to truncate."""page_count = 0while True:- response = _fetch_page(url, headers, logger, egress_identity)+ try:+ response = _fetch_page(url, headers, logger, egress_identity, skip_on_not_found=skip_on_not_found)+ except GithubOrgNotFoundError:+ logger.debug(f"Github: org-scoped endpoint not found, syncing zero rows: url={url}")+ returndata = response.json()if response_data_path and isinstance(data, dict):data = data.get(response_data_path) or []@@ -594,6 +616,10 @@ def _fan_out_get_rows(child_config = GITHUB_ENDPOINTS[endpoint]assert child_config.fan_out_parent is not None # guarded by the get_rows dispatchparent_config = GITHUB_ENDPOINTS[child_config.fan_out_parent]+ # team_members fans out from the org-scoped teams parent, which 404s for a user-owned repo (no+ # org). Skip only that parent walk — a 404 on a specific team's members is not this benign case+ # and should still surface.+ parent_org_scoped = child_config.fan_out_parent in ORG_SCOPED_ENDPOINTSheaders = _get_headers(personal_access_token, endpoint)batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)@@ -625,7 +651,12 @@ def _fan_out_get_rows(parent_url = _build_initial_url(parent_config, repository, {"per_page": parent_config.page_size})for parents, page_url in _iter_pages(- parent_url, headers, parent_config.response_data_path, logger, egress_identity=egress_identity+ parent_url,+ headers,+ parent_config.response_data_path,+ logger,+ egress_identity=egress_identity,+ skip_on_not_found=parent_org_scoped,):stop_after_this_page = _should_stop_desc(parents, "desc", parent_cursor_field, parent_cutoff)@@ -711,12 +742,16 @@ def get_rows(else:url = _build_initial_url(config, repository, initial_params)+ org_scoped = endpoint in ORG_SCOPED_ENDPOINTSwhile True:try:- response = _fetch_page(url, headers, logger, egress_identity)+ response = _fetch_page(url, headers, logger, egress_identity, skip_on_not_found=org_scoped)except GithubEmptyRepositoryError:logger.debug(f"Github: repository has no commits (empty repository), syncing zero rows: url={url}")break+ except GithubOrgNotFoundError:+ logger.debug(f"Github: no accessible org teams for {endpoint}, syncing zero rows: url={url}")+ breakdata = response.json()# Most GitHub list endpoints return a JSON array at the top level,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.pyindex 906636336ed7..f6b128775720 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py@@ -29,6 +29,39 @@ def _instant_backoff():yield+def _not_found_response() -> mock.Mock:+ response = mock.Mock(spec=requests.Response)+ response.status_code = 404+ response.ok = False+ response.headers = {}+ response.text = "Not Found"+ response.request = None+ response.raise_for_status.side_effect = requests.exceptions.HTTPError(+ "404 Client Error: Not Found for url", response=response+ )+ return response+++ "skip_on_not_found,expected_exc",+ [+ (True, github.GithubOrgNotFoundError),+ (False, requests.exceptions.HTTPError),+ ],+)+def test_fetch_page_404_skips_only_for_org_scoped_endpoints(skip_on_not_found, expected_exc):+ # An org-scoped endpoint (a user-owned repo has no org, so /orgs/{owner}/teams 404s) treats a 404+ # as a benign skip; a repo-scoped one keeps it fatal so a genuinely missing repo still fails loud.+ session = mock.Mock()+ session.request.return_value = _not_found_response()++ with mock.patch.object(github, "make_tracked_session", return_value=session):+ with pytest.raises(expected_exc):+ github._fetch_page(+ "https://api.github.com/orgs/acme/teams", {}, mock.Mock(), skip_on_not_found=skip_on_not_found+ )++def test_fetch_page_retries_chunked_encoding_error():session = mock.Mock()session.request.side_effect = [requests.exceptions.ChunkedEncodingError("Connection broken"), _ok_response()]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.pyindex 3e7b5f051b99..a04d446450d7 100644--- 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.py@@ -32,6 +32,74 @@ def _no_resume() -> mock.Mock:return manager+def _not_found_response() -> mock.Mock:+ response = mock.Mock(spec=requests.Response)+ response.status_code = 404+ response.ok = False+ response.headers = {}+ response.text = "Not Found"+ response.request = None+ response.raise_for_status.side_effect = requests.exceptions.HTTPError(+ "404 Client Error: Not Found for url", response=response+ )+ return response+++ "endpoint,expect_raise",+ [+ # Org-scoped: a 404 on /orgs/{owner}/teams (user-owned repo, or no org access) must sync zero+ # rows, not fail the schema. teams walks it directly; team_members hits it via its fan-out parent.+ ("teams", False),+ ("team_members", False),+ # Repo-scoped: a 404 is a genuinely missing/inaccessible repo and must stay fatal.+ ("issues", True),+ ],+)+def test_org_scoped_404_syncs_zero_rows_while_repo_scoped_404_stays_fatal(endpoint: str, expect_raise: bool) -> None:+ session = mock.Mock()+ session.request.return_value = _not_found_response()++ with mock.patch.object(github, "make_tracked_session", return_value=session):+ rows = github.get_rows(+ personal_access_token="tok",+ repository="acme/widgets",+ endpoint=endpoint,+ logger=mock.Mock(),+ resumable_source_manager=_no_resume(),+ )+ if expect_raise:+ with pytest.raises(requests.exceptions.HTTPError):+ list(rows)+ else:+ assert list(rows) == []+++def test_team_members_child_404_stays_fatal_after_parent_listed() -> None:+ # The org-scoped skip covers only the parent teams walk (user-owned repo, no org). Once the org+ # resolves and a team is listed, a 404 on that team's members is unexpected and must surface, not+ # silently drop the team's members.+ def fetch_page(url: str, *_args: Any, **kwargs: Any) -> mock.Mock:+ if "/orgs/acme/teams/core/members" in url:+ assert kwargs.get("skip_on_not_found") is False+ raise requests.exceptions.HTTPError("404 Client Error: Not Found for url", response=requests.Response())+ 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, "_fetch_page", side_effect=fetch_page):+ with pytest.raises(requests.exceptions.HTTPError):+ list(+ github.get_rows(+ personal_access_token="tok",+ repository="acme/widgets",+ endpoint="team_members",+ logger=mock.Mock(),+ resumable_source_manager=_no_resume(),+ )+ )++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(