Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(github): sync empty repositories as zero rows instead of failing (#63719)

Tom Owers3e4b8494ff9e
diff --git a/posthog/temporal/data_imports/sources/github/github.py b/posthog/temporal/data_imports/sources/github/github.py
index 0ba1a4a5dece..b5fd5533caf0 100644
--- a/posthog/temporal/data_imports/sources/github/github.py
+++ b/posthog/temporal/data_imports/sources/github/github.py
@@ -23,6 +23,14 @@ class GithubRetryableError(Exception):
pass
+class GithubEmptyRepositoryError(Exception):
+ """GitHub returns 409 "Git Repository is empty." on the commits endpoint for
+ a freshly created repo with no commits. `fetch_page` raises this so the
+ caller can sync zero rows without re-parsing the response body."""
+
+ pass
+
+
@dataclasses.dataclass
class GithubResumeConfig:
next_url: str
@@ -136,6 +144,22 @@ def _parse_next_url(link_header: str) -> str | None:
return None
+def _is_empty_repository_response(response: requests.Response) -> bool:
+ """GitHub returns 409 Conflict on the commits endpoint when the repository
+ has no commits yet (e.g. a freshly created, empty repo), with a stable
+ "Git Repository is empty." message in the body. This is a valid, benign
+ state — not a credential or config problem — so callers sync zero rows
+ rather than raising (which otherwise retries the activity indefinitely)."""
+ if response.status_code != 409:
+ return False
+ try:
+ body = response.json()
+ message = body.get("message", "") if isinstance(body, dict) else ""
+ except (ValueError, TypeError):
+ message = response.text or ""
+ return isinstance(message, str) and "repository is empty" in message.lower()
+
+
def _as_utc(dt: datetime) -> datetime:
"""Treat naive datetimes as UTC so tz-aware values (GitHub returns ISO 8601
with `Z`) can be safely compared against naive cutoffs from the DB."""
@@ -315,6 +339,12 @@ def get_rows(
if response.status_code == 429 or response.status_code >= 500:
raise GithubRetryableError(f"Github API error (retryable): status={response.status_code}, url={page_url}")
+ # An empty repository (no commits yet) returns 409 on the commits
+ # endpoint. Signal it so the loop can sync zero rows without raising
+ # a hard error (which would otherwise retry the activity indefinitely).
+ if _is_empty_repository_response(response):
+ raise GithubEmptyRepositoryError()
+
if not response.ok:
logger.error(f"Github API error: status={response.status_code}, body={response.text}, url={page_url}")
response.raise_for_status()
@@ -322,7 +352,11 @@ def get_rows(
return response
while True:
- response = fetch_page(url)
+ try:
+ response = fetch_page(url)
+ except GithubEmptyRepositoryError:
+ logger.debug(f"Github: repository has no commits (empty repository), syncing zero rows: url={url}")
+ break
data = response.json()
# Most GitHub list endpoints return a JSON array at the top level,
diff --git a/posthog/temporal/tests/data_imports/github/test_github_source.py b/posthog/temporal/tests/data_imports/github/test_github_source.py
index 91d9ca3cd9fb..5965150395bb 100644
--- a/posthog/temporal/tests/data_imports/github/test_github_source.py
+++ b/posthog/temporal/tests/data_imports/github/test_github_source.py
@@ -1,6 +1,7 @@
from datetime import UTC, date, datetime
from typing import Any
+import pytest
from unittest import mock
import requests
@@ -13,6 +14,7 @@ from posthog.temporal.data_imports.sources.github.github import (
_flatten_commit,
_flatten_stargazer,
_format_incremental_value,
+ _is_empty_repository_response,
_is_issue_not_pr,
_is_older_than_cutoff,
_parse_next_url,
@@ -372,6 +374,21 @@ class TestIsIssueNotPr:
assert _is_issue_not_pr(item) == expected
+class TestIsEmptyRepositoryResponse:
+ @parameterized.expand(
+ [
+ ("conflict_empty_repo", 409, {"message": "Git Repository is empty."}, True),
+ ("conflict_empty_repo_lowercase", 409, {"message": "git repository is empty"}, True),
+ ("conflict_other_message", 409, {"message": "Merge conflict"}, False),
+ ("conflict_no_body", 409, [], False),
+ ("not_conflict_status", 404, {"message": "Git Repository is empty."}, False),
+ ("ok_status", 200, [{"sha": "abc"}], False),
+ ]
+ )
+ def test_detects_empty_repository(self, _name: str, status: int, body: Any, expected: bool) -> None:
+ assert _is_empty_repository_response(_make_response(status=status, body=body)) is expected
+
+
class TestValidateCredentials:
def test_valid_credentials(self) -> None:
with mock.patch("posthog.temporal.data_imports.sources.github.github.make_tracked_session") as mock_get:
@@ -618,6 +635,63 @@ class TestGetRowsResume:
saved = manager.save_state.call_args.args[0]
assert saved.next_url == mock_get.return_value.get.call_args_list[0].args[0]
+ def test_empty_repository_409_syncs_zero_rows(self) -> None:
+ """An empty repo returns 409 "Git Repository is empty." on the commits
+ endpoint. That's a benign state, not an error — get_rows must yield zero
+ rows and not raise (otherwise the activity retries indefinitely)."""
+ manager = _make_manager(can_resume=False)
+ empty_repo_409 = _make_response(status=409, body={"message": "Git Repository is empty."})
+
+ with (
+ self._patch_batcher(),
+ mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ ) as mock_get,
+ ):
+ mock_get.return_value.get.side_effect = [empty_repo_409]
+ rows = list(
+ get_rows(
+ personal_access_token="tok",
+ repository="owner/repo",
+ endpoint="commits",
+ logger=mock.Mock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=False,
+ )
+ )
+
+ assert rows == []
+ manager.save_state.assert_not_called()
+
+ def test_non_empty_repo_409_still_raises(self) -> None:
+ """A 409 that is NOT the empty-repository case must still surface as an
+ error rather than being silently swallowed as zero rows."""
+ manager = _make_manager(can_resume=False)
+ other_409 = _make_response(status=409, body={"message": "Merge conflict"})
+ other_409.text = '{"message": "Merge conflict"}'
+ other_409.raise_for_status.side_effect = requests.HTTPError(
+ "409 Client Error: Conflict for url: ...", response=other_409
+ )
+
+ with (
+ self._patch_batcher(),
+ mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ ) as mock_get,
+ ):
+ mock_get.return_value.get.side_effect = [other_409]
+ with pytest.raises(requests.HTTPError):
+ list(
+ get_rows(
+ personal_access_token="tok",
+ repository="owner/repo",
+ endpoint="commits",
+ logger=mock.Mock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=False,
+ )
+ )
+
def test_workflow_runs_envelope_is_unwrapped(self) -> None:
manager = _make_manager(can_resume=False)
envelope = {"total_count": 1, "workflow_runs": [{"id": 1001, "created_at": "2026-01-20T10:00:00Z"}]}