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): github workflow_jobs + webhook prototype (#64479)

Julian Bezf25d348de27a
diff --git a/posthog/management/commands/sync_hog_function_templates.py b/posthog/management/commands/sync_hog_function_templates.py
index 28704b0955aa..7641bceac562 100644
--- a/posthog/management/commands/sync_hog_function_templates.py
+++ b/posthog/management/commands/sync_hog_function_templates.py
@@ -26,6 +26,7 @@ TEST_INCLUDE_PYTHON_TEMPLATE_IDS = [
"template-warehouse-source-stripe",
"template-warehouse-source-customer-io",
"template-warehouse-source-slack",
+ "template-warehouse-source-github",
"template-warehouse-source-default",
]
TEST_INCLUDE_NODEJS_TEMPLATE_IDS = [
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 5d2015e93e26..325f77ce0f90 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -98,7 +98,7 @@ the row lists both.
| eventbrite | HTTP | requests | ✅ |
| front | HTTP | requests | ✅ |
| fullstory | HTTP | requests | ✅ |
-| github | HTTP | requests | ✅ |
+| github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| gitlab | HTTP | requests | ✅ |
| gladly | HTTP | requests | ✅ |
| gocardless | HTTP | requests | ✅ |
diff --git a/posthog/temporal/data_imports/sources/github/github.py b/posthog/temporal/data_imports/sources/github/github.py
index b5fd5533caf0..67cd99ab0c69 100644
--- a/posthog/temporal/data_imports/sources/github/github.py
+++ b/posthog/temporal/data_imports/sources/github/github.py
@@ -1,23 +1,38 @@
import re
import dataclasses
-from collections.abc import Callable, Iterator
-from datetime import UTC, date, datetime
+from collections.abc import AsyncIterator, Callable, Iterator
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Literal, Optional
from urllib.parse import urlencode
import requests
+from asgiref.sync import async_to_sync
from dateutil import parser as dateutil_parser
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+)
from posthog.temporal.data_imports.sources.common.http import make_tracked_session
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from posthog.temporal.data_imports.sources.github.settings import GITHUB_ENDPOINTS, GithubEndpointConfig
GITHUB_BASE_URL = "https://api.github.com"
+# Managing repo webhooks needs the `admin:repo_hook` scope on a classic token, or the
+# "Repository webhooks: read and write" permission on a fine-grained token. Name both so
+# the error/setup guidance doesn't mislead whichever token type the user connected.
+_WEBHOOK_PERMISSION_HINT = (
+ "the `admin:repo_hook` scope (classic token) or the "
+ '"Repository webhooks: read and write" permission (fine-grained token)'
+)
+
class GithubRetryableError(Exception):
pass
@@ -111,16 +126,17 @@ def _resolve_sort_mode(
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.
+ sync — including the first. workflow_jobs inherits that order: it fans out
+ over workflow_runs newest-first, so its jobs land newest-first too.
"""
- if endpoint == "workflow_runs":
+ if endpoint in ("workflow_runs", "workflow_jobs"):
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]:
+def _get_headers(access_token: str, endpoint: str = "") -> dict[str, str]:
headers = {
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github+json",
@@ -166,6 +182,11 @@ def _as_utc(dt: datetime) -> datetime:
return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+def _now_utc() -> datetime:
+ """Wall clock as UTC. Wrapped so the first-sync lookback floor is patchable in tests."""
+ return datetime.now(UTC)
+
+
def _is_older_than_cutoff(value: Any, cutoff: datetime) -> bool:
if value is None:
return False
@@ -289,6 +310,163 @@ def _get_item_filter(endpoint: str) -> Callable[[dict[str, Any]], bool] | None:
return None
+@retry(
+ retry=retry_if_exception_type((GithubRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(page_url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> requests.Response:
+ response = make_tracked_session().get(page_url, headers=headers, timeout=60)
+
+ 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()
+
+ return response
+
+
+def _iter_pages(
+ url: str,
+ headers: dict[str, str],
+ response_data_path: str | None,
+ logger: FilteringBoundLogger,
+ max_pages: int | None = None,
+ page_cap_context: dict[str, Any] | None = None,
+) -> 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``,
+ logging a structured warning when the cap is reached. An empty or ``null``
+ envelope body simply ends iteration — there is nothing to truncate."""
+ page_count = 0
+ while True:
+ response = _fetch_page(url, headers, logger)
+ data = response.json()
+ if response_data_path and isinstance(data, dict):
+ data = data.get(response_data_path) or []
+ if not isinstance(data, list) or not data:
+ return
+ next_url = _parse_next_url(response.headers.get("Link", ""))
+ yield data, url
+ page_count += 1
+ if not next_url:
+ return
+ if max_pages is not None and page_count >= max_pages:
+ logger.warning(
+ "Github: per-parent page cap reached; remaining pages skipped",
+ max_pages=max_pages,
+ **(page_cap_context or {}),
+ )
+ return
+ url = next_url
+
+
+def _iter_jobs_for_run(
+ repository: str,
+ run_id: Any,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ config: GithubEndpointConfig,
+) -> Iterator[dict[str, Any]]:
+ path = config.path.format(repository=repository, run_id=run_id)
+ 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(
+ url,
+ headers,
+ config.response_data_path,
+ logger,
+ max_pages=config.max_pages_per_parent,
+ page_cap_context={"repository": repository, "run_id": run_id},
+ ):
+ yield from jobs
+
+
+def _fan_out_get_rows(
+ personal_access_token: str,
+ repository: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GithubResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | 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.
+ """
+ child_config = GITHUB_ENDPOINTS[endpoint]
+ assert child_config.fan_out_parent is not None # guarded by the get_rows dispatch
+ parent_config = GITHUB_ENDPOINTS[child_config.fan_out_parent]
+ 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
+
+ # 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
+ # 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
+ and db_incremental_field_last_value is None
+ and child_config.initial_lookback_days is not None
+ ):
+ parent_cutoff = _now_utc() - timedelta(days=child_config.initial_lookback_days)
+ logger.debug(f"Github: flooring {endpoint} first-sync fan-out at {parent_cutoff.isoformat()}")
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ parent_url: str = resume_config.next_url
+ logger.debug(f"Github: resuming {endpoint} fan-out from parent URL: {parent_url}")
+ else:
+ parent_url = _build_initial_url(parent_config, repository, {"per_page": parent_config.page_size})
+
+ for runs, page_url in _iter_pages(parent_url, headers, parent_config.response_data_path, logger):
+ stop_after_this_page = _should_stop_desc(runs, "desc", parent_field, parent_cutoff)
+
+ for run in runs:
+ # Direct access on the run's id (its primary key): a run without one is a broken
+ # response that should fail loudly, not get silently dropped.
+ run_id = run["id"]
+ # 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):
+ continue
+ for job in _iter_jobs_for_run(repository, run_id, headers, logger, child_config):
+ batcher.batch(job)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Checkpoint the parent page; resume re-fans it out and dedupes by id.
+ if not stop_after_this_page:
+ resumable_source_manager.save_state(GithubResumeConfig(next_url=page_url))
+
+ if stop_after_this_page:
+ break
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
def get_rows(
personal_access_token: str,
repository: str,
@@ -300,6 +478,19 @@ def get_rows(
incremental_field: str | None = None,
) -> Iterator[Any]:
config = GITHUB_ENDPOINTS[endpoint]
+ if config.fan_out_parent is not None:
+ yield from _fan_out_get_rows(
+ personal_access_token=personal_access_token,
+ repository=repository,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ )
+ return
+
headers = _get_headers(personal_access_token, endpoint)
batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
@@ -327,33 +518,9 @@ def get_rows(
else:
url = _build_initial_url(config, repository, initial_params)
- @retry(
- retry=retry_if_exception_type((GithubRetryableError, requests.ReadTimeout, requests.ConnectionError)),
- stop=stop_after_attempt(5),
- wait=wait_exponential_jitter(initial=1, max=30),
- reraise=True,
- )
- def fetch_page(page_url: str) -> requests.Response:
- response = make_tracked_session().get(page_url, headers=headers, timeout=60)
-
- 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()
-
- return response
-
while True:
try:
- response = fetch_page(url)
+ response = _fetch_page(url, headers, logger)
except GithubEmptyRepositoryError:
logger.debug(f"Github: repository has no commits (empty repository), syncing zero rows: url={url}")
break
@@ -410,6 +577,7 @@ def github_source(
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
incremental_field: str | None = None,
+ webhook_source_manager: Optional[WebhookSourceManager] = None,
) -> SourceResponse:
endpoint_config = GITHUB_ENDPOINTS[endpoint]
@@ -417,9 +585,24 @@ def github_source(
endpoint_config, endpoint, should_use_incremental_field, db_incremental_field_last_value
)
- return SourceResponse(
- name=endpoint,
- items=lambda: get_rows(
+ # Steady-state webhook ingestion replaces the poll fan-out once the initial
+ # backfill is complete and a webhook function is enabled. When no manager is
+ # passed (or it isn't enabled), the poll path below stays unchanged.
+ webhook_enabled = (
+ async_to_sync(webhook_source_manager.webhook_enabled)() if webhook_source_manager is not None else False
+ )
+
+ def items() -> Iterator[Any] | AsyncIterator[Any]:
+ if webhook_enabled:
+ assert webhook_source_manager is not None
+ # The Hog template lands the nested workflow_job / workflow_run object as the
+ # row, with no transform — it matches the polled REST shape. GitHub defines the
+ # job and workflow-run objects once: the "list jobs for a workflow run" REST
+ # response object is the same schema as the workflow_job webhook event's nested
+ # workflow_job object (same for workflow_run), so the rows are interchangeable.
+ return webhook_source_manager.get_items()
+
+ return get_rows(
personal_access_token=personal_access_token,
repository=repository,
endpoint=endpoint,
@@ -428,7 +611,11 @@ def github_source(
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
incremental_field=incremental_field,
- ),
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=items,
primary_keys=[endpoint_config.primary_key],
sort_mode=actual_sort_mode,
partition_count=1,
@@ -437,3 +624,155 @@ def github_source(
partition_format="week" if endpoint_config.partition_key else None,
partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
)
+
+
+def _is_repo_hook_permission_error(response: requests.Response) -> bool:
+ """A token without admin:repo_hook can't manage repo webhooks — GitHub returns
+ 403 (or 404 when the resource is hidden from the token). Treat both as the
+ permission case so callers fall back to manual setup instead of retrying."""
+ return response.status_code in (403, 404)
+
+
+def create_repo_webhook(
+ token: str, repo: str, webhook_url: str, events: list[str], secret: str
+) -> WebhookCreationResult:
+ """Create a repo webhook via POST /repos/{repo}/hooks.
+
+ Returns a failed (not raised) result when the token lacks admin:repo_hook so
+ the caller can surface a manual-setup caption instead of hard-failing.
+ """
+ headers = _get_headers(token)
+ payload = {
+ "name": "web",
+ "active": True,
+ "events": events,
+ "config": {
+ "url": webhook_url,
+ "content_type": "json",
+ "secret": secret,
+ },
+ }
+
+ try:
+ response = make_tracked_session().post(
+ f"{GITHUB_BASE_URL}/repos/{repo}/hooks", headers=headers, json=payload, timeout=30
+ )
+ except requests.exceptions.RequestException as e:
+ return WebhookCreationResult(success=False, error=f"Failed to create webhook automatically: {e}")
+
+ if response.status_code in (200, 201):
+ # GitHub never echoes the secret back, so we return the one we generated as
+ # extra_inputs — the framework persists it onto the hog function's
+ # signing_secret input, which the template uses to verify X-Hub-Signature-256.
+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})
+
+ if _is_repo_hook_permission_error(response):
+ return WebhookCreationResult(
+ success=False,
+ error=(
+ f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT} needed to create a repository webhook. "
+ "Add it and reconnect, or set up the webhook manually following the steps below."
+ ),
+ )
+
+ return WebhookCreationResult(
+ success=False, error=f"Failed to create webhook automatically: {response.status_code} {response.text}"
+ )
+
+
+def _list_repo_hooks(token: str, repo: str) -> tuple[list[dict[str, Any]] | None, str | None]:
+ """List repo webhooks via GET /repos/{repo}/hooks. Returns (hooks, error); error is
+ ``"permission"`` when the token lacks admin:repo_hook so callers can fall back to manual setup."""
+ try:
+ response = make_tracked_session().get(
+ f"{GITHUB_BASE_URL}/repos/{repo}/hooks", headers=_get_headers(token), params={"per_page": 100}, timeout=30
+ )
+ except requests.exceptions.RequestException as e:
+ return None, str(e)
+
+ if _is_repo_hook_permission_error(response):
+ return None, "permission"
+ if not response.ok:
+ return None, f"{response.status_code} {response.text}"
+
+ hooks = response.json()
+ return (hooks if isinstance(hooks, list) else []), None
+
+
+def _match_hook_by_url(hooks: list[dict[str, Any]], webhook_url: str) -> dict[str, Any] | None:
+ """Return the hook whose config.url matches webhook_url, or None."""
+ for hook in hooks:
+ # `config` can be present-but-null on some hook shapes; `or {}` guards the
+ # null case that a plain `.get("config", {})` default would not.
+ if (hook.get("config") or {}).get("url") == webhook_url:
+ return hook
+ return None
+
+
+def _find_repo_hook_id(token: str, repo: str, webhook_url: str) -> tuple[int | None, str | None]:
+ """Return (hook_id, error). Matches on config.url == webhook_url."""
+ hooks, error = _list_repo_hooks(token, repo)
+ if error is not None:
+ return None, error
+ hook = _match_hook_by_url(hooks or [], webhook_url)
+ return (hook.get("id") if hook else None), None
+
+
+def delete_repo_webhook(token: str, repo: str, webhook_url: str) -> WebhookDeletionResult:
+ """Find the repo webhook matching webhook_url and DELETE /repos/{repo}/hooks/{id}."""
+ hook_id, error = _find_repo_hook_id(token, repo, webhook_url)
+ if error == "permission":
+ return WebhookDeletionResult(
+ success=False,
+ error=f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT}. Please delete the webhook manually.",
+ )
+ if error is not None:
+ return WebhookDeletionResult(success=False, error=f"Failed to delete webhook: {error}")
+ if hook_id is None:
+ # Nothing to delete — treat as success, same as Stripe's no-match path.
+ return WebhookDeletionResult(success=True)
+
+ headers = _get_headers(token)
+ try:
+ response = make_tracked_session().delete(
+ f"{GITHUB_BASE_URL}/repos/{repo}/hooks/{hook_id}", headers=headers, timeout=30
+ )
+ except requests.exceptions.RequestException as e:
+ return WebhookDeletionResult(success=False, error=f"Failed to delete webhook: {e}")
+
+ # 404 here means the hook vanished between the list and the DELETE (concurrent
+ # delete, manual removal) — the end state we wanted, so treat it as success
+ # rather than the permission case _is_repo_hook_permission_error would assign.
+ if response.status_code in (200, 204, 404):
+ return WebhookDeletionResult(success=True)
+ if _is_repo_hook_permission_error(response):
+ return WebhookDeletionResult(
+ success=False,
+ error=f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT}. Please delete the webhook manually.",
+ )
+ return WebhookDeletionResult(
+ success=False, error=f"Failed to delete webhook: {response.status_code} {response.text}"
+ )
+
+
+def get_repo_webhook_info(token: str, repo: str, webhook_url: str) -> ExternalWebhookInfo:
+ """List repo webhooks via GET /repos/{repo}/hooks and match config.url == webhook_url."""
+ hooks, error = _list_repo_hooks(token, repo)
+ if error == "permission":
+ return ExternalWebhookInfo(
+ exists=False,
+ error=f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT} needed to read repository webhooks.",
+ )
+ if error is not None:
+ return ExternalWebhookInfo(exists=False, error=f"Failed to check webhook status: {error}")
+
+ hook = _match_hook_by_url(hooks or [], webhook_url)
+ if hook is None:
+ return ExternalWebhookInfo(exists=False)
+ return ExternalWebhookInfo(
+ exists=True,
+ url=webhook_url,
+ enabled_events=hook.get("events"),
+ status="active" if hook.get("active") else "disabled",
+ created_at=hook.get("created_at"),
+ )
diff --git a/posthog/temporal/data_imports/sources/github/settings.py b/posthog/temporal/data_imports/sources/github/settings.py
index 48d9d1eb9a10..7d1dbab0455b 100644
--- a/posthog/temporal/data_imports/sources/github/settings.py
+++ b/posthog/temporal/data_imports/sources/github/settings.py
@@ -18,6 +18,21 @@ class GithubEndpointConfig:
# (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
+ # 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.
+ fan_out_parent: Optional[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
+ # pagination. A structured warning is logged if the cap is reached.
+ max_pages_per_parent: int = 50
+ # First-sync floor: when set, the very first incremental sync only fans out
+ # over parents created within this many days, instead of crawling the whole
+ # repo history. The webhook carries steady-state, so only the one-off backfill
+ # needs a bound; later syncs advance from the stored watermark and ignore this.
+ initial_lookback_days: Optional[int] = None
GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {
@@ -119,6 +134,43 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {
sort_mode="desc", # API always returns newest-first; sort/direction are ignored
response_data_path="workflow_runs",
),
+ "workflow_jobs": GithubEndpointConfig(
+ name="workflow_jobs",
+ # Child of workflow_runs: {run_id} is filled per parent run during fan-out.
+ path="/repos/{repository}/actions/runs/{run_id}/jobs",
+ partition_key="created_at", # Set at job creation; non-null even while queued/running.
+ incremental_fields=[
+ # The jobs endpoint exposes no server-side time filter, so workflow_jobs
+ # cannot have its own cursor. We bound incremental syncs at the parent:
+ # walk workflow_runs newest-first, stop once run.created_at crosses below
+ # the watermark, and fan out jobs only for runs at/above it (see
+ # github.py). Jobs upsert by id, so re-reading a boundary run is harmless.
+ #
+ # Same created_at-cursor staleness as workflow_runs applies: a run whose
+ # jobs finish well after newer runs have landed won't be re-fanned-out
+ # once it drops below the watermark. The eventual fix is the workflow_run
+ # webhook (followup), not re-scanning history.
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ default_incremental_field="created_at",
+ sort_mode="desc", # Emitted parent-newest-first, so jobs land newest-first too.
+ response_data_path="jobs",
+ fan_out_parent="workflow_runs",
+ # filter=all returns jobs across every run_attempt (retries), not just the
+ # latest execution — required for retry/runner-utilization analysis.
+ extra_params={"filter": "all"},
+ # One /jobs call per run makes an unbounded first sync a multi-day,
+ # rate-limited crawl of the whole repo history (the OAuth budget is shared
+ # with Tasks/Code/deploys). A busy repo merges ~100 PRs/day, so even a few
+ # days seeds plenty of rows to start from; the webhook carries everything
+ # after. Keep the initial backfill tiny — just enough to not start empty.
+ initial_lookback_days=3,
+ ),
}
ENDPOINTS = tuple(GITHUB_ENDPOINTS.keys())
diff --git a/posthog/temporal/data_imports/sources/github/source.py b/posthog/temporal/data_imports/sources/github/source.py
index af80807a54d5..804ae829a1ce 100644
--- a/posthog/temporal/data_imports/sources/github/source.py
+++ b/posthog/temporal/data_imports/sources/github/source.py
@@ -1,4 +1,8 @@
-from typing import Optional, cast
+import secrets
+from typing import TYPE_CHECKING, Optional, cast
+
+if TYPE_CHECKING:
+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
from posthog.schema import (
DataWarehouseSourceCategory,
@@ -14,14 +18,25 @@ from posthog.schema import (
from posthog.models.integration import GitHubIntegration
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
-from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ FieldType,
+ ResumableSource,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+ WebhookSource,
+)
from posthog.temporal.data_imports.sources.common.mixins import OAuthMixin
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from posthog.temporal.data_imports.sources.generated_configs import GithubSourceConfig
from posthog.temporal.data_imports.sources.github.github import (
GithubResumeConfig,
+ create_repo_webhook,
+ delete_repo_webhook,
+ get_repo_webhook_info,
github_source,
validate_credentials as validate_github_credentials,
)
@@ -29,13 +44,34 @@ from posthog.temporal.data_imports.sources.github.settings import ENDPOINTS, INC
from products.data_warehouse.backend.types import ExternalDataSourceType
+# Schemas that can be fed by GitHub webhooks, mapped to the X-GitHub-Event header
+# value the webhook handler routes on (schema_mapping is keyed by these values).
+GITHUB_WEBHOOK_RESOURCE_MAP: dict[str, str] = {
+ "workflow_jobs": "workflow_job",
+ "workflow_runs": "workflow_run",
+}
+
@SourceRegistry.register
-class GithubSource(ResumableSource[GithubSourceConfig, GithubResumeConfig], OAuthMixin):
+class GithubSource(
+ ResumableSource[GithubSourceConfig, GithubResumeConfig],
+ WebhookSource[GithubSourceConfig],
+ OAuthMixin,
+):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GITHUB
+ @property
+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
+ from posthog.temporal.data_imports.sources.github.webhook_template import template
+
+ return template
+
+ @property
+ def webhook_resource_map(self) -> dict[str, str]:
+ return GITHUB_WEBHOOK_RESOURCE_MAP
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
@@ -100,6 +136,30 @@ class GithubSource(ResumableSource[GithubSourceConfig, GithubResumeConfig], OAut
),
],
),
+ webhookSetupCaption="""To set up the webhook manually:
+
+1. Go to your repository's **Settings > Webhooks** on GitHub
+2. Click **Add webhook**
+3. Paste the webhook URL shown below into the **Payload URL** field
+4. Set **Content type** to **application/json**
+5. Enter a **Secret** and add the same value to the **Signing secret** field below
+6. Under **Which events would you like to trigger this webhook?**, choose **Let me select individual events** and tick **Workflow jobs** and **Workflow runs**
+7. Click **Add webhook**
+
+If automatic creation failed, your token needs webhook permissions — the **admin:repo_hook** scope on a classic token, or **Repository webhooks: read and write** on a fine-grained token. Add it and reconnect, or set the webhook up manually using the steps above.""",
+ webhookFields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="signing_secret",
+ label="Signing secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="your webhook secret",
+ secret=True,
+ ),
+ ],
+ ),
)
def get_non_retryable_errors(self) -> dict[str, str | None]:
@@ -163,6 +223,9 @@ class GithubSource(ResumableSource[GithubSourceConfig, GithubResumeConfig], OAut
name=endpoint,
supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ # Only the workflow endpoints can be steady-state webhook-fed; the
+ # poll fan-out is the backfill, the webhook replaces re-polling.
+ supports_webhooks=endpoint in GITHUB_WEBHOOK_RESOURCE_MAP,
incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
)
for endpoint in list(ENDPOINTS)
@@ -184,6 +247,38 @@ class GithubSource(ResumableSource[GithubSourceConfig, GithubResumeConfig], OAut
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GithubResumeConfig]:
return ResumableSourceManager[GithubResumeConfig](inputs, GithubResumeConfig)
+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
+ return WebhookSourceManager(inputs, inputs.logger)
+
+ def get_desired_webhook_events(
+ self, config: GithubSourceConfig, eligible_schema_names: list[str]
+ ) -> list[str] | None:
+ # Map the eligible schemas to GitHub event names (e.g. ["workflow_job", "workflow_run"]).
+ return [
+ GITHUB_WEBHOOK_RESOURCE_MAP[name] for name in eligible_schema_names if name in GITHUB_WEBHOOK_RESOURCE_MAP
+ ]
+
+ def create_webhook(self, config: GithubSourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:
+ access_token = self._get_access_token(config, team_id)
+ # GitHub's webhook secret is creator-supplied, so we mint one, hand it to GitHub as the
+ # hook's config.secret, and return it via extra_inputs so it lands on the hog function for
+ # signature verification. (Contrast Stripe, which generates and returns its own secret.)
+ secret = secrets.token_hex(32)
+ # Always subscribe to the full workflow event pair, not just the enabled schemas: jobs fan
+ # out under runs, so the two travel together and we want both regardless of which is synced.
+ events = self.get_desired_webhook_events(config, list(GITHUB_WEBHOOK_RESOURCE_MAP.keys())) or []
+ return create_repo_webhook(access_token, config.repository, webhook_url, events, secret=secret)
+
+ def delete_webhook(self, config: GithubSourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:
+ access_token = self._get_access_token(config, team_id)
+ return delete_repo_webhook(access_token, config.repository, webhook_url)
+
+ def get_external_webhook_info(
+ self, config: GithubSourceConfig, webhook_url: str, team_id: int
+ ) -> ExternalWebhookInfo:
+ access_token = self._get_access_token(config, team_id)
+ return get_repo_webhook_info(access_token, config.repository, webhook_url)
+
def source_for_pipeline(
self,
config: GithubSourceConfig,
@@ -191,6 +286,11 @@ class GithubSource(ResumableSource[GithubSourceConfig, GithubResumeConfig], OAut
inputs: SourceInputs,
) -> SourceResponse:
access_token = self._get_access_token(config, inputs.team_id)
+ # Only the workflow schemas can be webhook-fed, so skip building the manager — and its
+ # webhook_enabled() DB lookup — for the poll-only endpoints (issues, commits, etc.).
+ webhook_source_manager = (
+ self.get_webhook_source_manager(inputs) if inputs.schema_name in GITHUB_WEBHOOK_RESOURCE_MAP else None
+ )
return github_source(
personal_access_token=access_token,
@@ -203,4 +303,5 @@ class GithubSource(ResumableSource[GithubSourceConfig, GithubResumeConfig], OAut
if inputs.should_use_incremental_field
else None,
incremental_field=inputs.incremental_field,
+ webhook_source_manager=webhook_source_manager,
)
diff --git a/posthog/temporal/data_imports/sources/github/webhook_template.py b/posthog/temporal/data_imports/sources/github/webhook_template.py
new file mode 100644
index 000000000000..32ef48b56c7b
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/github/webhook_template.py
@@ -0,0 +1,135 @@
+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+template: HogFunctionTemplateDC = HogFunctionTemplateDC(
+ status="alpha",
+ free=False,
+ type="warehouse_source_webhook",
+ id="template-warehouse-source-github",
+ name="GitHub warehouse source webhook",
+ description="Receive GitHub webhook events for data warehouse ingestion",
+ icon_url="/static/services/github.png",
+ category=["Data warehouse"],
+ code_language="hog",
+ code="""\
+if (request.method != 'POST') {
+ return {
+ 'httpResponse': {
+ 'status': 405,
+ 'body': 'Method not allowed'
+ }
+ }
+}
+
+if (not inputs.bypass_signature_check) {
+ if (empty(inputs.signing_secret)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Signing secret not configured',
+ }
+ }
+ }
+
+ let signatureHeader := request.headers['x-hub-signature-256']
+
+ if (empty(signatureHeader)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Missing signature',
+ }
+ }
+ }
+
+ // GitHub sends sha256=<hex>, where <hex> is the HMAC-SHA256 of the raw
+ // request body keyed by the webhook secret. No timestamp is involved.
+ let computedSignature := concat('sha256=', sha256HmacChainHex([inputs.signing_secret, request.stringBody]))
+
+ if (computedSignature != signatureHeader) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Bad signature',
+ }
+ }
+ }
+}
+
+// Event type comes from the X-GitHub-Event header, not the body.
+let eventType := request.headers['x-github-event']
+
+if (empty(eventType)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': 'No event type found, skipping'
+ }
+ }
+}
+
+let schemaId := inputs.schema_mapping?.[eventType]
+
+if (empty(schemaId)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': f'No schema mapping for event type: {eventType}, skipping'
+ }
+ }
+}
+
+// The poll endpoints land the job/run objects themselves, so the webhook lands the
+// same nested object — request.body.workflow_job / request.body.workflow_run — rather
+// than the whole event envelope. GitHub uses one object schema per resource, so the
+// nested webhook object matches the REST "list jobs for a workflow run" response shape.
+let row := request.body?.[eventType]
+
+if (empty(row)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': f'No {eventType} object in payload, skipping'
+ }
+ }
+}
+
+produceToWarehouseWebhooks(row, schemaId)""",
+ inputs_schema=[
+ {
+ "type": "string",
+ "key": "signing_secret",
+ "label": "Signing secret",
+ "required": False,
+ "secret": True,
+ "hidden": False,
+ "description": "Used to validate the webhook came from GitHub. Set as the webhook's Secret in the repo's Settings > Webhooks.",
+ },
+ {
+ "type": "boolean",
+ "key": "bypass_signature_check",
+ "label": "Bypass signature check",
+ "description": "If set, the X-Hub-Signature-256 header will not be checked. This is not recommended.",
+ "default": False,
+ "required": False,
+ "secret": False,
+ },
+ {
+ "type": "json",
+ "key": "schema_mapping",
+ "label": "Schema mapping",
+ "description": "Maps GitHub event types (workflow_job, workflow_run) to ExternalDataSchema IDs",
+ "required": True,
+ "secret": False,
+ "hidden": True,
+ },
+ {
+ "type": "string",
+ "key": "source_id",
+ "label": "Source ID",
+ "description": "The ExternalDataSource ID this webhook is associated with",
+ "required": True,
+ "secret": False,
+ "hidden": True,
+ },
+ ],
+)
diff --git a/posthog/temporal/tests/data_imports/github/conftest.py b/posthog/temporal/tests/data_imports/github/conftest.py
index 8bc2fea8abf4..759f7f3d4b41 100644
--- a/posthog/temporal/tests/data_imports/github/conftest.py
+++ b/posthog/temporal/tests/data_imports/github/conftest.py
@@ -7,7 +7,14 @@ import pytest
from dateutil import parser as dateutil_parser
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
+from posthog.temporal.tests.data_imports.github.data import (
+ COMMITS,
+ ISSUES,
+ PULL_REQUESTS,
+ STARGAZERS,
+ WORKFLOW_JOBS,
+ WORKFLOW_RUNS,
+)
class MockGithubAPI:
@@ -61,11 +68,15 @@ class MockGithubAPI:
path = urlparse(request.url).path
resource = path.split("/")[-1]
- if resource not in self.RESOURCES:
+ if resource == "jobs":
+ # Fan-out child: /repos/{owner}/{repo}/actions/runs/{run_id}/jobs
+ run_id = int(path.split("/")[-2])
+ data = [dict(job) for job in WORKFLOW_JOBS if job.get("run_id") == run_id]
+ elif resource not in self.RESOURCES:
context.status_code = 404
return []
-
- data = list(self.RESOURCES[resource])
+ else:
+ data = list(self.RESOURCES[resource])
if self.max_updated is not None:
max_dt = dateutil_parser.parse(self.max_updated)
@@ -91,12 +102,12 @@ class MockGithubAPI:
sort_key = f"{sort_field}_at" if not sort_field.endswith("_at") else sort_field
data = sorted(
data,
- key=lambda x: x.get(sort_key) or self._get_item_date(x) or "",
+ key=lambda x: str(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)
+ data = sorted(data, key=lambda x: str(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).
diff --git a/posthog/temporal/tests/data_imports/github/data.py b/posthog/temporal/tests/data_imports/github/data.py
index 84008929d282..d037cd4bd484 100644
--- a/posthog/temporal/tests/data_imports/github/data.py
+++ b/posthog/temporal/tests/data_imports/github/data.py
@@ -150,6 +150,8 @@ WORKFLOW_RUNS = [
"created_at": "2026-01-20T10:00:00Z",
"updated_at": "2026-01-20T10:30:00Z",
"run_started_at": "2026-01-20T10:00:30Z",
+ "actor": {"login": "alice", "id": 100},
+ "pull_requests": [],
},
{
"id": 1002,
@@ -165,6 +167,8 @@ WORKFLOW_RUNS = [
"created_at": "2026-01-22T10:00:00Z",
"updated_at": "2026-01-22T10:45:00Z",
"run_started_at": "2026-01-22T10:00:20Z",
+ "actor": {"login": "bob", "id": 101},
+ "pull_requests": [{"id": 11, "number": 11, "head": {"ref": "feature/foo"}}],
},
{
"id": 1003,
@@ -180,6 +184,90 @@ WORKFLOW_RUNS = [
"created_at": "2026-01-25T10:00:00Z",
"updated_at": "2026-01-25T10:05:00Z",
"run_started_at": "2026-01-25T10:00:10Z",
+ "actor": {"login": "charlie", "id": 102},
+ "pull_requests": [],
+ },
+]
+
+# Jobs fan out from WORKFLOW_RUNS by run_id. steps[] stays nested exactly as the
+# API returns it — the pipeline JSON-serializes nested struct/list columns on write.
+WORKFLOW_JOBS = [
+ {
+ "id": 20001,
+ "run_id": 1001,
+ "run_attempt": 1,
+ "name": "build",
+ "status": "completed",
+ "conclusion": "success",
+ "workflow_name": "CI",
+ "head_sha": "abc123",
+ "head_branch": "master",
+ "runner_id": 5,
+ "runner_name": "ubuntu-latest",
+ "runner_group_id": 1,
+ "runner_group_name": "GitHub Actions",
+ "labels": ["depot-ubuntu-latest-4"],
+ "created_at": "2026-01-20T10:00:05Z",
+ "started_at": "2026-01-20T10:00:30Z",
+ "completed_at": "2026-01-20T10:10:00Z",
+ "steps": [
+ {"name": "Set up job", "status": "completed", "conclusion": "success", "number": 1},
+ {"name": "Build", "status": "completed", "conclusion": "success", "number": 2},
+ ],
+ },
+ {
+ "id": 20002,
+ "run_id": 1001,
+ "run_attempt": 1,
+ "name": "test",
+ "status": "completed",
+ "conclusion": "success",
+ "workflow_name": "CI",
+ "head_branch": "master",
+ "runner_name": "ubuntu-latest",
+ "created_at": "2026-01-20T10:00:06Z",
+ "started_at": "2026-01-20T10:10:05Z",
+ "completed_at": "2026-01-20T10:20:00Z",
+ "steps": [
+ {"name": "Set up job", "status": "completed", "conclusion": "success", "number": 1},
+ {"name": "Run tests", "status": "completed", "conclusion": "success", "number": 2},
+ ],
+ },
+ {
+ "id": 20003,
+ "run_id": 1002,
+ "run_attempt": 1,
+ "name": "test",
+ "status": "completed",
+ "conclusion": "failure",
+ "workflow_name": "CI",
+ "head_branch": "feature/foo",
+ "runner_name": "ubuntu-latest",
+ "created_at": "2026-01-22T10:00:05Z",
+ "started_at": "2026-01-22T10:00:40Z",
+ "completed_at": "2026-01-22T10:15:00Z",
+ "steps": [
+ {"name": "Set up job", "status": "completed", "conclusion": "success", "number": 1},
+ {"name": "Run tests", "status": "completed", "conclusion": "failure", "number": 2},
+ ],
+ },
+ {
+ "id": 20004,
+ "run_id": 1003,
+ "run_attempt": 1,
+ "name": "deploy",
+ "status": "in_progress",
+ "conclusion": None,
+ "workflow_name": "Deploy",
+ "head_branch": "master",
+ "runner_name": "ubuntu-latest",
+ "created_at": "2026-01-25T10:00:05Z",
+ "started_at": "2026-01-25T10:00:20Z",
+ "completed_at": None, # still running
+ "steps": [
+ {"name": "Set up job", "status": "completed", "conclusion": "success", "number": 1},
+ {"name": "Deploy", "status": "in_progress", "conclusion": None, "number": 2},
+ ],
},
]
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 e620afd45ab2..e613354c642d 100644
--- a/posthog/temporal/tests/data_imports/github/test_github_integration.py
+++ b/posthog/temporal/tests/data_imports/github/test_github_integration.py
@@ -1,3 +1,4 @@
+import json
import uuid
from urllib.parse import parse_qs, urlparse
@@ -5,7 +6,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, WORKFLOW_RUNS
+from posthog.temporal.tests.data_imports.github.data import COMMITS, ISSUES, PULL_REQUESTS, WORKFLOW_JOBS, WORKFLOW_RUNS
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -95,6 +96,17 @@ def external_data_schema_workflow_runs_incremental(external_data_source, team):
)
+def external_data_schema_workflow_jobs_full_refresh(external_data_source, team):
+ return ExternalDataSchema.objects.create(
+ name="workflow_jobs",
+ team_id=team.pk,
+ source_id=external_data_source.pk,
+ sync_type="full_refresh",
+ sync_type_config={},
+ )
+
+
@mock.patch("posthog.temporal.data_imports.pipelines.pipeline.batcher.DEFAULT_CHUNK_SIZE", 1)
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
@@ -284,3 +296,114 @@ async def test_github_workflow_runs_incremental(
assert "sort" not in first_call_params
assert "direction" not in first_call_params
assert "state" 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_jobs_full_refresh(
+ team, mock_github_api, external_data_source, external_data_schema_workflow_jobs_full_refresh
+):
+ # workflow_jobs fans out over workflow_runs: one parent runs request, then one
+ # jobs request per run. Single sync only — cross-sync merge is the pipeline's
+ # job and is flaky to exercise in-harness, so the desc early-stop overlap is
+ # covered deterministically in test_github_source.py instead.
+ expected_num_rows = len(WORKFLOW_JOBS)
+
+ await run_external_data_job_workflow(
+ team=team,
+ external_data_source=external_data_source,
+ external_data_schema=external_data_schema_workflow_jobs_full_refresh,
+ table_name="github_workflow_jobs",
+ expected_rows_synced=expected_num_rows,
+ expected_total_rows=expected_num_rows,
+ )
+
+ api_calls = mock_github_api.get_all_api_calls()
+ # 1 parent runs page + 1 jobs request per run (3 runs).
+ assert len(api_calls) == 1 + len({job["run_id"] for job in WORKFLOW_JOBS})
+ parent_calls = [c for c in api_calls if c.url.rstrip("/").endswith("/actions/runs") or "/actions/runs?" in c.url]
+ jobs_calls = [c for c in api_calls if "/jobs" in c.url]
+ assert len(parent_calls) == 1
+ assert len(jobs_calls) == 3
+ # Every job request carries filter=all (jobs across all run_attempts) and no
+ # search-cap-tripping filters.
+ for call in jobs_calls:
+ params = parse_qs(urlparse(call.url).query)
+ assert params["filter"] == ["all"]
+ assert "created" not in params
+ assert "since" not in params
+
+
[email protected]("posthog.temporal.data_imports.pipelines.pipeline.batcher.DEFAULT_CHUNK_SIZE", 1)
[email protected]_db(transaction=True)
+async def test_github_workflow_jobs_load_bearing_fields_land_queryable(
+ team, mock_github_api, external_data_source, external_data_schema_workflow_jobs_full_refresh
+):
+ # Every column the engineering_analytics cost model reads must survive the
+ # fan-out and stay queryable. This is the full WORKFLOW_JOBS_COLUMNS contract
+ # (products/engineering_analytics/.../views/source_schema.py); a column dropped
+ # here breaks per-PR attribution (run_id/head_branch), retry analysis
+ # (run_attempt), duration/cost (started_at/completed_at), or runner-tier parsing
+ # (labels). Nested steps/labels must arrive as JSON lists, not flattened.
+ expected_num_rows = len(WORKFLOW_JOBS)
+ load_bearing_columns = [
+ "id",
+ "run_id",
+ "run_attempt",
+ "name",
+ "workflow_name",
+ "status",
+ "conclusion",
+ "head_sha",
+ "head_branch",
+ "labels",
+ "runner_name",
+ "runner_group_name",
+ "created_at",
+ "started_at",
+ "completed_at",
+ "steps",
+ ]
+
+ res = await run_external_data_job_workflow(
+ team=team,
+ external_data_source=external_data_source,
+ external_data_schema=external_data_schema_workflow_jobs_full_refresh,
+ table_name="github_workflow_jobs",
+ expected_rows_synced=expected_num_rows,
+ expected_total_rows=expected_num_rows,
+ expected_columns=load_bearing_columns,
+ )
+
+ columns = res.columns
+ assert columns is not None
+ col_idx = {name: i for i, name in enumerate(columns)}
+ rows_by_id = {row[col_idx["id"]]: row for row in res.results}
+ # Job 20001 carries the full field set, including labels + runner_group_name.
+ job = rows_by_id[20001]
+
+ def value(column: str):
+ return job[col_idx[column]]
+
+ assert value("run_id") == 1001
+ assert value("run_attempt") == 1
+ assert value("name") == "build"
+ assert value("workflow_name") == "CI"
+ assert value("status") == "completed"
+ assert value("conclusion") == "success"
+ assert value("head_sha") == "abc123"
+ assert value("head_branch") == "master"
+ assert value("runner_name") == "ubuntu-latest"
+ assert value("runner_group_name") == "GitHub Actions"
+ # Timestamps land as strings (parsed reader-side); duration = completed - started.
+ assert value("started_at") == "2026-01-20T10:00:30Z"
+ assert value("completed_at") == "2026-01-20T10:10:00Z"
+
+ # steps + labels are stored as JSON; they must round-trip as lists, not
+ # stringified scalars or dropped columns.
+ steps = json.loads(value("steps")) if isinstance(value("steps"), str) else value("steps")
+ labels = json.loads(value("labels")) if isinstance(value("labels"), str) else value("labels")
+ assert isinstance(steps, list) and len(steps) == 2
+ assert labels == ["depot-ubuntu-latest-4"]
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 d6cc1a05abf8..7d80a2de848d 100644
--- a/posthog/temporal/tests/data_imports/github/test_github_source.py
+++ b/posthog/temporal/tests/data_imports/github/test_github_source.py
@@ -1,5 +1,7 @@
+import dataclasses
from datetime import UTC, date, datetime
from typing import Any
+from urllib.parse import parse_qs, urlparse
import pytest
from unittest import mock
@@ -18,6 +20,8 @@ from posthog.temporal.data_imports.sources.github.github import (
_is_empty_repository_response,
_is_issue_not_pr,
_is_older_than_cutoff,
+ _iter_jobs_for_run,
+ _iter_pages,
_parse_next_url,
_should_stop_desc,
get_rows,
@@ -496,6 +500,17 @@ class TestGithubSourceSortMode:
datetime(2026, 1, 15, tzinfo=UTC),
"desc",
),
+ # workflow_jobs fans out over workflow_runs newest-first, so it emits
+ # desc on every sync — same as its parent.
+ ("workflow_jobs_full_refresh", "workflow_jobs", False, None, "desc"),
+ ("workflow_jobs_first_sync_no_cutoff", "workflow_jobs", True, None, "desc"),
+ (
+ "workflow_jobs_incremental_with_cutoff",
+ "workflow_jobs",
+ True,
+ datetime(2026, 1, 15, tzinfo=UTC),
+ "desc",
+ ),
]
)
def test_sort_mode(
@@ -955,3 +970,474 @@ class TestGithubSourceNonRetryableErrors:
# Mirrors the substring match done in external_data_job.update_external_data_job_model.
non_retryable_errors = self.source.get_non_retryable_errors()
assert any(pattern in error_message for pattern in non_retryable_errors) == expected_match
+
+
+class _RoutingSession:
+ """Routes GitHub GET calls by URL so two-level runs->jobs fan-out can be mocked
+ without depending on request order. Records every requested URL."""
+
+ def __init__(
+ self,
+ runs_pages: list[tuple[Any, str]],
+ jobs_by_run: dict[int, tuple[Any, str]],
+ ) -> None:
+ self._runs_pages = list(runs_pages)
+ self._jobs_by_run = jobs_by_run
+ self.calls: list[str] = []
+
+ def get(self, url: str, headers: Any = None, timeout: Any = None) -> Any:
+ self.calls.append(url)
+ if "/jobs" in url:
+ run_id = int(urlparse(url).path.split("/")[-2])
+ body, link = self._jobs_by_run.get(run_id, ({"total_count": 0, "jobs": []}, ""))
+ return _make_response(body=body, link=link)
+ body, link = self._runs_pages.pop(0)
+ return _make_response(body=body, link=link)
+
+
+def _run(created_at: str, run_id: int) -> dict[str, Any]:
+ return {"id": run_id, "created_at": created_at}
+
+
+def _runs_envelope(*runs: dict[str, Any]) -> dict[str, Any]:
+ return {"total_count": len(runs), "workflow_runs": list(runs)}
+
+
+def _jobs_envelope(*jobs: dict[str, Any]) -> dict[str, Any]:
+ return {"total_count": len(jobs), "jobs": list(jobs)}
+
+
+class TestFanOutJobs:
+ """workflow_jobs fans out over workflow_runs and emits each run's jobs."""
+
+ def _patch_batcher(self) -> Any:
+ return mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.Batcher",
+ autospec=False,
+ side_effect=lambda logger, chunk_size, chunk_size_bytes: _ImmediateBatcher(),
+ )
+
+ def _fan_out(self, session: _RoutingSession, **kwargs: Any) -> list[Any]:
+ with (
+ self._patch_batcher(),
+ mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ return_value=session,
+ ),
+ ):
+ return list(
+ get_rows(
+ personal_access_token="tok",
+ repository="owner/repo",
+ endpoint="workflow_jobs",
+ logger=mock.Mock(),
+ resumable_source_manager=_make_manager(),
+ **kwargs,
+ )
+ )
+
+ def test_each_job_carries_run_id_and_nested_steps(self) -> None:
+ session = _RoutingSession(
+ runs_pages=[(_runs_envelope(_run("2026-01-22T00:00:00Z", 1002), _run("2026-01-20T00:00:00Z", 1001)), "")],
+ jobs_by_run={
+ 1002: (
+ _jobs_envelope(
+ {
+ "id": 3,
+ "run_id": 1002,
+ "steps": [{"name": "test", "number": 1}],
+ "labels": ["depot-ubuntu-latest-4"],
+ }
+ ),
+ "",
+ ),
+ 1001: (
+ _jobs_envelope(
+ {"id": 1, "run_id": 1001, "steps": [{"name": "build", "number": 1}], "labels": []},
+ {"id": 2, "run_id": 1001, "steps": []},
+ ),
+ "",
+ ),
+ },
+ )
+
+ rows = self._fan_out(session, should_use_incremental_field=False)
+
+ assert [row["id"] for row in rows] == [3, 1, 2]
+ assert all("run_id" in row for row in rows)
+ # steps[] and labels[] are yielded nested (lists), not pre-flattened or
+ # stringified — the pipeline JSON-serializes them on write.
+ assert rows[0]["steps"] == [{"name": "test", "number": 1}]
+ assert rows[0]["labels"] == ["depot-ubuntu-latest-4"]
+ assert isinstance(rows[1]["steps"], list)
+ assert isinstance(rows[1]["labels"], list)
+
+ def test_child_request_uses_filter_all_and_per_page_only(self) -> None:
+ session = _RoutingSession(
+ runs_pages=[(_runs_envelope(_run("2026-01-20T00:00:00Z", 1001)), "")],
+ jobs_by_run={1001: (_jobs_envelope({"id": 1, "run_id": 1001}), "")},
+ )
+
+ self._fan_out(session, should_use_incremental_field=False)
+
+ jobs_calls = [c for c in session.calls if "/jobs" in c]
+ assert len(jobs_calls) == 1
+ assert "/repos/owner/repo/actions/runs/1001/jobs" in jobs_calls[0]
+ params = parse_qs(urlparse(jobs_calls[0]).query)
+ assert params["filter"] == ["all"]
+ assert params["per_page"] == ["100"]
+ # No params that would trip the parent's 1,000-result search cap or are
+ # unsupported on the jobs endpoint.
+ assert "since" not in params
+ assert "created" not in params
+ assert "sort" not in params
+ assert "state" not in params
+
+ def test_null_jobs_envelope_does_not_crash_or_truncate(self) -> None:
+ session = _RoutingSession(
+ runs_pages=[(_runs_envelope(_run("2026-01-22T00:00:00Z", 1002), _run("2026-01-20T00:00:00Z", 1001)), "")],
+ jobs_by_run={
+ 1002: ({"total_count": 0, "jobs": None}, ""), # run with no jobs yet
+ 1001: (_jobs_envelope({"id": 1, "run_id": 1001}), ""),
+ },
+ )
+
+ rows = self._fan_out(session, should_use_incremental_field=False)
+
+ # Empty/null envelope for one run contributes nothing; the other run's
+ # jobs still land.
+ assert [row["id"] for row in rows] == [1]
+
+ def test_incremental_fans_out_only_runs_at_or_above_cutoff(self) -> None:
+ cutoff = datetime(2026, 1, 22, tzinfo=UTC)
+ # Runs are newest-first. 1003 is above the cutoff; 1001 is below it.
+ session = _RoutingSession(
+ runs_pages=[(_runs_envelope(_run("2026-01-25T00:00:00Z", 1003), _run("2026-01-20T00:00:00Z", 1001)), "")],
+ jobs_by_run={
+ 1003: (_jobs_envelope({"id": 9, "run_id": 1003}), ""),
+ 1001: (_jobs_envelope({"id": 1, "run_id": 1001}), ""),
+ },
+ )
+
+ rows = self._fan_out(
+ session,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=cutoff,
+ incremental_field="created_at",
+ )
+
+ # Only the run above the cutoff is fanned out; the older run is skipped
+ # entirely — no jobs request is made for it.
+ assert [row["id"] for row in rows] == [9]
+ jobs_calls = [c for c in session.calls if "/jobs" in c]
+ assert any("/runs/1003/jobs" in c for c in jobs_calls)
+ assert not any("/runs/1001/jobs" in c for c in jobs_calls)
+
+ def test_first_incremental_sync_floors_fan_out_to_lookback_window(self) -> None:
+ # First incremental sync (watermark configured, nothing synced yet): the
+ # backfill is floored at settings' initial_lookback_days instead of crawling
+ # all history. Runs are newest-first; 1003 lands a day before the frozen now
+ # (inside any small window) and 1001 over a month back (outside).
+ frozen_now = datetime(2026, 2, 20, tzinfo=UTC)
+ session = _RoutingSession(
+ runs_pages=[(_runs_envelope(_run("2026-02-19T00:00:00Z", 1003), _run("2026-01-10T00:00:00Z", 1001)), "")],
+ jobs_by_run={
+ 1003: (_jobs_envelope({"id": 9, "run_id": 1003}), ""),
+ 1001: (_jobs_envelope({"id": 1, "run_id": 1001}), ""),
+ },
+ )
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.github.github._now_utc",
+ return_value=frozen_now,
+ ):
+ rows = self._fan_out(
+ session,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+
+ # Only the run inside the lookback window is fanned out; the older one is
+ # skipped without a jobs request.
+ assert [row["id"] for row in rows] == [9]
+ jobs_calls = [c for c in session.calls if "/jobs" in c]
+ assert any("/runs/1003/jobs" in c for c in jobs_calls)
+ assert not any("/runs/1001/jobs" in c for c in jobs_calls)
+
+ def test_resume_starts_from_saved_parent_page_url(self) -> None:
+ saved_url = "https://api.github.com/repos/owner/repo/actions/runs?per_page=100&page=3"
+ manager = _make_manager(can_resume=True, resume_state=GithubResumeConfig(next_url=saved_url))
+ session = _RoutingSession(
+ runs_pages=[(_runs_envelope(_run("2026-01-20T00:00:00Z", 1001)), "")],
+ jobs_by_run={1001: (_jobs_envelope({"id": 1, "run_id": 1001}), "")},
+ )
+
+ with (
+ self._patch_batcher(),
+ mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ return_value=session,
+ ),
+ ):
+ list(
+ get_rows(
+ personal_access_token="tok",
+ repository="owner/repo",
+ endpoint="workflow_jobs",
+ logger=mock.Mock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=False,
+ )
+ )
+
+ assert session.calls[0] == saved_url
+ manager.load_state.assert_called_once()
+
+
+class TestIterPages:
+ """Generic paginator shared by the fan-out: envelope unwrap, Link following,
+ and the per-parent page cap."""
+
+ def test_unwraps_envelope_and_follows_link(self) -> None:
+ responses = [
+ _make_response(
+ body={"total_count": 3, "jobs": [{"id": 1}]},
+ link='<https://api.github.com/x?page=2>; rel="next"',
+ ),
+ _make_response(body={"total_count": 3, "jobs": [{"id": 2}]}, link=""),
+ ]
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ ) as mock_get:
+ mock_get.return_value.get.side_effect = responses
+ pages = list(_iter_pages("https://api.github.com/x", {}, "jobs", mock.Mock()))
+
+ assert [items for items, _url in pages] == [[{"id": 1}], [{"id": 2}]]
+
+ @parameterized.expand(
+ [
+ ("null_body", {"total_count": 0, "jobs": None}),
+ ("empty_dict", {}),
+ ("empty_list", {"total_count": 0, "jobs": []}),
+ ]
+ )
+ def test_empty_or_null_envelope_yields_no_pages(self, _name: str, body: Any) -> None:
+ with 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=body, link="")]
+ pages = list(_iter_pages("https://api.github.com/x", {}, "jobs", mock.Mock()))
+
+ assert pages == []
+
+ def test_page_cap_stops_and_logs(self) -> None:
+ # Every page links to a next page; the cap must halt pagination.
+ responses = [
+ _make_response(body={"jobs": [{"id": i}]}, link='<https://api.github.com/x?page=n>; rel="next"')
+ for i in range(5)
+ ]
+ logger = mock.Mock()
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ ) as mock_get:
+ mock_get.return_value.get.side_effect = responses
+ pages = list(
+ _iter_pages(
+ "https://api.github.com/x",
+ {},
+ "jobs",
+ logger,
+ max_pages=2,
+ page_cap_context={"repository": "owner/repo", "run_id": 1001},
+ )
+ )
+
+ assert len(pages) == 2
+ logger.warning.assert_called_once()
+ assert logger.warning.call_args.kwargs["max_pages"] == 2
+ assert logger.warning.call_args.kwargs["run_id"] == 1001
+
+ def test_iter_jobs_for_run_builds_path_and_passes_cap(self) -> None:
+ config = dataclasses.replace(GITHUB_ENDPOINTS["workflow_jobs"], max_pages_per_parent=1)
+ responses = [
+ _make_response(
+ body=_jobs_envelope({"id": 1, "run_id": 1001}),
+ link='<https://api.github.com/x?page=2>; rel="next"',
+ ),
+ ]
+ logger = mock.Mock()
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ ) as mock_get:
+ mock_get.return_value.get.side_effect = responses
+ jobs = list(_iter_jobs_for_run("owner/repo", 1001, {}, logger, config))
+
+ assert [job["id"] for job in jobs] == [1]
+ url = mock_get.return_value.get.call_args_list[0].args[0]
+ assert "/repos/owner/repo/actions/runs/1001/jobs" in url
+ assert "filter=all" in url
+ # Cap of 1 page reached (a next link exists) → warning emitted.
+ logger.warning.assert_called_once()
+
+
+def _pat_config() -> GithubSourceConfig:
+ return GithubSourceConfig(
+ auth_method=GithubAuthMethodConfig(selection="pat", personal_access_token="test-token"),
+ repository="owner/repo",
+ )
+
+
+class TestGithubWebhookSource:
+ """The WebhookSource surface: event mapping, schema flags, and the create/
+ delete/info round-trips that mint and reconcile the repo webhook."""
+
+ def setup_method(self) -> None:
+ self.source = GithubSource()
+
+ def test_webhook_resource_map(self) -> None:
+ assert self.source.webhook_resource_map == {
+ "workflow_jobs": "workflow_job",
+ "workflow_runs": "workflow_run",
+ }
+
+ def test_webhook_template_identity(self) -> None:
+ template = self.source.webhook_template
+ assert template is not None
+ assert template.id == "template-warehouse-source-github"
+ assert template.type == "warehouse_source_webhook"
+
+ def test_get_schemas_marks_only_workflow_schemas_webhook_capable(self) -> None:
+ schemas = self.source.get_schemas(_pat_config(), team_id=1)
+ webhook_capable = {s.name for s in schemas if s.supports_webhooks}
+ assert webhook_capable == {"workflow_jobs", "workflow_runs"}
+
+ @parameterized.expand(
+ [
+ ("both", ["workflow_jobs", "workflow_runs"], ["workflow_job", "workflow_run"]),
+ ("jobs_only", ["workflow_jobs"], ["workflow_job"]),
+ ("drops_non_webhook_schemas", ["workflow_jobs", "issues", "commits"], ["workflow_job"]),
+ ]
+ )
+ def test_get_desired_webhook_events(self, _name: str, eligible: list[str], expected_events: list[str]) -> None:
+ assert self.source.get_desired_webhook_events(_pat_config(), eligible) == expected_events
+
+ def test_create_webhook_sends_secret_and_returns_it_as_extra_input(self) -> None:
+ captured: dict[str, Any] = {}
+
+ def post(url: str, headers: Any = None, json: Any = None, timeout: Any = None) -> Any:
+ captured["url"] = url
+ captured["json"] = json
+ return _make_response(status=201, body={"id": 99})
+
+ session = mock.Mock()
+ session.post.side_effect = post
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ return_value=session,
+ ):
+ result = self.source.create_webhook(_pat_config(), "https://app.posthog.com/webhook", team_id=1)
+
+ assert "/repos/owner/repo/hooks" in captured["url"]
+ sent_secret = captured["json"]["config"]["secret"]
+ assert sent_secret # a non-empty secret is minted and handed to GitHub
+ assert result.success is True
+ # GitHub never echoes the secret, so create_webhook returns the minted one
+ # for the framework to persist as the hog function's signing_secret.
+ assert result.extra_inputs["signing_secret"] == sent_secret
+
+ def test_create_webhook_permission_error_falls_back_to_manual(self) -> None:
+ session = mock.Mock()
+ session.post.return_value = _make_response(status=403, body={"message": "Forbidden"})
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ return_value=session,
+ ):
+ result = self.source.create_webhook(_pat_config(), "https://app.posthog.com/webhook", team_id=1)
+
+ assert result.success is False
+ assert result.error is not None
+ assert "admin:repo_hook" in result.error
+
+ def test_delete_webhook_lists_then_deletes_matching_hook(self) -> None:
+ webhook_url = "https://app.posthog.com/webhook"
+ session = mock.Mock()
+ session.get.return_value = _make_response(status=200, body=[{"id": 42, "config": {"url": webhook_url}}])
+ session.delete.return_value = _make_response(status=204)
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ return_value=session,
+ ):
+ result = self.source.delete_webhook(_pat_config(), webhook_url, team_id=1)
+
+ assert result.success is True
+ delete_url = session.delete.call_args.args[0]
+ assert "/repos/owner/repo/hooks/42" in delete_url
+
+ def test_get_external_webhook_info_reports_existing_hook(self) -> None:
+ webhook_url = "https://app.posthog.com/webhook"
+ session = mock.Mock()
+ session.get.return_value = _make_response(
+ status=200,
+ body=[
+ {
+ "id": 42,
+ "active": True,
+ "events": ["workflow_job", "workflow_run"],
+ "config": {"url": webhook_url},
+ "created_at": "2026-01-01T00:00:00Z",
+ }
+ ],
+ )
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ return_value=session,
+ ):
+ info = self.source.get_external_webhook_info(_pat_config(), webhook_url, team_id=1)
+
+ assert info.exists is True
+ assert info.url == webhook_url
+ assert info.status == "active"
+ assert info.enabled_events == ["workflow_job", "workflow_run"]
+
+ def test_delete_webhook_treats_404_as_success(self) -> None:
+ # The hook is found in the list but DELETE races a concurrent removal and
+ # 404s — the desired end state, so it must not surface as a permission error.
+ webhook_url = "https://app.posthog.com/webhook"
+ session = mock.Mock()
+ session.get.return_value = _make_response(status=200, body=[{"id": 42, "config": {"url": webhook_url}}])
+ session.delete.return_value = _make_response(status=404, body={"message": "Not Found"})
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ return_value=session,
+ ):
+ result = self.source.delete_webhook(_pat_config(), webhook_url, team_id=1)
+
+ assert result.success is True
+ assert result.error is None
+
+ def test_get_external_webhook_info_skips_hook_with_null_config(self) -> None:
+ # A hook whose `config` is present-but-null must be skipped, not crash the
+ # match loop — the real hook still resolves.
+ webhook_url = "https://app.posthog.com/webhook"
+ session = mock.Mock()
+ session.get.return_value = _make_response(
+ status=200,
+ body=[
+ {"id": 7, "config": None},
+ {"id": 42, "active": True, "events": ["workflow_job"], "config": {"url": webhook_url}},
+ ],
+ )
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.github.github.make_tracked_session",
+ return_value=session,
+ ):
+ info = self.source.get_external_webhook_info(_pat_config(), webhook_url, team_id=1)
+
+ assert info.exists is True
+ assert info.url == webhook_url