: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): find Decagon rows in a re-nested response envelope (#102772)
posthog[bot]04af0a9803f3
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 48e06b0e5000..49025b0d0e55 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@@ -29,9 +29,10 @@ DECAGON_PAGE_SIZE = 100# than relying on 429 backoff alone.MIN_SECONDS_BETWEEN_REQUESTS = 1.0-# Hard bound on the pages a "page" walk requests when the response gives no total to-# derive one from. It stops a server that ignores the page param and returns a full page-# on every request; a real export of this size would still end on its short last page.+# Hard bound on the requests a "page" or "offset" walk makes when the response gives no+# total to derive one from. It stops a server that ignores the position param and returns+# a full page on every request; a real export of this size would still end on its short+# last page.MAX_PAGES_WITHOUT_TOTAL = 10_000# Maps a conversation row column to the `timestamp_filter` enum value that makes the@@ -59,6 +60,11 @@ class DecagonRetryableError(Exception):# fragment to match the failure on.CONTRACT_MISMATCH_ERROR = "Decagon imported no rows against a nonzero reported total"+# Stable opening of the failure raised when the response holds lists but the config can+# identify none of them as rows. Classified apart from the mismatch above because only two+# endpoints report a total, so that guard cannot see this failure for the other six.+UNREADABLE_ENVELOPE_ERROR = "Decagon sent lists this table's config cannot read as rows"+class DecagonContractError(Exception):"""The response does not match the contract the endpoint is configured against."""@@ -105,11 +111,24 @@ class _IncrementalWindow:return params[email protected](frozen=True)+class _ListCandidate:+ """A list found in a response envelope, with the object that held it."""++ path: str+ items: list[Any]+ parent: dict[str, Any]++@dataclasses.dataclass(frozen=True)class _Batch:"""One page of a walk: the response envelope, the rows it carried, and the rows to emit."""data: dict[str, Any]+ # Where the walk reads its cursor, has_more and total. Rows found one object down take+ # their pagination fields with them, so reading only the top level ends the walk after+ # one page; the response itself stays the fallback for fields the wrapper leaves outside.+ pagination: dict[str, Any]items: list[Any]fresh: list[dict[str, Any]]@@ -158,32 +177,130 @@ 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.+def _list_candidates(data: dict[str, Any]) -> list[_ListCandidate]:+ """Every list in the envelope, at the top level or one object below it."""+ candidates: list[_ListCandidate] = []+ for key, value in data.items():+ if isinstance(value, list):+ candidates.append(_ListCandidate(path=key, items=value, parent=data))+ elif isinstance(value, dict):+ candidates.extend(+ _ListCandidate(path=f"{key}.{nested}", items=item, parent=value)+ for nested, item in value.items()+ if isinstance(item, list)+ )+ return candidates+++def _looks_like_rows(config: DecagonEndpointConfig, items: list[Any]) -> bool:+ """Whether a list can hold this endpoint's rows: every item an object carrying its primary keys.++ A keyless endpoint never qualifies. "A list of objects" is not evidence of anything, and+ its stream appends without a merge, so a wrong pick lands rows no later sync can clean up.+ """+ if config.primary_keys is None or not items:+ return False+ return all(isinstance(item, dict) and all(key in item for key in config.primary_keys) for item in items)+++def _describe_shape(data: dict[str, Any]) -> str:+ """The envelope's keys and value shapes, so the log names what arrived, not what did not."""+ parts: list[str] = []+ for key in sorted(data):+ value = data[key]+ if isinstance(value, list):+ parts.append(f"{key}: list[{len(value)}]")+ elif isinstance(value, dict):+ parts.append(f"{key}: object({', '.join(sorted(value))})")+ else:+ parts.append(f"{key}: {type(value).__name__}")+ return ", ".join(parts)+++def _unreadable_reason(+ config: DecagonEndpointConfig, same_key: list[_ListCandidate], row_like: list[_ListCandidate]+) -> str:+ """Why the walk could not choose a row list, in the words the operator has to act on.++ Two lists matching needs a different repair from none matching, and support reads this+ text without a Decagon credential to check it against. So name the lists that matched+ rather than report every failure as a response that carries no rows anywhere.+ """+ if len(same_key) > 1:+ paths = ", ".join(f"'{found.path}'" for found in same_key)+ return f"{len(same_key)} of them are named '{config.data_key}' ({paths})"+ if len(row_like) > 1:+ paths = ", ".join(f"'{found.path}'" for found in row_like)+ return f"{len(row_like)} of them carry this endpoint's primary keys ({paths})"+ if row_like:+ return (+ f"only '{row_like[0].path}' carries this endpoint's primary keys, but an empty list beside it "+ f"reads the same as this table's rows returning none"+ )+ return f"none of them is named '{config.data_key}' or carries this endpoint's primary keys"+- 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.+def _resolve_rows(+ data: dict[str, Any], config: DecagonEndpointConfig, endpoint: str, logger: FilteringBoundLogger+) -> _ListCandidate:+ """Read the row list out of a response envelope, with the object that held it.++ Decagon renames and re-nests 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 fails the walk against the reported total. So search the+ envelope for the list the rows moved to: the same key one object down, or the only+ list whose items carry this endpoint's primary keys. A response holding lists that+ match neither fails the sync rather than reading as an empty page."""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 _ListCandidate(path=config.data_key, items=items, parent=data)++ candidates = _list_candidates(data)+ same_key = [found for found in candidates if found.path.rsplit(".", 1)[-1] == config.data_key]+ row_like = [found for found in candidates if _looks_like_rows(config, found.items)]+ # An empty list reads the same as a renamed key that returned no rows, so the primary+ # keys stop separating the two readings. Most keyed endpoints key on `id`, which any+ # sibling list of objects carries, and a full refresh would replace the table with that+ # list. A name match is unaffected: there the response names the rows.+ inferred = [] if any(not found.items for found in candidates) else row_like+ # A list qualifies on its name or on the endpoint's primary keys. Being the envelope's+ # only list is not evidence: "the only list" also describes a list of warnings, and+ # reading that one imports metadata as rows. Anything that leaves more than one+ # candidate is a guess, so it fails instead.+ for shortlist in (same_key, inferred):+ if len(shortlist) == 1:+ found = shortlist[0]+ logger.warning(+ f"Decagon: {endpoint} response carries no '{config.data_key}' list; reading rows from "+ f"'{found.path}' instead (response shape: {_describe_shape(data)})"+ )+ return found++ if candidates:+ reason = _unreadable_reason(config, same_key, row_like)+ # Finalization replaces this message with the fixed operator-facing one, so the+ # shape only reaches whoever has to act on it through the log.+ logger.error(+ f"Decagon: {endpoint} cannot read rows from its response; {reason} "+ f"(response shape: {_describe_shape(data)}, rows read from '{config.data_key}')"+ )+ # Only `articles` and `admin_logs` report a total, so for every other endpoint the+ # contract check has nothing to fail on and this would complete as an empty sync.+ # A full refresh clears the table before extraction, so the populated table would+ # be gone and the job green. The rows are in one of these lists, so fail instead.+ raise DecagonContractError(+ f"{UNREADABLE_ENVELOPE_ERROR}: {endpoint} carries {len(candidates)} list(s) and {reason} "+ f"(response shape: {_describe_shape(data)}).")- return data[list_keys[0]]+ # No list anywhere can be an endpoint that omits its key instead of sending it empty,+ # so an empty page stays a warning rather than a failed sync.logger.warning(- f"Decagon: {endpoint} response carries no '{config.data_key}' list (response keys: {sorted(data.keys())})"+ f"Decagon: {endpoint} response carries no '{config.data_key}' list and no list to read it from "+ f"(response shape: {_describe_shape(data)})")- return []+ return _ListCandidate(path=config.data_key, items=[], parent=data)def _next_cursor(data: dict[str, Any], cursor_keys: tuple[str, ...]) -> Optional[str]:@@ -399,6 +516,7 @@ class _RowWalk:self._logger = loggerself._saw_rows = Falseself._reported_total: Any = None+ self._envelope_shape = ""def run(self) -> Iterator[list[dict[str, Any]]]:yield from self._walk()@@ -416,20 +534,41 @@ class _RowWalk:def _read(self, position_params: dict[str, str]) -> _Batch:params: dict[str, str] = {**self._config.extra_params, **position_params, **self._window_params}data = self._fetcher.fetch(params)- items = _resolve_items(data, self._config, self._endpoint, self._logger)- fresh = self._deduplicator.fresh(items)+ self._envelope_shape = _describe_shape(data)+ rows = _resolve_rows(data, self._config, self._endpoint, self._logger)+ fresh = self._deduplicator.fresh(rows.items)self._saw_rows = self._saw_rows or bool(fresh)- return _Batch(data=data, items=items, fresh=fresh)-- def _record_total(self, batch: _Batch) -> Any:- self._reported_total = batch.data.get(self._config.total_key) if self._config.total_key else None- return self._reported_total+ pagination = data if rows.parent is data else {**data, **rows.parent}+ # Recorded here rather than in the walk, so the contract check sees the reported+ # total whichever mode read the response. A later page that omits the total keeps+ # the one an earlier page reported: dropping it falls the walk back to short-page+ # termination, which a server-capped page then ends before the total is reached.+ reported = pagination.get(self._config.total_key) if self._config.total_key else None+ if _usable_total(reported) is not None or _usable_total(self._reported_total) is None:+ self._reported_total = reported+ return _Batch(data=data, pagination=pagination, items=rows.items, fresh=fresh)def _short_page(self, batch: _Batch) -> bool:"""Termination signal left when the response carries no usable total."""page_size = self._config.page_sizereturn not batch.items or (page_size is not None and len(batch.items) < page_size)+ def _request_cap_reached(self, requests_made: int, position_param: str) -> bool:+ """Constant bound for a walk with no usable total to size one from.++ A server that ignores the position param answers every request with a full page,+ which short-page termination never ends. With no total to check the kept rows+ against, the cap can only warn.+ """+ if requests_made < MAX_PAGES_WITHOUT_TOTAL:+ return False+ self._logger.warning(+ f"Decagon: {self._endpoint} walk stopped at the cap of {MAX_PAGES_WITHOUT_TOTAL} requests with no "+ f"usable total (got {self._reported_total!r}). If the synced row count looks truncated, check that "+ f"the endpoint honors the {position_param} param."+ )+ return True+def _check_contract(self) -> None:# 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@@ -441,9 +580,16 @@ class _RowWalk:and isinstance(self._reported_total, int | float)and self._reported_total > 0):+ # Finalization replaces the message below with the fixed operator-facing one, so+ # the shape only reaches whoever has to act on it through the log.+ self._logger.error(+ f"Decagon: {self._endpoint} kept no rows against a reported total of {self._reported_total} "+ f"(response shape: {self._envelope_shape}, rows read from '{self._config.data_key}')"+ )raise DecagonContractError(f"{CONTRACT_MISMATCH_ERROR}: {self._endpoint} reports {self._reported_total} rows and the walk "- f"kept none. Check the response envelope against the endpoint config."+ f"kept none. The last response carried {self._envelope_shape}, and the config reads rows from "+ f"'{self._config.data_key}'.")def _save_position(self, **position: Any) -> None:@@ -469,8 +615,8 @@ class _RowWalk:while True:# An omitted cursor starts the stream at the oldest rows.batch = self._read({"cursor": cursor} if cursor else {})- next_cursor = _next_cursor(batch.data, config.next_cursor_keys or ())- more = batch.data.get(config.has_more_key) if config.has_more_key else None+ next_cursor = _next_cursor(batch.pagination, config.next_cursor_keys or ())+ more = batch.pagination.get(config.has_more_key) if config.has_more_key else Noneif batch.fresh:yield batch.fresh@@ -483,7 +629,20 @@ class _RowWalk:# server ever returns the cursor we just used, to guard against spinning on# one page forever.if not next_cursor or next_cursor == cursor:- if config.has_more_key is None and not next_cursor and len(batch.items) >= DECAGON_PAGE_SIZE:+ if more:+ # The walk has to stop here, but the response says rows remain, so this+ # is a truncated stream rather than an exhausted one. The endpoints that+ # send has_more append with no merge and walk desc, so a completed run+ # advances the watermark past the newest rows this page held and every+ # later sync skips the pages this walk never reached.+ stopped = "repeated the cursor just used" if next_cursor else "carried no next-page cursor"+ self._logger.warning(+ f"Decagon: {self._endpoint} stopped after a page that {stopped} while "+ f"'{config.has_more_key}' reports {more!r} (response keys: {sorted(batch.data.keys())}, "+ f"cursor read from {list(config.next_cursor_keys or ())}). The rows past this page did "+ f"not sync; check the export pagination contract."+ )+ elif config.has_more_key is None and not next_cursor and len(batch.items) >= DECAGON_PAGE_SIZE:# A full page that ends the walk is legitimate only when the total row# count happens to be a multiple of the page size; far more often it means# Decagon renamed the pagination field again and rows were truncated.@@ -514,7 +673,7 @@ class _RowWalk:params["page_size"] = str(config.page_size)batch = self._read(params)- total = self._record_total(batch)+ total = self._reported_totalrows_walked += len(batch.fresh)page_rows = max(page_rows, len(batch.items))exhausted = self._page_walk_exhausted(page, rows_walked, page_rows, total, batch)@@ -539,19 +698,9 @@ class _RowWalk:return Trueif total is None:- # A missing or malformed total falls back to short-page termination and a- # constant cap. With nothing to check the kept rows against, the cap can only- # warn.- if self._short_page(batch):- return True- if page < MAX_PAGES_WITHOUT_TOTAL:- return False- self._logger.warning(- f"Decagon: {self._endpoint} walk stopped at the page cap of {MAX_PAGES_WITHOUT_TOTAL} with no "- f"usable total (got {reported!r}). If the synced row count looks truncated, check that the "- f"endpoint honors the page param."- )- return True+ # A missing or malformed total falls back to short-page termination, bounded by+ # the constant cap.+ return self._short_page(batch) or self._request_cap_reached(page, "page")# One page more than the total needs at the server's page size, so rows that shift# pages mid-walk (arriving twice, kept once) do not push the last unique rows past@@ -571,6 +720,7 @@ class _RowWalk:def _walk_offset(self) -> Iterator[list[dict[str, Any]]]:config = self._configoffset = self._resume.offset or 0+ requests_made = 0while True:params = {"offset": str(offset)}@@ -578,16 +728,19 @@ class _RowWalk:params["limit"] = str(config.page_size)batch = self._read(params)- total = self._record_total(batch)+ requests_made += 1+ total = _usable_total(self._reported_total)# Advance by the rows actually received rather than by page_size, so a server that# caps `limit` below what we asked still walks every row. The offset itself is the# cumulative row count, so the total check needs no separate counter.next_offset = offset + len(batch.items)- if isinstance(total, int | float):+ if total is not None:exhausted = not batch.items or next_offset >= totalelse:- exhausted = self._short_page(batch)+ # A server that ignores `offset` sends a full page to every request and never+ # the short page this would otherwise end on.+ exhausted = self._short_page(batch) or self._request_cap_reached(requests_made, "offset")if batch.fresh:yield batch.freshdiff --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 68e4fc2bf43c..aecf90d5cb1d 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@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schfrom 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,+ UNREADABLE_ENVELOPE_ERROR,DecagonResumeConfig,decagon_source,validate_credentials as validate_decagon_credentials,@@ -107,6 +108,15 @@ You can find your API key on the **Developer** page of the [Decagon dashboard](h"is not a problem with your API key. Contact support so we can update the sync to ""match what Decagon now sends."),+ # Same cause as above, caught one step earlier: the response holds lists, but none of+ # them is the row list this table is configured to read. Most endpoints report no total+ # for the guard above to read, so this failure is what stops an empty full refresh from+ # replacing the table.+ UNREADABLE_ENVELOPE_ERROR: (+ "PostHog could not find this table's rows in Decagon's response. 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 350c04447691..2267e806440f 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@@ -431,6 +431,58 @@ class TestPaginationModes:saved = [call.args[0] for call in manager.save_state.call_args_list]assert saved == [DecagonResumeConfig(offset=2)]+ def test_offset_mode_ignores_a_total_that_cannot_bound_the_walk(self) -> None:+ # Python counts True as 1, so a boolean total made the first row satisfy the bound+ # and the walk reported success on a partial table. An unusable total has to fall+ # back to short-page termination, as the page walk already does.+ cfg = _synthetic_endpoint(pagination="offset", page_size=2, total_key="total")+ with patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}):+ manager = _fresh_manager()+ responses = [+ _make_response({"rows": [_row("r1"), _row("r2")], "total": True}),+ _make_response({"rows": [_row("r3")], "total": True}),+ ]+ _, batches = _drive_rows(manager, responses, endpoint="synthetic")++ assert [[r["id"] for r in b] for b in batches] == [["r1", "r2"], ["r3"]]++ def test_offset_mode_without_a_total_stops_at_the_constant_request_cap(self) -> None:+ # With no usable total the short page is the only natural end, and a server that+ # ignores `offset` never sends one: the walk then requests once a second until the+ # activity times out, burning a worker per attempt and inviting vendor throttling.+ cfg = _synthetic_endpoint(pagination="offset", page_size=2)+ cap = 7++ def respond(_params: dict[str, Any]) -> Response:+ return _make_response({"rows": [_row("r1"), _row("r2")]})++ logger = MagicMock()+ with (+ patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}),+ patch(f"{DECAGON_MODULE}.MAX_PAGES_WITHOUT_TOTAL", cap),+ ):+ manager = _fresh_manager()+ sent_params, batches = _drive_server(manager, respond, cap, endpoint="synthetic", logger=logger)++ assert len(sent_params) == cap+ assert [[r["id"] for r in b] for b in batches] == [["r1", "r2"]]+ assert "offset" in logger.warning.call_args.args[0]++ def test_a_page_that_omits_the_total_keeps_the_one_already_reported(self) -> None:+ # Falling back to short-page termination here ends the walk on a server-capped+ # page, so the rows past it never sync and the job still reports success.+ cfg = _synthetic_endpoint(pagination="page", page_size=2, total_key="total")+ with patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}):+ manager = _fresh_manager()+ responses = [+ _make_response({"rows": [_row("r1"), _row("r2")], "total": 4}),+ _make_response({"rows": [_row("r3")]}),+ _make_response({"rows": [_row("r4")], "total": 4}),+ ]+ _, batches = _drive_rows(manager, responses, endpoint="synthetic")++ assert [[r["id"] for r in b] for b in batches] == [["r1", "r2"], ["r3"], ["r4"]]+def test_cursor_mode_has_more_false_ends_the_walk_even_with_a_cursor_present(self) -> None:# On endpoints that send has_more the flag is authoritative; following a leftover# cursor would re-fetch or spin on the final page.@@ -441,11 +493,52 @@ class TestPaginationModes:_make_response({"rows": [_row("r1")], "next_cursor": "cur-1", "has_more": True}),_make_response({"rows": [_row("r2")], "next_cursor": "cur-stale", "has_more": False}),]- sent_params, _ = _drive_rows(manager, responses, endpoint="synthetic")+ logger = MagicMock()+ sent_params, _ = _drive_rows(manager, responses, endpoint="synthetic", logger=logger)assert sent_params == [{}, {"cursor": "cur-1"}]+ # An exhausted stream is the healthy case, so the truncation warning below must not+ # fire on every sync of every endpoint that sends the flag.+ logger.warning.assert_not_called()saved = [call.args[0] for call in manager.save_state.call_args_list]assert saved == [DecagonResumeConfig(cursor="cur-1")]+ @parameterized.expand(+ [+ (+ "carrying_no_next_page_cursor",+ [{"rows": [_row("r1")], "has_more": True}],+ "carried no next-page cursor",+ ),+ (+ "repeating_the_cursor_just_used",+ [+ {"rows": [_row("r1")], "next_cursor": "cur-1", "has_more": True},+ {"rows": [_row("r2")], "next_cursor": "cur-1", "has_more": True},+ ],+ "repeated the cursor just used",+ ),+ ]+ )+ def test_cursor_mode_logs_a_walk_that_ends_while_has_more_reports_rows(+ self, _name: str, bodies: list[dict[str, Any]], stopped: str+ ) -> None:+ # Following a missing or repeated cursor would re-fetch or spin, so stopping is+ # right, but the endpoints that send has_more append with no merge and walk desc:+ # a completed run moves the watermark past this page and every later sync skips+ # what the walk never reached. Silence here leaves a green job as the only trace.+ cfg = _synthetic_endpoint(pagination="cursor", next_cursor_keys=("next_cursor",), has_more_key="has_more")+ logger = MagicMock()+ with patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}):+ manager = _fresh_manager()+ responses = [_make_response(body) for body in bodies]+ sent_params, batches = _drive_rows(manager, responses, endpoint="synthetic", logger=logger)++ assert len(sent_params) == len(bodies)+ assert [len(b) for b in batches] == [1] * len(bodies)+ logged = logger.warning.call_args.args[0]+ assert stopped in logged+ assert "'has_more' reports True" in logged+def test_keyless_stream_yields_rows_without_touching_a_primary_key(self) -> None:# Streams with no documented id must not KeyError on a dedupe key they don't have.cfg = _synthetic_endpoint(pagination="single", primary_keys=None)@@ -530,6 +623,20 @@ class TestAgentAssistActions:saved = [call.args[0] for call in manager.save_state.call_args_list]assert saved == [DecagonResumeConfig(cursor="cur-1", min_timestamp=int(epoch))]+ def test_a_wrapped_envelope_pages_on_the_cursor_beside_its_rows(self) -> None:+ # Rows one object down take has_more and next_cursor with them. Reading those from+ # the top level alone ends the walk after page one and reports the truncated table+ # as synced, which is worse than the empty table the renamed key used to leave.+ manager = _fresh_manager()+ responses = [+ _make_response({"result": {"events": [{"agent_name": "a"}], "has_more": True, "next_cursor": "cur-1"}}),+ _make_response({"result": {"events": [{"agent_name": "b"}], "has_more": False, "next_cursor": None}}),+ ]+ sent_params, batches = _drive_rows(manager, responses, endpoint="agent_assist_actions")++ assert sent_params == [{"include_details": "true"}, {"include_details": "true", "cursor": "cur-1"}]+ assert [len(b) for b in batches] == [1, 1]+def test_a_refused_details_add_on_retries_the_walk_without_it(self) -> None:# Detail export is entitled separately from the actions export, and a team without# it is refused the whole request, so the table only syncs if the walk drops the@@ -685,29 +792,150 @@ class TestArticleTables:assert [[r["id"] for r in b] for b in batches] == [[1, 2]]logger.warning.assert_called_once()- 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.+ @parameterized.expand(+ [+ ("only_list", {"data": [{"id": 1}, {"id": 2}], "total": 2}),+ ("configured_key_one_level_down", {"result": {"articles": [{"id": 1}, {"id": 2}]}, "total": 2}),+ ("only_list_one_level_down", {"result": {"items": [{"id": 1}, {"id": 2}]}, "total": 2}),+ (+ "only_list_carrying_the_primary_key",+ {"items": [{"id": 1}, {"id": 2}], "warnings": ["stale"], "total": 2},+ ),+ ]+ )+ def test_rows_are_read_from_a_renamed_or_re_nested_envelope(self, _name: str, body: dict[str, Any]) -> None:+ # A renamed or re-nested envelope key otherwise reads as an empty page, which fails+ # the walk against the reported total and leaves the table empty until support+ # updates the config.manager = _fresh_manager()- responses = [_make_response({"data": [{"id": 1}, {"id": 2}], "total": 2})]- _, batches = _drive_rows(manager, responses, endpoint="articles")+ _, batches = _drive_rows(manager, [_make_response(body)], endpoint="articles")assert [[r["id"] for r in b] for b in batches] == [[1, 2]]+ @parameterized.expand(+ [+ (+ "two_lists_that_both_look_like_rows",+ {"drafts": [{"id": 1}], "published": [{"id": 2}], "total": 2},+ "2 of them carry this endpoint's primary keys ('drafts', 'published')",+ ),+ (+ "two_lists_carrying_the_configured_name",+ {"result": {"articles": [{"id": 1}]}, "backup": {"articles": [{"id": 2}]}},+ "2 of them are named 'articles' ('result.articles', 'backup.articles')",+ ),+ (+ "a_later_item_without_the_primary_key",+ {"items": [{"id": 1}, {"slug": "x"}], "tags": [], "total": 2},+ "none of them is named 'articles' or carries this endpoint's primary keys",+ ),+ (+ "an_empty_list_beside_a_list_carrying_the_primary_key",+ {"data": [], "tags": [{"id": 7}], "total": 0},+ "only 'tags' carries this endpoint's primary keys",+ ),+ (+ "the_only_list_carrying_no_primary_key",+ {"warnings": [{"message": "partial"}], "total": 2},+ "none of them is named 'articles' or carries this endpoint's primary keys",+ ),+ (+ "one_list_one_level_down_carrying_no_primary_key",+ {"meta": {"warnings": [{"m": 1}]}, "total": 2},+ "none of them is named 'articles' or carries this endpoint's primary keys",+ ),+ ]+ )+ def test_an_ambiguous_envelope_fails_rather_than_guessing_a_list(+ self, _name: str, body: dict[str, Any], reason: str+ ) -> None:+ # Picking one of these would import the wrong table silently, or pick a list whose+ # later rows have no primary key and crash the deduplicator. Being the envelope's+ # only list is not evidence either: a list of warnings fits that description. An+ # empty list is a second reading of its own, because the renamed rows can be the+ # empty one. The walk keeps nothing and the contract guard fails the sync instead.+ # Support reads this failure without a Decagon credential to check it against, so+ # two lists matching has to read as two lists matching, not as a response with no+ # rows in it.+ manager = _fresh_manager()+ logger = MagicMock()++ with pytest.raises(DecagonContractError) as excinfo:+ _drive_rows(manager, [_make_response(body)], endpoint="articles", logger=logger)++ assert reason in str(excinfo.value)+ assert reason in logger.error.call_args.args[0]++ def test_an_unreadable_envelope_fails_a_cursor_walk_too(self) -> None:+ # The contract guard has to hold for every pagination mode. Reading the total only+ # in the paged modes left it inert everywhere else, so an unreadable envelope+ # completed as an empty sync.+ cfg = dataclasses.replace(DECAGON_ENDPOINTS["conversations"], total_key="total")+ with patch.dict(DECAGON_ENDPOINTS, {"conversations": cfg}):+ manager = _fresh_manager()+ responses = [_make_response({"unexpected": {"conversation_id": "c1"}, "total": 12})]++ with pytest.raises(DecagonContractError):+ _drive_rows(manager, responses, endpoint="conversations")++ @parameterized.expand(+ [+ ("two_lists", {"data": [{"article_id": 1}], "meta": [{"page": 1}]}),+ ("the_only_list", {"data": [{"article_id": 1}]}),+ ("one_list_one_level_down", {"result": {"warnings": [{"message": "partial"}]}}),+ ]+ )+ def test_a_keyless_table_fails_rather_than_reading_a_guessed_list(self, _name: str, body: dict[str, Any]) -> None:+ # article_usage appends without a merge, so a guessed list lands rows no later sync+ # can clean up. With no primary key to recognize rows by, no list qualifies, and the+ # endpoint reports no total, so completing would replace the table with nothing.+ manager = _fresh_manager()++ with pytest.raises(DecagonContractError):+ _drive_rows(manager, [_make_response(body)], endpoint="article_usage")+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()+ logger = MagicMock()responses = [_make_response({"unexpected": {"id": 1}, "total": 12})]with pytest.raises(DecagonContractError) as excinfo:- _drive_rows(manager, responses, endpoint="articles")+ _drive_rows(manager, responses, endpoint="articles", logger=logger)++ # Finalization replaces the raised message with the fixed operator-facing one, so+ # the shape reaches support through the log or not at all.+ assert "unexpected: object(id)" in logger.error.call_args.args[0]+ # Support cannot read the Decagon account, so the shape the walk saw has to travel+ # with the failure; without it the next envelope change needs a live credential to+ # diagnose.+ assert "unexpected: object(id)" in str(excinfo.value)+ assert "total: int" in str(excinfo.value)# 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())+ @parameterized.expand(+ [+ ("beside_the_nested_rows", {"result": {"articles": [{"id": 1}, {"id": 2}], "total": 2}}),+ ("left_at_the_top_level", {"result": {"articles": [{"id": 1}, {"id": 2}]}, "total": 2}),+ ]+ )+ def test_a_wrapped_envelope_bounds_the_page_walk_on_its_total(self, _name: str, body: dict[str, Any]) -> None:+ # A wrapper can take the total down with the rows or leave it outside, so the walk+ # reads it from the object that held the rows and falls back to the response. With+ # neither read finding it, a full page keeps requesting pages the export has ended.+ cfg = dataclasses.replace(DECAGON_ENDPOINTS["articles"], page_size=2)+ with patch.dict(DECAGON_ENDPOINTS, {"articles": cfg}):+ manager = _fresh_manager()+ sent_params, batches = _drive_rows(manager, [_make_response(body)], endpoint="articles")++ assert len(sent_params) == 1+ assert [[r["id"] for r in b] for b in batches] == [[1, 2]]+def test_an_empty_knowledge_base_still_completes(self) -> None:manager = _fresh_manager()responses = [_make_response({"articles": [], "total": 0})]@@ -715,6 +943,21 @@ class TestArticleTables:assert batches == []+ def test_a_table_without_a_total_also_fails_on_an_unreadable_envelope(self) -> None:+ # /tag/all reports no total, so the contract check that covers articles cannot see+ # this failure. The table is full refresh, and the pipeline clears it before the walk+ # runs, so completing with no rows leaves the tag dimension empty and the job green.+ manager = _fresh_manager()+ responses = [_make_response({"drafts": [{"slug": "a"}], "published": [{"slug": "b"}]})]++ with pytest.raises(DecagonContractError) as excinfo:+ _drive_rows(manager, responses, endpoint="tags")++ # Unclassified, this identical request repeats for the whole attempt budget and the+ # schema stays enabled to repeat it on the next schedule.+ assert error_message_matches(str(excinfo.value), DecagonSource().get_non_retryable_errors())+ assert "drafts: list[1]" in str(excinfo.value)+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.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 7ce31097b02e..03e3d468bf15 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@@ -121,6 +121,12 @@ class TestDecagonSource:"and the walk kept none. Check the response envelope against the endpoint config.","Contact support",),+ (+ "unreadable_envelope_points_at_support_not_the_key",+ "Decagon sent lists this table's config cannot read as rows: tags carries 2 list(s) and "+ "2 of them carry this endpoint's primary keys ('drafts', 'published').",+ "Contact support",+ ),])def test_non_retryable_errors_surface_the_most_specific_message(