: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(warehouse_sources): restore merge commit SHA on merged pull requests (#95643)
posthog[bot]2e1fd8be0261
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 8288d97798b9..52d631d11878 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@@ -5,6 +5,7 @@ import asyncioimport dataclassesfrom collections.abc import AsyncIterator, Callable, Iteratorfrom datetime import UTC, date, datetime, timedelta+from itertools import batchedfrom typing import Any, Literal, Optionalfrom urllib.parse import urlencode, urlsplit@@ -60,10 +61,12 @@ FAN_OUT_PARENT_CAP_HITS = Counter(# for clock skew between the two before trusting it to skip a parent._RECONCILE_SKEW_ALLOWANCE = timedelta(minutes=5)-# GitHub's date-based REST API versions are sent in the X-GitHub-Api-Version header. The header is-# the only version-dependent part for the endpoints we sync — response shapes are compatible across-# these versions. Every caller — sync, credential validation, webhook management — passes the-# source's resolved pin; this constant is only the fallback for callers outside a source instance.+# GitHub's date-based REST API versions are sent in the X-GitHub-Api-Version header. Every caller —+# sync, credential validation, webhook management — passes the source's resolved pin; this constant+# is only the fallback for callers outside a source instance. Response shapes are not compatible+# across these versions: 2026-03-10 drops `merge_commit_sha` from the pull request object, which+# `_add_merge_commit_shas` puts back. Read a new version's breaking changes against the columns we+# land before adding it to supported_versions.GITHUB_DEFAULT_API_VERSION = "2022-11-28"# Managing repo webhooks needs the `admin:repo_hook` scope on a classic token, the "Repository@@ -136,6 +139,12 @@ class GithubRepositoryTooLargeError(Exception):pass+class GithubGraphqlUnavailableError(Exception):+ """The connection cannot read the requested GitHub GraphQL resource."""++ pass++@dataclasses.dataclassclass GithubResumeConfig:next_url: str@@ -894,21 +903,23 @@ def _pace_before_request(installation_id: str, logger: FilteringBoundLogger) ->time.sleep(pace)+# Transient failures every GitHub call retries on, REST and GraphQL alike.+_GITHUB_RETRYABLE_ERRORS = (+ GithubRetryableError,+ # Our egress limiter shed this deferrable call (BATCH); back off and re-acquire next attempt.+ GitHubEgressBudgetExhausted,+ GitHubRateLimitError,+ requests.ReadTimeout,+ requests.ConnectionError,+ # GitHub can break the connection mid-body on a chunked response, which surfaces as a+ # ChunkedEncodingError (a direct RequestException subclass, not a ConnectionError). It's+ # transient — a fresh request re-fetches the page — so retry it instead of failing the sync.+ requests.exceptions.ChunkedEncodingError,+)++@retry(- retry=retry_if_exception_type(- (- GithubRetryableError,- # Our egress limiter shed this deferrable page (BATCH); back off and re-acquire next attempt.- GitHubEgressBudgetExhausted,- GitHubRateLimitError,- requests.ReadTimeout,- requests.ConnectionError,- # GitHub can break the connection mid-body on a chunked response, which surfaces as a- # ChunkedEncodingError (a direct RequestException subclass, not a ConnectionError). It's- # transient — a fresh GET re-fetches the page — so retry it instead of failing the sync.- requests.exceptions.ChunkedEncodingError,- )- ),+ retry=retry_if_exception_type(_GITHUB_RETRYABLE_ERRORS),stop=stop_after_attempt(5),wait=_github_retry_wait,reraise=True,@@ -1296,6 +1307,230 @@ def _fan_out_get_rows(yield batcher.get_table()+# REST version 2026-03-10 stopped returning `merge_commit_sha` on the pull request object, so a+# merged pull request lands with no record of the commit it produced and every join onto that commit+# matches nothing. GraphQL still holds the value as PullRequest.mergeCommit.oid, so read it from+# there and put it back on the row, whatever version the source is pinned to.+GITHUB_GRAPHQL_URL = f"{GITHUB_BASE_URL}/graphql"++# One GraphQL call per REST page: the aliases cost one rate point each, far below the node cap.+_MERGE_COMMIT_BATCH_SIZE = GITHUB_ENDPOINTS["pull_requests"].page_size+_GRAPHQL_ACCESS_ERROR_TYPES = frozenset({"FORBIDDEN", "INSUFFICIENT_SCOPES", "NOT_FOUND", "UNAUTHENTICATED"})+++def _merge_commit_document(numbers: list[int]) -> str:+ # The numbers are ints read off the REST rows, so they cannot carry anything into the document;+ # owner and name travel as variables.+ aliases = " ".join(f"pr{number}: pullRequest(number: {number}) {{ mergeCommit {{ oid }} }}" for number in numbers)+ return f"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"+++def _graphql_error_type(error: Any) -> str | None:+ if not isinstance(error, dict):+ return None++ candidates = [error.get("type")]+ extensions = error.get("extensions")+ if isinstance(extensions, dict):+ candidates.extend((extensions.get("type"), extensions.get("code"), extensions.get("classification")))++ return next((candidate.upper() for candidate in candidates if isinstance(candidate, str)), None)+++def _has_only_graphql_access_errors(errors: Any) -> bool:+ return (+ isinstance(errors, list)+ and bool(errors)+ and all(_graphql_error_type(error) in _GRAPHQL_ACCESS_ERROR_TYPES for error in errors)+ )+++def _raise_if_graphql_rate_limited(response: requests.Response, body: dict[str, Any]) -> None:+ """Map GraphQL's own primary rate limit onto the error the REST path raises.++ GraphQL reports that limit as a 200 whose `errors` carry type RATE_LIMITED. `raise_if_github_rate_limited`+ cannot see that shape, because it only inspects 429 and 403 responses. Without this mapping the retry+ falls back to the plain backoff, which is capped at 30 seconds and so cannot outlast the hourly window+ the GraphQL limit resets on.+ """+ errors = body.get("errors")+ if not isinstance(errors, list):+ return+ if not any(isinstance(error, dict) and error.get("type") == "RATE_LIMITED" for error in errors):+ return++ try:+ reset_at: int | None = int(response.headers.get("x-ratelimit-reset", ""))+ except (ValueError, TypeError):+ reset_at = None+ # A response without a usable reset header still needs a wait longer than the plain backoff, for+ # the same reason.+ retry_after = max(1, reset_at - int(time.time())) if reset_at is not None else 60+ raise GitHubRateLimitError(+ f"Github GraphQL rate limit exceeded (resets at {reset_at})",+ reset_at=reset_at,+ retry_after=retry_after,+ )+++def _read_graphql_body(response: requests.Response) -> dict[str, Any]:+ try:+ body = response.json()+ except requests.exceptions.JSONDecodeError as error:+ raise GithubRetryableError("Github GraphQL returned invalid JSON") from error+ if not isinstance(body, dict):+ raise GithubRetryableError("Github GraphQL returned an invalid response body")+ return body+++def _merge_commit_sha(pull_requests: dict[str, Any], number: int) -> str | None:+ pull_request = pull_requests.get(f"pr{number}")+ if pull_request is None:+ return None+ if not isinstance(pull_request, dict):+ raise GithubRetryableError("Github GraphQL returned an invalid pull request")++ merge_commit = pull_request.get("mergeCommit")+ if merge_commit is None:+ return None+ if not isinstance(merge_commit, dict):+ raise GithubRetryableError("Github GraphQL returned an invalid merge commit")++ oid = merge_commit.get("oid")+ if not isinstance(oid, str):+ raise GithubRetryableError("Github GraphQL returned an invalid merge commit")+ return oid+++def _parse_merge_commit_shas(+ body: dict[str, Any], numbers: list[int], repository: str, logger: FilteringBoundLogger+) -> dict[int, str]:+ errors = body.get("errors")+ data = body.get("data")+ pull_requests = data.get("repository") if isinstance(data, dict) else None+ if not isinstance(pull_requests, dict):+ if _has_only_graphql_access_errors(errors):+ raise GithubGraphqlUnavailableError(f"Github GraphQL returned no repository data: errors={errors}")+ raise GithubRetryableError(f"Github GraphQL returned no repository data: errors={errors}")++ if errors:+ if not _has_only_graphql_access_errors(errors):+ raise GithubRetryableError(f"Github GraphQL returned unresolved errors: errors={errors}")+ logger.warning(+ "Github: GraphQL denied part of the merge commit batch, so those pull requests keep "+ f"an empty merge_commit_sha: repository={repository}, errors={errors}"+ )++ return {number: sha for number in numbers if (sha := _merge_commit_sha(pull_requests, number)) is not None}+++@retry(+ retry=retry_if_exception_type(_GITHUB_RETRYABLE_ERRORS),+ stop=stop_after_attempt(5),+ wait=_github_retry_wait,+ reraise=True,+)+def _fetch_merge_commit_shas(+ repository: str,+ numbers: list[int],+ access_token: str,+ logger: FilteringBoundLogger,+ egress_identity: GithubEgressIdentity | None = None,+ api_version: str = GITHUB_DEFAULT_API_VERSION,+) -> dict[int, str]:+ """Ask GraphQL for the merge commit of each pull request number, through the gated and recorded+ transport, budget pacing, and retry policy the REST walk uses. Returns only the numbers GraphQL+ answered for: a partial GraphQL error leaves its own alias null while the rest of the batch+ still resolves."""+ installation_id = egress_identity.installation_id if egress_identity is not None else None+ if installation_id is not None:+ _pace_before_request(installation_id, logger)++ owner, _, name = repository.partition("/")+ response = github_request(+ "POST",+ GITHUB_GRAPHQL_URL,+ source="warehouse",+ endpoint="/graphql",+ headers=_get_headers(access_token, api_version=api_version),+ installation_id=installation_id,+ priority=Priority.BATCH,+ timeout=60,+ session=make_tracked_session(retry=_NO_ADAPTER_RETRY),+ json={+ "query": _merge_commit_document(numbers),+ "variables": {"owner": owner, "name": name},+ },+ )++ if response.status_code >= 500:+ raise GithubRetryableError(f"Github GraphQL error (retryable): status={response.status_code}")+ raise_if_github_rate_limited(response)+ if response.status_code in {401, 403, 404}:+ raise GithubGraphqlUnavailableError(f"Github GraphQL access failed: status={response.status_code}")+ response.raise_for_status()++ body = _read_graphql_body(response)+ _raise_if_graphql_rate_limited(response, body)+ return _parse_merge_commit_shas(body, numbers, repository, logger)+++def _add_merge_commit_shas(+ rows: list[dict[str, Any]],+ repository: str,+ access_token: str,+ logger: FilteringBoundLogger,+ egress_identity: GithubEgressIdentity | None = None,+ api_version: str = GITHUB_DEFAULT_API_VERSION,+) -> bool:+ """Fill in `merge_commit_sha` on the merged pull requests of one page, in place. False says+ GraphQL is closed to this connection, so the caller can stop asking for the rest of the walk.++ A permanent denial does not fail the sync: the rest of the pull request row is good, and failing+ would lose the whole table on every run for a connection that can never answer. Other failures+ abort the walk so its incremental watermark cannot skip rows that still need enrichment."""+ # Land the column whatever happens. The curated engineering analytics views select+ # `merge_commit_sha` by name, so a page that resolves nothing must still carry an empty column+ # rather than drop it from the table and break the read.+ for row in rows:+ row.setdefault("merge_commit_sha", None)++ pending: dict[int, dict[str, Any]] = {+ row["number"]: row+ for row in rows+ if row.get("merged_at") and not row.get("merge_commit_sha") and isinstance(row.get("number"), int)+ }+ if not pending:+ return True++ for batch in batched(pending, _MERGE_COMMIT_BATCH_SIZE, strict=False):+ try:+ shas = _fetch_merge_commit_shas(+ repository,+ list(batch),+ access_token,+ logger,+ egress_identity=egress_identity,+ api_version=api_version,+ )+ except GithubGraphqlUnavailableError as error:+ logger.warning(+ "Github: GraphQL is unavailable, so merged pull requests keep an empty merge_commit_sha: "+ f"repository={repository}, error={error}"+ )+ return False+ for number, sha in shas.items():+ pending[number]["merge_commit_sha"] = sha++ missing = sum(1 for row in pending.values() if not row.get("merge_commit_sha"))+ if missing:+ logger.warning(+ "Github: GraphQL holds no merge commit for some merged pull requests: "+ f"repository={repository}, missing={missing}"+ )+ return True++def get_rows(personal_access_token: str,repository: str,@@ -1343,6 +1578,9 @@ def get_rows(item_filter = _get_item_filter(endpoint)item_mapper = _get_item_mapper(endpoint)body_transform = _get_body_transform(endpoint)+ # One unreachable GraphQL call turns the merge commit enrichment off for the rest of the walk,+ # rather than paying its retries again on every page.+ enrich_merge_commits = endpoint == "pull_requests"initial_params = _build_initial_params(config, endpoint, should_use_incremental_field, db_incremental_field_last_value, incremental_field@@ -1404,6 +1642,16 @@ def get_rows(if not isinstance(data, list) or not data:break+ if enrich_merge_commits:+ enrich_merge_commits = _add_merge_commit_shas(+ data,+ repository,+ personal_access_token,+ logger,+ egress_identity=egress_identity,+ api_version=api_version,+ )+next_url = _parse_next_url(response.headers.get("Link", ""))stop_after_this_page = _should_stop_desc(data, actual_sort_mode, stop_field, stop_cutoff)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.pyindex f1412e5a2346..47ebd0519d2b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py@@ -1,14 +1,18 @@+import reimport jsonfrom datetime import UTC, datetime, timedeltafrom typing import Anyimport pytest+import time_machinefrom unittest import mockimport pyarrow as paimport requestsfrom parameterized import parameterized+from posthog.egress.github.transport import GitHubRateLimitError+from products.warehouse_sources.backend.temporal.data_imports.sources.github import githubfrom products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import GITHUB_ENDPOINTS@@ -456,3 +460,167 @@ class TestCommitFanOut:assert rows == [{"id": 21, "name": "lint", "started_at": "2026-01-20T10:00:00Z"}]# filter=all is what surfaces re-runs rather than only the latest run per check name.assert any("filter=all" in call for call in calls)+++class TestMergeCommitSha:+ @staticmethod+ def _pull_request(number: int, merged: bool, **extra: Any) -> dict[str, Any]:+ # The 2026-03-10 pull request object: no merge_commit_sha key at all.+ return {+ "id": 500 + number,+ "number": number,+ "state": "closed" if merged else "open",+ "created_at": "2026-09-01T09:00:00Z",+ "updated_at": "2026-09-01T10:00:00Z",+ "merged_at": "2026-09-01T10:00:00Z" if merged else None,+ **extra,+ }++ def test_merged_pull_requests_get_their_merge_commit_from_graphql(self) -> None:+ graphql = mock.Mock()+ graphql.status_code = 200+ graphql.headers = {}+ graphql.json.return_value = {"data": {"repository": {"pr7": {"mergeCommit": {"oid": "sha-seven"}}}}}+ page = _response(+ [+ self._pull_request(7, merged=True),+ self._pull_request(8, merged=False),+ self._pull_request(9, merged=True, merge_commit_sha="sha-nine"),+ ]+ )++ with mock.patch.object(github, "github_request", return_value=graphql) as github_request:+ rows, _calls = _run("pull_requests", {"api.github.com": page}, api_version="2026-03-10")++ assert [row["merge_commit_sha"] for row in rows] == ["sha-seven", None, "sha-nine"]+ assert github_request.call_args.kwargs["headers"]["X-GitHub-Api-Version"] == "2026-03-10"+ # Only the merged row that arrived without a SHA is asked for: an open pull request has no+ # merge commit, and a row that already carries one costs nothing.+ github_request.assert_called_once()+ payload = github_request.call_args.kwargs["json"]+ assert re.findall(r"pr(\d+): pullRequest", payload["query"]) == ["7"]+ assert payload["variables"] == {"owner": "acme", "name": "widgets"}++ def test_a_permanent_alias_error_costs_only_its_own_pull_request(self) -> None:+ graphql = mock.Mock()+ graphql.status_code = 200+ graphql.headers = {}+ graphql.json.return_value = {+ "data": {"repository": {"pr7": {"mergeCommit": {"oid": "sha-seven"}}, "pr8": None}},+ "errors": [+ {"type": "NOT_FOUND", "message": "Could not resolve pull request", "path": ["repository", "pr8"]}+ ],+ }+ page = _response([self._pull_request(7, merged=True), self._pull_request(8, merged=True)])++ with mock.patch.object(github, "github_request", return_value=graphql):+ rows, _calls = _run("pull_requests", {"api.github.com": page})++ assert [row["merge_commit_sha"] for row in rows] == ["sha-seven", None]++ def test_an_unknown_alias_error_fails_the_walk(self) -> None:+ graphql = mock.Mock()+ graphql.status_code = 200+ graphql.headers = {}+ graphql.json.return_value = {+ "data": {"repository": {"pr7": None}},+ "errors": [{"message": "Something went wrong", "path": ["repository", "pr7"]}],+ }+ page = _response([self._pull_request(7, merged=True)])++ with (+ mock.patch.object(github, "github_request", return_value=graphql) as github_request,+ mock.patch.object(github, "_github_backoff_wait", return_value=0.0),+ pytest.raises(github.GithubRetryableError),+ ):+ _run("pull_requests", {"api.github.com": page})++ assert github_request.call_count == 5++ @parameterized.expand([("advertised reset", 900, 900), ("no reset header", None, 60)])+ def test_graphql_rate_limit_carries_a_wait_that_outlasts_the_window(+ self, _name: str, reset_in: int | None, expected_retry_after: int+ ) -> None:+ now = datetime(2026, 9, 1, 10, 0, 0, tzinfo=UTC)+ rate_limited = mock.Mock()+ rate_limited.status_code = 200+ rate_limited.headers = (+ {"x-ratelimit-reset": str(int((now + timedelta(seconds=reset_in)).timestamp()))}+ if reset_in is not None+ else {}+ )+ rate_limited.json.return_value = {+ "data": None,+ "errors": [{"type": "RATE_LIMITED", "message": "API rate limit exceeded"}],+ }++ with (+ time_machine.travel(now, tick=False),+ mock.patch.object(github, "github_request", return_value=rate_limited),+ ):+ with pytest.raises(GitHubRateLimitError) as raised:+ # Called past the retry decorator, so the assertion does not wait out the reset it+ # is asserting on.+ github._fetch_merge_commit_shas.__wrapped__( # type: ignore[attr-defined]+ "acme/widgets", [7], "tok", mock.Mock()+ )++ # A GithubRetryableError here would fall to the backoff capped at 30s, which the hourly+ # GraphQL window outlasts.+ assert raised.value.retry_after == expected_retry_after++ def test_pull_requests_still_sync_when_graphql_is_closed_to_the_connection(self) -> None:+ # A token with no GraphQL grant gets a 200 with null data on every run, so failing the sync+ # would lose the whole table forever. The rest of the row is good: keep it.+ denied = mock.Mock()+ denied.status_code = 200+ denied.headers = {}+ denied.json.return_value = {"data": None, "errors": [{"type": "FORBIDDEN"}]}+ page = _response([self._pull_request(7, merged=True)])++ with mock.patch.object(github, "github_request", return_value=denied) as github_request:+ rows, _calls = _run("pull_requests", {"api.github.com": page})++ # Indexed, not `.get`: the curated views select the column by name, so it has to land empty+ # rather than go missing from the table.+ assert [(row["number"], row["merge_commit_sha"]) for row in rows] == [(7, None)]+ # Permanent, so it is not retried either.+ github_request.assert_called_once()++ def test_graphql_is_disabled_after_a_permanent_failure(self) -> None:+ denied = mock.Mock()+ denied.status_code = 200+ denied.headers = {}+ denied.json.return_value = {"data": None, "errors": [{"type": "FORBIDDEN"}]}+ second_page_url = "https://api.github.com/repos/acme/widgets/pulls?page=2"+ first_page = _response([self._pull_request(7, merged=True)], next_url=second_page_url)+ second_page = _response([self._pull_request(6, merged=True)])++ with mock.patch.object(github, "github_request", return_value=denied) as github_request:+ rows, calls = _run("pull_requests", {second_page_url: second_page, "api.github.com": first_page})++ assert [(row["number"], row["merge_commit_sha"]) for row in rows] == [(7, None), (6, None)]+ assert len(calls) == 2+ assert calls[-1] == second_page_url+ github_request.assert_called_once()++ def test_an_unexpected_enrichment_failure_fails_the_walk(self) -> None:+ page = _response([self._pull_request(7, merged=True)])++ with (+ mock.patch.object(github, "_fetch_merge_commit_shas", side_effect=KeyError("mergeCommit")),+ pytest.raises(KeyError, match="mergeCommit"),+ ):+ _run("pull_requests", {"api.github.com": page})++ def test_a_transient_graphql_failure_fails_the_walk(self) -> None:+ # Merged pull requests rarely move `updated_at` again, and the newest-first watermark+ # advances on any walk that completes. Syncing these rows without their SHA would strand+ # them until a full refresh, so the walk fails and the next sync reads them again.+ page = _response([self._pull_request(7, merged=True)])+ with (+ mock.patch.object(github, "github_request", side_effect=requests.ConnectionError("boom")),+ mock.patch.object(github, "_github_backoff_wait", return_value=0.0),+ ):+ with pytest.raises(requests.ConnectionError):+ _run("pull_requests", {"api.github.com": page})