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.

feat(data-warehouse): add workflow_runs endpoint to GitHub source (#58890)

Raúl Negrón-Otero5230f7c13885
diff --git a/posthog/temporal/data_imports/sources/github/github.py b/posthog/temporal/data_imports/sources/github/github.py
index 39eb5391acc5..0ba1a4a5dece 100644
--- a/posthog/temporal/data_imports/sources/github/github.py
+++ b/posthog/temporal/data_imports/sources/github/github.py
@@ -2,7 +2,7 @@ import re
import dataclasses
from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime
-from typing import Any, Optional
+from typing import Any, Literal, Optional
from urllib.parse import urlencode
import requests
@@ -44,6 +44,16 @@ def _build_initial_params(
db_incremental_field_last_value: Any,
incremental_field: str | None,
) -> dict[str, Any]:
+ # workflow_runs has a different param surface: it accepts neither
+ # state/sort/direction nor `since`, and always returns newest-first by
+ # created_at. We intentionally send no time filter either — its `created`
+ # filter would cap the result set to GitHub's 1,000-result search limit and
+ # silently drop rows on busy repos. Incremental sync is handled instead by
+ # paginating newest-first and stopping at the cursor (see get_rows), so the
+ # request stays a plain paged read regardless of incremental state.
+ if endpoint == "workflow_runs":
+ return {"per_page": config.page_size}
+
params: dict[str, Any] = {
"per_page": config.page_size,
"state": "all",
@@ -79,6 +89,29 @@ def _build_initial_url(config: GithubEndpointConfig, repository: str, params: di
return f"{GITHUB_BASE_URL}{path}?{urlencode(params)}"
+def _resolve_sort_mode(
+ config: GithubEndpointConfig,
+ endpoint: str,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Literal["asc", "desc"]:
+ """The order rows are actually emitted in. SourceResponse.sort_mode must
+ match this, otherwise the pipeline persists the cursor watermark assuming
+ the wrong direction (e.g. advancing past unread older rows).
+
+ Most endpoints emit asc on the first sync / full refresh (stable offset
+ pagination via sort=created&direction=asc) and only flip to their
+ configured sort once a cutoff exists. workflow_runs is different: it ignores
+ sort/direction and always returns newest-first, so it emits desc on every
+ sync — including the first.
+ """
+ if endpoint == "workflow_runs":
+ return config.sort_mode
+ if should_use_incremental_field and db_incremental_field_last_value:
+ return config.sort_mode
+ return "asc"
+
+
def _get_headers(access_token: str, endpoint: str) -> dict[str, str]:
headers = {
"Authorization": f"Bearer {access_token}",
@@ -246,9 +279,9 @@ def get_rows(
headers = _get_headers(personal_access_token, endpoint)
batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
- # Only use the endpoint's configured sort mode when we actually have a cutoff;
- # otherwise the full refresh uses asc for stable offset pagination.
- actual_sort_mode = config.sort_mode if should_use_incremental_field and db_incremental_field_last_value else "asc"
+ actual_sort_mode = _resolve_sort_mode(
+ config, endpoint, should_use_incremental_field, db_incremental_field_last_value
+ )
stop_field: str | None = None
stop_cutoff: Any = None
@@ -292,7 +325,10 @@ def get_rows(
response = fetch_page(url)
data = response.json()
- # GitHub list endpoints return a JSON array at the top level.
+ # Most GitHub list endpoints return a JSON array at the top level,
+ # but some (e.g. /actions/runs) wrap results in {"<resource>": [...]}.
+ if config.response_data_path and isinstance(data, dict):
+ data = data.get(config.response_data_path, [])
if not isinstance(data, list) or not data:
break
@@ -343,8 +379,8 @@ def github_source(
) -> SourceResponse:
endpoint_config = GITHUB_ENDPOINTS[endpoint]
- actual_sort_mode = (
- endpoint_config.sort_mode if should_use_incremental_field and db_incremental_field_last_value else "asc"
+ actual_sort_mode = _resolve_sort_mode(
+ endpoint_config, endpoint, should_use_incremental_field, db_incremental_field_last_value
)
return SourceResponse(
diff --git a/posthog/temporal/data_imports/sources/github/settings.py b/posthog/temporal/data_imports/sources/github/settings.py
index 288af39aa362..48d9d1eb9a10 100644
--- a/posthog/temporal/data_imports/sources/github/settings.py
+++ b/posthog/temporal/data_imports/sources/github/settings.py
@@ -14,6 +14,10 @@ class GithubEndpointConfig:
page_size: int = 100 # GitHub default, max is 100
sort_mode: Literal["asc", "desc"] = "asc"
primary_key: str = "id" # Primary key for upsert operations
+ # Body key to drill into when the API wraps results in an envelope
+ # (e.g. /actions/runs returns {"total_count": N, "workflow_runs": [...]}).
+ # None means the response body is itself the list.
+ response_data_path: Optional[str] = None
GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {
@@ -86,6 +90,35 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {
partition_key="created_at",
incremental_fields=[], # No incremental support
),
+ "workflow_runs": GithubEndpointConfig(
+ name="workflow_runs",
+ path="/repos/{repository}/actions/runs",
+ partition_key="created_at",
+ incremental_fields=[
+ # The list endpoint returns newest-first by created_at and exposes
+ # no updated_at filter/sort, so created_at is the only viable
+ # cursor. We sync incrementally by paginating newest-first and
+ # stopping once we cross below the cursor (see github.py), mirroring
+ # how pull_requests/commits scroll desc. We deliberately do NOT send
+ # the server-side `created` filter: GitHub caps any filtered search
+ # to 1,000 results, which would silently truncate busy repos.
+ #
+ # created_at is immutable, but a run's status/conclusion mutate
+ # after it first appears. The created_at cursor only refreshes runs
+ # at/above the watermark, so a run that completes well after newer
+ # runs landed won't be picked up here — that's handled by the
+ # workflow_run webhook (followup), not by re-scanning history.
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ default_incremental_field="created_at",
+ sort_mode="desc", # API always returns newest-first; sort/direction are ignored
+ response_data_path="workflow_runs",
+ ),
}
ENDPOINTS = tuple(GITHUB_ENDPOINTS.keys())
diff --git a/posthog/temporal/tests/data_imports/github/conftest.py b/posthog/temporal/tests/data_imports/github/conftest.py
index 285705c73455..8bc2fea8abf4 100644
--- a/posthog/temporal/tests/data_imports/github/conftest.py
+++ b/posthog/temporal/tests/data_imports/github/conftest.py
@@ -6,7 +6,8 @@ import pytest
from dateutil import parser as dateutil_parser
-from posthog.temporal.tests.data_imports.github.data import COMMITS, ISSUES, PULL_REQUESTS, STARGAZERS
+from posthog.temporal.data_imports.sources.github.settings import GITHUB_ENDPOINTS
+from posthog.temporal.tests.data_imports.github.data import COMMITS, ISSUES, PULL_REQUESTS, STARGAZERS, WORKFLOW_RUNS
class MockGithubAPI:
@@ -26,6 +27,15 @@ class MockGithubAPI:
"pulls": PULL_REQUESTS,
"commits": COMMITS,
"stargazers": STARGAZERS,
+ "runs": WORKFLOW_RUNS,
+ }
+
+ # Derived from the production endpoint config so the mock and source stay
+ # in sync on which endpoints return enveloped responses.
+ ENVELOPE_KEYS: dict[str, str] = {
+ config.path.rsplit("/", 1)[-1]: config.response_data_path
+ for config in GITHUB_ENDPOINTS.values()
+ if config.response_data_path
}
def __init__(self, requests_mock):
@@ -47,7 +57,7 @@ class MockGithubAPI:
date_str = item.get("commit", {}).get("author", {}).get("date")
return date_str
- def get_resources(self, request: Any, context: Any) -> list[dict[str, Any]]:
+ def get_resources(self, request: Any, context: Any) -> Any:
path = urlparse(request.url).path
resource = path.split("/")[-1]
@@ -84,13 +94,20 @@ class MockGithubAPI:
key=lambda x: x.get(sort_key) or self._get_item_date(x) or "",
reverse=(direction == "desc"),
)
+ elif resource == "runs":
+ # Workflow runs API always returns newest-first by created_at.
+ data = sorted(data, key=lambda x: x.get("created_at") or "", reverse=True)
+
+ # total_count is the filtered count before pagination, matching GitHub's
+ # enveloped endpoints (the count does not shrink page to page).
+ total_count = len(data)
per_page = int(query.get("per_page", ["100"])[0])
page = int(query.get("page", ["1"])[0])
start = (page - 1) * per_page
end = start + per_page
- has_more = end < len(data)
+ has_more = end < total_count
data = data[start:end]
if has_more:
@@ -98,6 +115,9 @@ class MockGithubAPI:
next_page = page + 1
context.headers["Link"] = f'<{base_url}?page={next_page}&per_page={per_page}>; rel="next"'
+ envelope_key = self.ENVELOPE_KEYS.get(resource)
+ if envelope_key:
+ return {"total_count": total_count, envelope_key: data}
return data
def get_all_api_calls(self) -> list:
diff --git a/posthog/temporal/tests/data_imports/github/data.py b/posthog/temporal/tests/data_imports/github/data.py
index c6411587387c..84008929d282 100644
--- a/posthog/temporal/tests/data_imports/github/data.py
+++ b/posthog/temporal/tests/data_imports/github/data.py
@@ -135,6 +135,54 @@ COMMITS = [
},
]
+WORKFLOW_RUNS = [
+ {
+ "id": 1001,
+ "name": "CI",
+ "head_branch": "master",
+ "head_sha": "abc123",
+ "path": ".github/workflows/ci.yml",
+ "run_number": 100,
+ "event": "push",
+ "status": "completed",
+ "conclusion": "success",
+ "workflow_id": 9001,
+ "created_at": "2026-01-20T10:00:00Z",
+ "updated_at": "2026-01-20T10:30:00Z",
+ "run_started_at": "2026-01-20T10:00:30Z",
+ },
+ {
+ "id": 1002,
+ "name": "CI",
+ "head_branch": "feature/foo",
+ "head_sha": "def456",
+ "path": ".github/workflows/ci.yml",
+ "run_number": 101,
+ "event": "pull_request",
+ "status": "completed",
+ "conclusion": "failure",
+ "workflow_id": 9001,
+ "created_at": "2026-01-22T10:00:00Z",
+ "updated_at": "2026-01-22T10:45:00Z",
+ "run_started_at": "2026-01-22T10:00:20Z",
+ },
+ {
+ "id": 1003,
+ "name": "Deploy",
+ "head_branch": "master",
+ "head_sha": "ghi789",
+ "path": ".github/workflows/deploy.yml",
+ "run_number": 50,
+ "event": "push",
+ "status": "in_progress",
+ "conclusion": None,
+ "workflow_id": 9002,
+ "created_at": "2026-01-25T10:00:00Z",
+ "updated_at": "2026-01-25T10:05:00Z",
+ "run_started_at": "2026-01-25T10:00:10Z",
+ },
+]
+
STARGAZERS = [
{
"starred_at": "2026-01-10T10:00:00Z",
diff --git a/posthog/temporal/tests/data_imports/github/test_github_integration.py b/posthog/temporal/tests/data_imports/github/test_github_integration.py
index 116b2d00a7aa..e620afd45ab2 100644
--- a/posthog/temporal/tests/data_imports/github/test_github_integration.py
+++ b/posthog/temporal/tests/data_imports/github/test_github_integration.py
@@ -5,7 +5,7 @@ import pytest
from unittest import mock
from posthog.temporal.tests.data_imports.conftest import run_external_data_job_workflow
-from posthog.temporal.tests.data_imports.github.data import COMMITS, ISSUES, PULL_REQUESTS
+from posthog.temporal.tests.data_imports.github.data import COMMITS, ISSUES, PULL_REQUESTS, WORKFLOW_RUNS
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -73,6 +73,28 @@ def external_data_schema_pull_requests_incremental(external_data_source, team):
)
+def external_data_schema_workflow_runs_full_refresh(external_data_source, team):
+ return ExternalDataSchema.objects.create(
+ name="workflow_runs",
+ team_id=team.pk,
+ source_id=external_data_source.pk,
+ sync_type="full_refresh",
+ sync_type_config={},
+ )
+
+
+def external_data_schema_workflow_runs_incremental(external_data_source, team):
+ return ExternalDataSchema.objects.create(
+ name="workflow_runs",
+ team_id=team.pk,
+ source_id=external_data_source.pk,
+ sync_type="incremental",
+ sync_type_config={"incremental_field": "created_at", "incremental_field_type": "datetime"},
+ )
+
+
@mock.patch("posthog.temporal.data_imports.pipelines.pipeline.batcher.DEFAULT_CHUNK_SIZE", 1)
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
@@ -197,3 +219,68 @@ async def test_github_pull_requests_incremental(
assert first_call_params.get("sort") == ["created"]
assert first_call_params.get("direction") == ["asc"]
assert "since" not in first_call_params
+
+
[email protected]("posthog.temporal.data_imports.pipelines.pipeline.batcher.DEFAULT_CHUNK_SIZE", 1)
[email protected]_db(transaction=True)
+async def test_github_workflow_runs_full_refresh(
+ team, mock_github_api, external_data_source, external_data_schema_workflow_runs_full_refresh
+):
+ expected_num_rows = len(WORKFLOW_RUNS)
+
+ await run_external_data_job_workflow(
+ team=team,
+ external_data_source=external_data_source,
+ external_data_schema=external_data_schema_workflow_runs_full_refresh,
+ table_name="github_workflow_runs",
+ expected_rows_synced=expected_num_rows,
+ expected_total_rows=expected_num_rows,
+ )
+
+ api_calls = mock_github_api.get_all_api_calls()
+ assert len(api_calls) == 1
+ assert "/repos/owner/repo/actions/runs" in api_calls[0].url
+ # workflow_runs is a minimal-params endpoint: no sort/direction/state.
+ first_call_params = parse_qs(urlparse(api_calls[0].url).query)
+ assert "sort" not in first_call_params
+ assert "direction" not in first_call_params
+ assert "state" not in first_call_params
+ assert "created" not in first_call_params
+
+
[email protected]("posthog.temporal.data_imports.pipelines.pipeline.batcher.DEFAULT_CHUNK_SIZE", 1)
[email protected]_db(transaction=True)
+async def test_github_workflow_runs_incremental(
+ team, mock_github_api, external_data_source, external_data_schema_workflow_runs_incremental
+):
+ # Single-sync test mirroring the pull_requests/commits incremental tests:
+ # workflow_runs scrolls newest-first and bounds incremental syncs via
+ # client-side early-stop (no server filter), so the request shape is what
+ # matters here. The newest-first re-read + primary-key dedup across syncs is
+ # the pipeline merge's job; exercising it through two rapid in-harness syncs
+ # is flaky, so the desc early-stop overlap is covered deterministically in
+ # test_github_source.py instead.
+ expected_num_rows = len(WORKFLOW_RUNS)
+
+ await run_external_data_job_workflow(
+ team=team,
+ external_data_source=external_data_source,
+ external_data_schema=external_data_schema_workflow_runs_incremental,
+ table_name="github_workflow_runs",
+ expected_rows_synced=expected_num_rows,
+ expected_total_rows=expected_num_rows,
+ )
+
+ api_calls = mock_github_api.get_all_api_calls()
+ assert len(api_calls) == 1
+ assert "/repos/owner/repo/actions/runs" in api_calls[0].url
+ # No created/since/sort/state — the 1,000-result search cap is only hit when
+ # those filters are sent, so workflow_runs avoids them entirely.
+ first_call_params = parse_qs(urlparse(api_calls[0].url).query)
+ assert "created" not in first_call_params
+ assert "since" not in first_call_params
+ assert "sort" not in first_call_params
+ assert "direction" not in first_call_params
+ assert "state" not in first_call_params
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 4dcbe94845f5..7d82f91140c4 100644
--- a/posthog/temporal/tests/data_imports/github/test_github_source.py
+++ b/posthog/temporal/tests/data_imports/github/test_github_source.py
@@ -152,6 +152,30 @@ class TestBuildInitialParams:
assert params["sort"] == "created"
assert params["direction"] == "asc"
+ @parameterized.expand(
+ [
+ ("full_refresh", False, None),
+ ("incremental_first_sync", True, None),
+ ("incremental_with_cutoff", True, datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC)),
+ ]
+ )
+ def test_workflow_runs_always_minimal_params(
+ self, _name: str, should_use_incremental_field: bool, last_value: Any
+ ) -> None:
+ params = _build_initial_params(
+ GITHUB_ENDPOINTS["workflow_runs"],
+ "workflow_runs",
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ incremental_field="created_at",
+ )
+
+ # workflow_runs is always a plain paged read: no state/sort/direction,
+ # no `since`, and crucially no `created` filter (the filter caps results
+ # at 1,000). Incremental bounding happens client-side via desc
+ # early-stop in get_rows, so the request never changes shape.
+ assert params == {"per_page": 100}
+
class TestBuildInitialUrl:
def test_with_params(self) -> None:
@@ -439,6 +463,18 @@ class TestGithubSourceSortMode:
"desc",
),
("issues_always_asc", "issues", True, datetime(2026, 1, 15, tzinfo=UTC), "asc"),
+ # workflow_runs always emits newest-first (the API ignores sort), so
+ # sort_mode must be desc even on the first sync / full refresh —
+ # never the asc default that other endpoints use before a cutoff.
+ ("workflow_runs_full_refresh", "workflow_runs", False, None, "desc"),
+ ("workflow_runs_first_sync_no_cutoff", "workflow_runs", True, None, "desc"),
+ (
+ "workflow_runs_incremental_with_cutoff",
+ "workflow_runs",
+ True,
+ datetime(2026, 1, 15, tzinfo=UTC),
+ "desc",
+ ),
]
)
def test_sort_mode(
@@ -579,6 +615,108 @@ 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_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"}]}
+
+ 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 = [_make_response(body=envelope, link="")]
+ rows = list(
+ get_rows(
+ personal_access_token="tok",
+ repository="owner/repo",
+ endpoint="workflow_runs",
+ logger=mock.Mock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=False,
+ )
+ )
+
+ assert len(rows) == 1
+ assert rows[0]["id"] == 1001
+
+ def test_workflow_runs_empty_envelope_ends_loop(self) -> None:
+ manager = _make_manager(can_resume=False)
+ envelope = {"total_count": 0, "workflow_runs": []}
+
+ 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 = [_make_response(body=envelope, link="")]
+ rows = list(
+ get_rows(
+ personal_access_token="tok",
+ repository="owner/repo",
+ endpoint="workflow_runs",
+ logger=mock.Mock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=False,
+ )
+ )
+
+ assert rows == []
+ manager.save_state.assert_not_called()
+
+ def test_workflow_runs_incremental_stops_at_cutoff_without_filter(self) -> None:
+ """Incremental workflow_runs paginates newest-first and stops once a
+ page crosses below the cursor — never sending a `created`/`since`
+ filter (which would cap results at 1,000). A page past the cutoff must
+ not be fetched."""
+ manager = _make_manager(can_resume=False)
+ cutoff = datetime(2026, 1, 20, tzinfo=UTC)
+ page1 = {
+ "total_count": 3,
+ "workflow_runs": [
+ {"id": 3, "created_at": "2026-01-25T00:00:00Z"},
+ {"id": 2, "created_at": "2026-01-22T00:00:00Z"},
+ ],
+ }
+ page2 = {"total_count": 3, "workflow_runs": [{"id": 1, "created_at": "2026-01-18T00:00:00Z"}]}
+ link_page1 = '<https://api.github.com/repos/owner/repo/actions/runs?page=2>; rel="next"'
+ # Only two responses are provided: a fetch of page 3 would raise
+ # StopIteration, so the test fails if early-stop doesn't fire.
+ responses = [
+ _make_response(body=page1, link=link_page1),
+ _make_response(
+ body=page2, link='<https://api.github.com/repos/owner/repo/actions/runs?page=3>; rel="next"'
+ ),
+ ]
+
+ 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 = responses
+ rows = list(
+ get_rows(
+ personal_access_token="tok",
+ repository="owner/repo",
+ endpoint="workflow_runs",
+ logger=mock.Mock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=cutoff,
+ incremental_field="created_at",
+ )
+ )
+
+ assert [row["id"] for row in rows] == [3, 2, 1]
+ assert mock_get.return_value.get.call_count == 2
+ first_url = mock_get.return_value.get.call_args_list[0].args[0]
+ assert "created=" not in first_url
+ assert "since=" not in first_url
+ assert "/actions/runs" in first_url
+
def test_mid_page_chunk_boundary_checkpoints_current_page(self) -> None:
"""If the chunk boundary lands mid-page, the checkpoint must point at
the CURRENT page (not the next), so trailing unyielded items are