: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(instantly): bound account daily analytics requests to a date window (#112788)
Tom Owerse4cac03fe79a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/instantly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/instantly.pyindex abd428e6dde9..28ce037ff3be 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/instantly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/instantly.py@@ -3,7 +3,7 @@ import hashlibimport secretsimport dataclassesfrom collections.abc import Callable, Iterable, Iterator-from datetime import date, datetime+from datetime import UTC, date, datetime, timedeltafrom typing import Any, Optionalimport orjson@@ -12,6 +12,8 @@ import requestsfrom asgiref.sync import async_to_syncfrom structlog.types import FilteringBoundLogger+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_listfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (ExternalWebhookInfo,@@ -54,6 +56,9 @@ SYNC_REQUEST_TIMEOUT_SECONDS = (10, 120)# thousands of webhooks, so this is a defensive cap, not an expected limit.MAX_WEBHOOK_LIST_PAGES = 10+# Instantly limits daily analytics requests to 31 days.+DATE_WINDOW_SIZE_DAYS = 31+WEBHOOK_NAME = "PostHog data warehouse"# Instantly deliveries are unsigned, but webhooks accept static custom headers — we attach a# generated secret header on create and the webhook template verifies it on every delivery.@@ -319,17 +324,36 @@ def _campaign_fanout_pages(client: RESTClient, config: InstantlyEndpointConfig)yield page+def _today() -> date:+ return datetime.now(UTC).date()+++@frozen+class DateWindow:+ start: str+ end: str+++def _date_windows(start_date: str, end: date) -> Iterator[DateWindow]:+ current = datetime.strptime(start_date, "%Y-%m-%d").date()+ while current <= end:+ window_end = min(current + timedelta(days=DATE_WINDOW_SIZE_DAYS - 1), end)+ yield DateWindow(start=current.isoformat(), end=window_end.isoformat())+ current = window_end + timedelta(days=1)++def _date_windowed_pages(client: RESTClient, config: InstantlyEndpointConfig, start_date: str) -> Iterator[list[dict[str, Any]]]:- for page in client.paginate(- path=f"/api/v2{config.path}",- params={**config.params, "start_date": start_date},- paginator=SinglePagePaginator(),- data_selector=config.data_selector,- ):- # Row order is undocumented; sort so the asc watermark never passes an unwritten date.- yield sorted(page, key=lambda row: str(row.get("date") or ""))+ for window in _date_windows(start_date, _today()):+ for page in client.paginate(+ path=f"/api/v2{config.path}",+ params={**config.params, "start_date": window.start, "end_date": window.end},+ paginator=SinglePagePaginator(),+ data_selector=config.data_selector,+ ):+ # Row order is undocumented; sort so the asc watermark never passes an unwritten date.+ yield sorted(page, key=lambda row: str(row.get("date") or ""))def _webhook_events_source(webhook_source_manager: Optional[WebhookSourceManager]) -> SourceResponse:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly.pyindex b2a3c749f519..79d4b6900a37 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly.py@@ -229,43 +229,70 @@ class TestInstantly:# A campaign without an id is skipped rather than sent as an unscoped request.assert client.calls == [("/api/v2/campaigns", {"limit": 100}), (child_path, expected_params)]- @pytest.mark.parametrize(- "should_use_incremental_field,last_value,expected_start_date",- [- # The API defaults to the last 30 days without start_date, so full refresh asks for all history.- (False, None, ANALYTICS_HISTORY_START_DATE),- (True, None, ANALYTICS_HISTORY_START_DATE),- (True, date(2026, 3, 4), "2026-03-04"),- ],- )- def test_account_daily_analytics_windows_by_start_date_and_sorts_rows(- self, should_use_incremental_field, last_value, expected_start_date- ):+ def test_account_daily_analytics_windows_by_start_date_and_sorts_rows(self):rows = [{"date": "2026-03-05", "email_account": "[email protected]"},{"date": "2026-03-04", "email_account": "[email protected]"},]client = _FakeClient({"/api/v2/accounts/analytics/daily": [rows]})- with mock.patch(f"{MODULE}._make_client", return_value=client):+ with (+ mock.patch(f"{MODULE}._make_client", return_value=client),+ mock.patch(f"{MODULE}._today", return_value=date(2026, 3, 10)),+ ):response = instantly_source(api_key="key",endpoint="account_daily_analytics",team_id=1,job_id="job",resumable_source_manager=mock.MagicMock(),- should_use_incremental_field=should_use_incremental_field,- db_incremental_field_last_value=last_value,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 3, 4),)items = response.items()assert isinstance(items, Iterable)pages = list(items)- assert client.calls == [("/api/v2/accounts/analytics/daily", {"start_date": expected_start_date})]+ # The incremental watermark is within one window of "today", so this collapses to a+ # single bounded request instead of a chunked walk.+ assert client.calls == [+ ("/api/v2/accounts/analytics/daily", {"start_date": "2026-03-04", "end_date": "2026-03-10"})+ ]# Ascending date order keeps the asc incremental watermark from skipping unwritten days.assert [row["date"] for row in pages[0]] == ["2026-03-04", "2026-03-05"]assert response.primary_keys == ["date", "email_account"]+ @pytest.mark.parametrize("should_use_incremental_field", [False, True])+ def test_account_daily_analytics_full_refresh_splits_into_bounded_windows(self, should_use_incremental_field):+ client = _FakeClient({"/api/v2/accounts/analytics/daily": [[]]})++ with (+ mock.patch(f"{MODULE}._make_client", return_value=client),+ mock.patch(f"{MODULE}._today", return_value=date(2020, 4, 15)),+ ):+ response = instantly_source(+ api_key="key",+ endpoint="account_daily_analytics",+ team_id=1,+ job_id="job",+ resumable_source_manager=mock.MagicMock(),+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=None,+ )+ items = response.items()+ assert isinstance(items, Iterable)+ list(items)++ assert client.calls == [+ (+ "/api/v2/accounts/analytics/daily",+ {"start_date": ANALYTICS_HISTORY_START_DATE, "end_date": "2020-01-31"},+ ),+ ("/api/v2/accounts/analytics/daily", {"start_date": "2020-02-01", "end_date": "2020-03-02"}),+ ("/api/v2/accounts/analytics/daily", {"start_date": "2020-03-03", "end_date": "2020-04-02"}),+ ("/api/v2/accounts/analytics/daily", {"start_date": "2020-04-03", "end_date": "2020-04-15"}),+ ]+def test_probe_sends_required_campaign_id_for_subsequences(self):session = mock.MagicMock()