:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse): dedupe github webhook batches to latest state per id (#66296)
Julian Bezfb688169ae2f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.pyindex 0aba3346241f..086dd6f8ec86 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py@@ -69,9 +69,12 @@ class WebhookSourceManager:try:ls_res = await s3._ls(prefix, detail=True)ls_values = ls_res.values() if isinstance(ls_res, dict) else ls_res- files = [- f"s3://{f['Key']}" for f in ls_values if f["type"] != "directory" and f["Key"].endswith(".parquet")- ]+ entries = [f for f in ls_values if f["type"] != "directory" and f["Key"].endswith(".parquet")]+ # Read oldest-first (by S3 mtime, Key as a stable tiebreak) so a key's events reach+ # the loader in arrival order. The leading `is None` flag sends entries without a+ # LastModified to the end without ever comparing None to a timestamp.+ entries.sort(key=lambda f: (f.get("LastModified") is None, f.get("LastModified"), f["Key"]))+ files = [f"s3://{f['Key']}" for f in entries]await self._logger.adebug("list_webhook_parquet_files", prefix=prefix, file_count=len(files))@@ -90,6 +93,13 @@ class WebhookSourceManager:await self._logger.adebug(f"Webhook source reading {len(files)} files")+ def finalize_batch(tables: list[pa.Table]) -> pa.Table:+ # Dedupe across the whole concatenated batch, not per file: a yielded batch can span+ # several S3 files, and the same id (e.g. a run's queued/completed events) can land in+ # different files. A per-file pass would let both survive into one batch.+ merged = pa.concat_tables(tables, promote_options="permissive")+ return table_transformer(merged) if table_transformer else merged+batch_tables: list[pa.Table] = []batch_paths: list[str] = []batch_rows = 0@@ -112,16 +122,13 @@ class WebhookSourceManager:table = self._transform_webhook_table(table)- if table_transformer:- table = table_transformer(table)-batch_tables.append(table)batch_paths.append(path)batch_rows += table.num_rowsbatch_bytes += table.nbytesif batch_rows >= batch_row_limit or batch_bytes >= batch_byte_limit:- merged = pa.concat_tables(batch_tables, promote_options="permissive")+ merged = finalize_batch(batch_tables)await self._logger.adebug("webhook_batch_yield",file_count=len(batch_paths),@@ -140,7 +147,7 @@ class WebhookSourceManager:# Yield any remaining rowsif batch_tables:- merged = pa.concat_tables(batch_tables, promote_options="permissive")+ merged = finalize_batch(batch_tables)await self._logger.adebug("webhook_batch_yield",file_count=len(batch_paths),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.pyindex 905a15830292..6f25759185e8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py@@ -6,6 +6,7 @@ from datetime import UTC, date, datetime, timedeltafrom typing import Any, Literal, Optionalfrom urllib.parse import urlencode+import pyarrow as paimport requestsfrom asgiref.sync import async_to_syncfrom dateutil import parser as dateutil_parser@@ -623,6 +624,47 @@ def get_rows(yield py_table+def _make_webhook_dedupe_transformer(primary_key: str, version_keys: list[str]) -> Callable[[pa.Table], pa.Table]:+ """Collapse a webhook batch to one row per ``primary_key`` — the one ranking newest by+ ``version_keys`` (newest first, NULLs last). GitHub emits a single run/job as separate+ queued -> in_progress -> completed events sharing an id, and the delta merge doesn't dedupe+ within a source batch, so without this it keeps whichever event landed last in batch order and+ freezes rows pre-completion. Same problem and same fix as the Stripe webhook source."""++ def transform(table: pa.Table) -> pa.Table:+ present_version_keys = [key for key in version_keys if key in table.column_names]+ if table.num_rows == 0 or primary_key not in table.column_names or not present_version_keys:+ return table++ ids = table.column(primary_key).to_pylist()+ version_columns = [table.column(key).to_pylist() for key in present_version_keys]++ def rank(row_index: int) -> tuple[tuple[int, Any], ...]:+ # A present value beats NULL (NULLS LAST); among present values a larger one is newer+ # (ISO-8601 timestamps compare correctly as strings). The leading flag keeps NULLs from+ # ever being order-compared against a real value.+ return tuple(+ (1, column[row_index]) if column[row_index] is not None else (0, "") for column in version_columns+ )++ best_index_by_id: dict[Any, int] = {}+ for index, object_id in enumerate(ids):+ if object_id is None:+ continue+ best = best_index_by_id.get(object_id)+ # On a tie (>=, not >) the later-arriving row wins. GitHub timestamps are second-coarse,+ # so a fast in_progress -> completed transition can share an updated_at; rows arrive in+ # chronological order (files read oldest-first), so the later index is the newer event.+ if best is None or rank(index) >= rank(best):+ best_index_by_id[object_id] = index++ # Preserve input order among the survivors so the batch stays in arrival order. The indices+ # are an explicit int64 array so an empty result doesn't infer a null-typed index array.+ return table.take(pa.array(sorted(best_index_by_id.values()), type=pa.int64()))++ return transform++def github_source(personal_access_token: str,repository: str,@@ -665,7 +707,16 @@ def github_source(# 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()+ #+ # Each event for an id arrives as its own row (queued -> in_progress -> completed);+ # collapse them to the latest per id here, since the delta merge doesn't dedupe a+ # source batch. Same pattern as the Stripe webhook source.+ transformer = (+ _make_webhook_dedupe_transformer(endpoint_config.primary_key, endpoint_config.version_keys)+ if endpoint_config.version_keys+ else None+ )+ return webhook_source_manager.get_items(table_transformer=transformer)return get_rows(personal_access_token=personal_access_token,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.pyindex e0d3fc714aff..1ec3d83eabff 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py@@ -14,6 +14,12 @@ class GithubEndpointConfig:page_size: int = 100 # GitHub default, max is 100sort_mode: Literal["asc", "desc"] = "asc"primary_key: str = "id" # Primary key for upsert operations+ # Ordered columns (compared newest-first, NULLs last) that rank webhook events sharing a+ # primary key, so the source collapses a batch to the latest state per id before it reaches the+ # delta merge (which doesn't dedupe within a batch). GitHub emits one run/job as separate+ # queued -> in_progress -> completed events; without this the merge keeps whichever landed last+ # in batch order, freezing rows pre-completion. None = no webhook dedup (poll-only endpoints).+ version_keys: Optional[list[str]] = None# 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.@@ -133,6 +139,9 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {default_incremental_field="created_at",sort_mode="desc", # API always returns newest-first; sort/direction are ignoredresponse_data_path="workflow_runs",+ # workflow_run carries updated_at, which GitHub bumps on every status change — the natural+ # recency key so a completed run is never frozen by a stale earlier webhook event.+ version_keys=["updated_at"],),"workflow_jobs": GithubEndpointConfig(name="workflow_jobs",@@ -174,6 +183,10 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {# window since the latest job. Repos that genuinely want history should run a# deliberate one-off backfill, not pay for it on every connect.initial_lookback_days=0,+ # workflow_job has no updated_at, so rank by how far the job progressed: completed_at+ # (terminal) outranks started_at (running) outranks created_at (queued). Each is NULL until+ # the job reaches that stage, so NULLs-last ordering keeps the latest state.+ version_keys=["completed_at", "started_at", "created_at"],),}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_dedupe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_dedupe.pynew file mode 100644index 000000000000..43e26ec2a25e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_dedupe.py@@ -0,0 +1,105 @@+from typing import Any++import pyarrow as pa++from products.warehouse_sources.backend.temporal.data_imports.sources.github.github import (+ _make_webhook_dedupe_transformer,+)++_JOB_VERSION_KEYS = ["completed_at", "started_at", "created_at"]+_JOB_FIELDS: dict[str, pa.DataType] = {+ "id": pa.int64(),+ "status": pa.string(),+ "completed_at": pa.string(),+ "started_at": pa.string(),+ "created_at": pa.string(),+}+_JOB_SCHEMA = pa.schema(_JOB_FIELDS)+++def _job(+ id: int, status: str, *, created: str, started: str | None = None, completed: str | None = None+) -> dict[str, Any]:+ return {"id": id, "status": status, "created_at": created, "started_at": started, "completed_at": completed}+++def _dedupe(rows: list[dict[str, Any]], *, version_keys: list[str] = _JOB_VERSION_KEYS) -> list[dict[str, Any]]:+ table = pa.table({name: [row.get(name) for row in rows] for name in _JOB_SCHEMA.names}, schema=_JOB_SCHEMA)+ out = _make_webhook_dedupe_transformer("id", version_keys)(table)+ return [{name: out.column(name)[i].as_py() for name in out.column_names} for i in range(out.num_rows)]+++def test_keeps_completed_when_whole_lifecycle_lands_in_one_batch() -> None:+ # The completed event is deliberately not last in the batch — ranking, not order, must win.+ rows = _dedupe(+ [+ _job(1, "queued", created="t0"),+ _job(1, "completed", created="t0", started="t1", completed="t2"),+ _job(1, "in_progress", created="t0", started="t1"),+ ]+ )+ assert rows == [_job(1, "completed", created="t0", started="t1", completed="t2")]+++def test_keeps_newer_intermediate_event_when_neither_is_completed() -> None:+ # Both pre-completion (completed_at NULL): the later started_at must win, so a terminal-only+ # comparison wouldn't be enough — the full version tuple decides.+ rows = _dedupe(+ [+ _job(1, "in_progress", created="t0", started="t5"),+ _job(1, "in_progress", created="t0", started="t3"),+ ]+ )+ assert rows == [_job(1, "in_progress", created="t0", started="t5")]+++def test_one_row_per_id_in_arrival_order() -> None:+ rows = _dedupe(+ [+ _job(1, "completed", created="a0", started="a1", completed="a2"),+ _job(2, "queued", created="b0"),+ _job(1, "queued", created="a0"),+ ]+ )+ assert [row["id"] for row in rows] == [1, 2]+ assert rows[0]["status"] == "completed"+++def test_drops_rows_with_null_id() -> None:+ rows = _dedupe([{"id": None, "status": "queued", "created_at": "t0", "started_at": None, "completed_at": None}])+ assert rows == []+++def test_equal_version_keys_keep_later_arrival() -> None:+ # GitHub's second-coarse updated_at can be identical for a fast in_progress -> completed+ # transition; the later-arriving completed event must win, so a strict > would freeze the row.+ table = pa.table(+ {+ "id": [1, 1],+ "status": ["in_progress", "completed"],+ "updated_at": ["2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z"],+ }+ )+ out = _make_webhook_dedupe_transformer("id", ["updated_at"])(table)+ assert out.num_rows == 1+ assert out.column("status")[0].as_py() == "completed"+++def test_single_version_key_keeps_max() -> None:+ # workflow_runs ranks on updated_at alone.+ table = pa.table(+ {+ "id": [1, 1],+ "status": ["in_progress", "completed"],+ "updated_at": ["2026-01-01T00:00:00Z", "2026-01-01T00:05:00Z"],+ }+ )+ out = _make_webhook_dedupe_transformer("id", ["updated_at"])(table)+ assert out.num_rows == 1+ assert out.column("status")[0].as_py() == "completed"+++def test_returns_table_unchanged_when_version_columns_absent() -> None:+ table = pa.table({"id": [1, 1], "status": ["queued", "in_progress"]})+ out = _make_webhook_dedupe_transformer("id", _JOB_VERSION_KEYS)(table)+ assert out.num_rows == 2