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.

fix(pendo): paginate aggregation endpoints via filter cursor, not skip (#74360)

Tom Owers9830e8263611
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pendo/pendo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pendo/pendo.py
index ab1b09311c6c..4abf4e1121ad 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pendo/pendo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pendo/pendo.py
@@ -32,8 +32,11 @@ class PendoRetryableError(Exception):
@dataclasses.dataclass
class PendoResumeConfig:
- # Number of rows already yielded for this schema; on resume we skip past them.
+ # Number of rows already yielded for a list endpoint schema; on resume we skip past them.
offset: int = 0
+ # Sort-field value of the last row yielded for an aggregation endpoint schema. Pendo's
+ # aggregation pipeline has no skip/offset stage, so resuming re-filters for values past this.
+ last_id: Optional[str] = None
def get_base_url(region: Optional[str]) -> str:
@@ -115,6 +118,13 @@ def _iter_list_endpoint(
resumable_source_manager.save_state(PendoResumeConfig(offset=offset))
+def _escape_filter_string(value: str) -> str:
+ # Pendo's filter grammar uses JS-style string literals. `last_id` comes from a row's sort
+ # field (e.g. visitorId, which a customer's own tracking code can set to an arbitrary
+ # string), so escape backslashes and quotes before splicing it into the filter expression.
+ return value.replace("\\", "\\\\").replace('"', '\\"')
+
+
def _iter_aggregation(
session: requests.Session,
base_url: str,
@@ -122,23 +132,27 @@ def _iter_aggregation(
sort_field: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[PendoResumeConfig],
- start_offset: int,
+ start_after: Optional[str],
) -> Iterator[list[dict[str, Any]]]:
url = f"{base_url}{AGGREGATION_PATH}"
- offset = start_offset
+ last_id = start_after
while True:
+ # Sort on a stable id and page via a `>` filter cursor: Pendo's aggregation pipeline
+ # has no skip/offset stage (a "skip" step returns a 400 "unknown step type" error).
+ pipeline: list[dict[str, Any]] = [
+ {"source": {aggregation_source: None}},
+ {"sort": [sort_field]},
+ ]
+ if last_id is not None:
+ pipeline.append({"filter": f'{sort_field}>"{_escape_filter_string(last_id)}"'})
+ pipeline.append({"limit": AGGREGATION_PAGE_SIZE})
+
body = {
"response": {"mimeType": "application/json"},
"request": {
"requestId": f"posthog-{aggregation_source}",
- "pipeline": [
- {"source": {aggregation_source: None}},
- # Sort on a stable id so skip/limit paging is deterministic across requests.
- {"sort": [sort_field]},
- {"skip": offset},
- {"limit": AGGREGATION_PAGE_SIZE},
- ],
+ "pipeline": pipeline,
},
}
response = _request(session, "POST", url, logger, json=body)
@@ -149,8 +163,8 @@ def _iter_aggregation(
break
yield rows
- offset += len(rows)
- resumable_source_manager.save_state(PendoResumeConfig(offset=offset))
+ last_id = str(rows[-1][sort_field])
+ resumable_source_manager.save_state(PendoResumeConfig(last_id=last_id))
if len(rows) < AGGREGATION_PAGE_SIZE:
break
@@ -169,13 +183,13 @@ def get_rows(
session = make_tracked_session(headers=_get_headers(integration_key), redact_values=(integration_key,))
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- start_offset = resume.offset if resume else 0
- if start_offset:
- logger.debug(f"Pendo: resuming endpoint={endpoint} from offset={start_offset}")
if config.is_aggregation:
if config.aggregation_source is None:
raise ValueError(f"Endpoint '{endpoint}' is marked as aggregation but has no aggregation_source")
+ start_after = resume.last_id if resume else None
+ if start_after is not None:
+ logger.debug(f"Pendo: resuming endpoint={endpoint} after id={start_after}")
yield from _iter_aggregation(
session,
base_url,
@@ -183,11 +197,14 @@ def get_rows(
config.primary_keys[0],
logger,
resumable_source_manager,
- start_offset,
+ start_after,
)
else:
if config.path is None:
raise ValueError(f"Endpoint '{endpoint}' is not an aggregation but has no path")
+ start_offset = resume.offset if resume else 0
+ if start_offset:
+ logger.debug(f"Pendo: resuming endpoint={endpoint} from offset={start_offset}")
yield from _iter_list_endpoint(
session,
base_url,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pendo/tests/test_pendo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pendo/tests/test_pendo.py
index 077ecb5d7dfe..e0626a1892d2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pendo/tests/test_pendo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pendo/tests/test_pendo.py
@@ -163,7 +163,9 @@ class TestGetRowsListEndpoint:
class TestGetRowsAggregation:
@mock.patch(f"{PENDO_PATH}.AGGREGATION_PAGE_SIZE", 2)
@mock.patch(f"{PENDO_PATH}.make_tracked_session")
- def test_paginates_via_skip_and_limit(self, mock_session):
+ def test_paginates_via_filter_cursor_and_limit(self, mock_session):
+ # Pendo's aggregation pipeline has no skip/offset stage (a "skip" step is rejected with
+ # a 400 "unknown step type" error), so paging must use a `>` filter cursor on the sort field.
page1 = {"results": [{"visitorId": "1"}, {"visitorId": "2"}]}
page2 = {"results": [{"visitorId": "3"}]}
mock_session.return_value.request.side_effect = [_resp(page1), _resp(page2)]
@@ -181,14 +183,14 @@ class TestGetRowsAggregation:
first_pipeline = calls[0].kwargs["json"]["request"]["pipeline"]
assert {"source": {"visitors": None}} in first_pipeline
assert {"sort": ["visitorId"]} in first_pipeline
- assert {"skip": 0} in first_pipeline
assert {"limit": 2} in first_pipeline
+ assert not any("filter" in step for step in first_pipeline)
second_pipeline = calls[1].kwargs["json"]["request"]["pipeline"]
- assert {"skip": 2} in second_pipeline
+ assert {"filter": 'visitorId>"2"'} in second_pipeline
- offsets = [call.args[0].offset for call in manager.save_state.call_args_list]
- assert offsets == [2, 3]
+ last_ids = [call.args[0].last_id for call in manager.save_state.call_args_list]
+ assert last_ids == ["2", "3"]
@mock.patch(f"{PENDO_PATH}.make_tracked_session")
def test_accounts_source_sorts_on_account_id(self, mock_session):
@@ -212,14 +214,26 @@ class TestGetRowsAggregation:
manager.save_state.assert_not_called()
@mock.patch(f"{PENDO_PATH}.make_tracked_session")
- def test_resumes_aggregation_from_saved_offset(self, mock_session):
+ def test_resumes_aggregation_from_saved_last_id(self, mock_session):
+ mock_session.return_value.request.return_value = _resp({"results": []})
+ manager = _make_manager(PendoResumeConfig(last_id="9"))
+
+ list(get_rows("key", "us", "visitors", mock.MagicMock(), manager))
+
+ pipeline = mock_session.return_value.request.call_args.kwargs["json"]["request"]["pipeline"]
+ assert {"filter": 'visitorId>"9"'} in pipeline
+
+ @mock.patch(f"{PENDO_PATH}.make_tracked_session")
+ def test_escapes_quotes_in_the_filter_cursor(self, mock_session):
+ # visitorId is set by the customer's own tracking code, so a value containing a `"`
+ # must not be able to break out of the filter string literal and alter the expression.
mock_session.return_value.request.return_value = _resp({"results": []})
- manager = _make_manager(PendoResumeConfig(offset=10))
+ manager = _make_manager(PendoResumeConfig(last_id='ab"cd'))
list(get_rows("key", "us", "visitors", mock.MagicMock(), manager))
pipeline = mock_session.return_value.request.call_args.kwargs["json"]["request"]["pipeline"]
- assert {"skip": 10} in pipeline
+ assert {"filter": 'visitorId>"ab\\"cd"'} in pipeline
class TestPendoSourceResponse: