:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse-sources): stop a Decagon walk reporting success with no rows (#98910)
posthog[bot]383daa97dfdd
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/decagon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/decagon.pyindex ac2185e69ef3..e82100b39a83 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/decagon.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/decagon.py@@ -48,6 +48,16 @@ class DecagonRetryableError(Exception):pass+# Stable opening of the DecagonContractError message. The rest of the message names the+# endpoint and the reported total, so `DecagonSource.get_non_retryable_errors` needs a fixed+# fragment to match the failure on.+CONTRACT_MISMATCH_ERROR = "Decagon imported no rows against a nonzero reported total"+++class DecagonContractError(Exception):+ """The response does not match the contract the endpoint is configured against."""++@dataclasses.dataclassclass DecagonResumeConfig:# Position of the next unfetched page, one field per pagination mode: the next-page@@ -113,6 +123,34 @@ def _incremental_window_value(config: DecagonEndpointConfig, value: Any) -> intreturn _to_epoch_seconds(value)+def _resolve_items(+ data: dict[str, Any], config: DecagonEndpointConfig, endpoint: str, logger: FilteringBoundLogger+) -> list[Any]:+ """Read the row list out of a response envelope.++ Decagon renames envelope fields between doc revisions (the conversations export alone+ documents three names for one cursor field), and a lookup that misses reads as an+ empty page, which ends the walk and reports success. So fall back to the response's+ only list when the configured key is absent.+ """+ items = data.get(config.data_key)+ if isinstance(items, list):+ return items++ list_keys = [key for key, value in data.items() if isinstance(value, list)]+ if len(list_keys) == 1:+ logger.warning(+ f"Decagon: {endpoint} response carries no '{config.data_key}' list; reading rows from "+ f"'{list_keys[0]}' instead (response keys: {sorted(data.keys())})"+ )+ return data[list_keys[0]]++ logger.warning(+ f"Decagon: {endpoint} response carries no '{config.data_key}' list (response keys: {sorted(data.keys())})"+ )+ return []++def _next_cursor(data: dict[str, Any], cursor_keys: tuple[str, ...]) -> Optional[str]:# Skip falsy values rather than returning the first key present: a response that# carries `next_page_cursor: null` alongside a populated alias must keep paginating.@@ -198,6 +236,12 @@ def get_rows(# refresh trues the table up.window_value += 1+ # True when a real watermark bounds the request. A windowed walk can legitimately keep no+ # rows, so the contract guard at the end of the walk must not fire for it. Read before the+ # mandatory-bound fallback below, because an epoch bound includes every row: a walk under it+ # that keeps nothing carries the same mismatch signal as a walk with no bound at all.+ windowed_by_watermark = window_value is not None+if window_value is None and config.incremental_param and config.incremental_param_required:# No prior state and no watermark left the window unset, but this endpoint 400s# on a request that omits the bound entirely. The epoch keeps a full walk honest@@ -266,6 +310,9 @@ def get_rows(set() if config.primary_keys is not None and not should_use_incremental_field else None)+ saw_rows = False+ reported_total: Any = None+while True:params: dict[str, str] = dict(config.extra_params)if config.pagination == "cursor":@@ -286,7 +333,7 @@ def get_rows(params[config.timestamp_filter_param] = timestamp_filterdata = fetch_page_with_optional(params)- items = data.get(config.data_key) or []+ items = _resolve_items(data, config, endpoint, logger)fresh: list[dict[str, Any]] = []for item in items:@@ -301,6 +348,8 @@ def get_rows(seen_keys.add(key)fresh.append(item)+ saw_rows = saw_rows or bool(fresh)+if config.pagination == "single":if fresh:yield fresh@@ -336,6 +385,7 @@ def get_rows(continuetotal = data.get(config.total_key) if config.total_key else None+ reported_total = totalif config.pagination == "page":# Terminate against the reported total using rows actually kept: a row that@@ -376,6 +426,21 @@ def get_rows(breakoffset = next_offset+ # A walk that read every row of the endpoint and kept none, while the endpoint itself+ # reports rows, means the response no longer matches this config. Fail the sync: the+ # alternative is the table reporting success forever and never holding a row.+ if (+ not saw_rows+ and resume_config is None+ and not windowed_by_watermark+ and isinstance(reported_total, int | float)+ and reported_total > 0+ ):+ raise DecagonContractError(+ f"{CONTRACT_MISMATCH_ERROR}: {endpoint} reports {reported_total} rows and the walk kept none. "+ f"Check the response envelope against the endpoint config."+ )+# Walked to completion, so drop any checkpoint: a retried attempt of this job would# otherwise resume at the final page and append its rows again.resumable_source_manager.clear_state()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/source.pyindex f3631e72191b..86084e3cb6be 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/source.py@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.decagon.decagon import (+ CONTRACT_MISMATCH_ERROR,DecagonResumeConfig,decagon_source,validate_credentials as validate_decagon_credentials,@@ -99,6 +100,15 @@ You can find your API key on the **Developer** page of the [Decagon dashboard](h"every table is failing, generate a new key on the Developer page of the Decagon ""dashboard and reconnect."),+ # The walk read the endpoint and kept nothing while the endpoint reported rows, so+ # the response no longer matches the config this source ships. Every attempt repeats+ # the same request and fails the same way, so retrying only multiplies the reports+ # and leaves the schema enabled to repeat it on the next schedule.+ CONTRACT_MISMATCH_ERROR: (+ "Decagon reports rows for this table, but PostHog could not read any of them. This "+ "is not a problem with your API key. Contact support so we can update the sync to "+ "match what Decagon now sends."+ ),}def get_retryable_errors(self) -> set[str]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon.pyindex c8b74b737cd9..ee6a6a754a8a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon.py@@ -8,9 +8,11 @@ from unittest.mock import MagicMock, patchfrom parameterized import parameterizedfrom requests import HTTPError, Response+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.decagon.decagon import (DECAGON_BASE_URL,+ DecagonContractError,DecagonResumeConfig,_to_epoch_seconds,decagon_source,@@ -21,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.decagon.seDECAGON_ENDPOINTS,DecagonEndpointConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.decagon.source import DecagonSourceDECAGON_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.decagon.decagon"SETTINGS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.decagon.settings"@@ -584,6 +587,36 @@ class TestArticleTables:assert len(sent_params) == 2assert [[r["id"] for r in b] for b in batches] == [[1, 2]]+ def test_rows_are_read_from_the_response_only_list_when_the_configured_key_is_absent(self) -> None:+ # A renamed envelope key otherwise reads as an empty page: the walk ends on the+ # first request and the sync reports success with an empty table.+ manager = _fresh_manager()+ responses = [_make_response({"data": [{"id": 1}, {"id": 2}], "total": 2})]+ _, batches = _drive_rows(manager, responses, endpoint="articles")++ assert [[r["id"] for r in b] for b in batches] == [[1, 2]]++ def test_no_rows_against_a_nonzero_total_fails_the_sync(self) -> None:+ # The endpoint reports articles and the walk kept none, so the config no longer+ # matches the response. Completing here is what kept the table empty silently.+ manager = _fresh_manager()+ responses = [_make_response({"unexpected": {"id": 1}, "total": 12})]++ with pytest.raises(DecagonContractError) as excinfo:+ _drive_rows(manager, responses, endpoint="articles")++ # The failure is deterministic, so the source must classify the message it actually+ # raises. An unclassified message repeats this identical request for the whole attempt+ # budget, reports it every time, and leaves the schema enabled for the next schedule.+ assert error_message_matches(str(excinfo.value), DecagonSource().get_non_retryable_errors())++ def test_an_empty_knowledge_base_still_completes(self) -> None:+ manager = _fresh_manager()+ responses = [_make_response({"articles": [], "total": 0})]+ _, batches = _drive_rows(manager, responses, endpoint="articles")++ assert batches == []+def test_article_usage_is_a_single_request_pinned_to_utc(self) -> None:# The timezone param changes how usage is bucketed; leaving it to the account# default would let a dashboard setting silently shift the numbers.@@ -690,6 +723,44 @@ class TestAdminLogs:]assert [len(b) for b in batches] == [2, 1]+ @parameterized.expand(+ [+ ("full_refresh", {}),+ (+ "first_incremental_run_without_watermark",+ {"should_use_incremental_field": True, "incremental_field": "created_at"},+ ),+ ]+ )+ def test_no_rows_against_a_nonzero_total_fails_the_sync(+ self, _name: str, incremental_kwargs: dict[str, Any]+ ) -> None:+ # The mandatory `start` bound is the epoch in both modes, so the request covered every+ # row and keeping none against a positive total means the envelope no longer matches.+ # The bound must not read as a server-side window and excuse the empty walk.+ manager = _fresh_manager()+ responses = [_make_response({"unexpected": {"id": "a1"}, "total": 12})]++ with pytest.raises(DecagonContractError):+ _drive_rows(manager, responses, endpoint="admin_logs", **incremental_kwargs)++ def test_a_watermarked_walk_that_finds_nothing_new_still_completes(self) -> None:+ # `total` counts the whole table, not the window, so an incremental run with nothing+ # new past the watermark keeps no rows against a positive total. That is the ordinary+ # result and must stay a success.+ manager = _fresh_manager()+ responses = [_make_response({"admin_logs": [], "total": 12})]+ _, batches = _drive_rows(+ manager,+ responses,+ endpoint="admin_logs",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 15, 12, 0, 5, tzinfo=UTC),+ incremental_field="created_at",+ )++ assert batches == []+def test_response_merges_on_id_partitioned_by_created_at(self) -> None:response = decagon_source(api_key="key",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon_source.pyindex da268e54253d..7ce31097b02e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon_source.py@@ -115,6 +115,12 @@ class TestDecagonSource:"401 Client Error: Unauthorized for url: https://api.decagon.ai/conversation/export","rejected the API key",),+ (+ "contract_mismatch_points_at_support_not_the_key",+ "Decagon imported no rows against a nonzero reported total: articles reports 12 rows "+ "and the walk kept none. Check the response envelope against the endpoint config.",+ "Contact support",+ ),])def test_non_retryable_errors_surface_the_most_specific_message(