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.

feat(warehouse-sources): add four missing instantly tables (#111529)

Tom Owers277f821a0c9b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index d694b71553e8..b6fdd29899ef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -4355,10 +4355,10 @@ Today (10): `accounts`, `campaign_analytics`, `campaign_daily_analytics`, `campa
Diffed against: <https://developer.instantly.ai/api-reference/openapi.json>
-- [ ] `GET /api/v2/campaigns/analytics/steps` — per-sequence-step send/open/reply breakdown; the dimension that explains campaign performance (high)
-- [ ] `GET /api/v2/accounts/analytics/daily` — daily per-sending-account volume and deliverability; we sync accounts but no account time series (high)
-- [ ] `GET /api/v2/custom-tag-mappings` — junction resolving the custom_tags we already sync to campaigns/accounts/leads (high)
-- [ ] `GET /api/v2/subsequences` — follow-up sequences attached to campaigns; missing branch of the campaign tree (medium)
+- [x] `GET /api/v2/campaigns/analytics/steps` — per-sequence-step send/open/reply breakdown; the dimension that explains campaign performance (high)
+- [x] `GET /api/v2/accounts/analytics/daily` — daily per-sending-account volume and deliverability; we sync accounts but no account time series (high)
+- [x] `GET /api/v2/custom-tag-mappings` — junction resolving the custom_tags we already sync to campaigns/accounts/leads (high)
+- [x] `GET /api/v2/subsequences` — follow-up sequences attached to campaigns; missing branch of the campaign tree (medium)
- [ ] `GET /api/v2/block-lists-entries` — suppression list explaining why leads were never contacted (medium)
- [ ] `POST /api/v2/accounts/warmup-analytics` — read-shaped per-account warmup health scores (medium)
- [ ] `GET /api/v2/inbox-placement-analytics + /inbox-placement-reports` — inbox vs spam placement results per deliverability test (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/canonical_descriptions.py
index 1c2240c34d16..b3d4a3856f43 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/canonical_descriptions.py
@@ -161,6 +161,74 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"opportunities": "Opportunities created that day.",
},
},
+ "campaign_step_analytics": {
+ "description": "Per-campaign analytics for each sequence step and A/B variant: sends, opens, replies, clicks, and opportunities.",
+ "docs_url": "https://developer.instantly.ai/api-reference/campaign/get-campaign-steps-analytics",
+ "columns": {
+ "campaign_id": "Campaign the step belongs to (UUID).",
+ "step": "Step number in the campaign sequence. Null when the API cannot attribute the event to a step.",
+ "variant": "A/B variant number, starting from 0 (0 = A, 1 = B, and so on). Null when the API cannot attribute the event to a variant.",
+ "sent": "Total emails sent for this step and variant.",
+ "opened": "Total email opens.",
+ "unique_opened": "Unique leads that opened an email.",
+ "replies": "Total replies received.",
+ "unique_replies": "Unique leads that replied.",
+ "replies_automatic": "Automatic replies (such as out-of-office) detected.",
+ "unique_replies_automatic": "Unique leads that sent an automatic reply.",
+ "clicks": "Total tracked link clicks.",
+ "unique_clicks": "Unique leads that clicked a link.",
+ "opportunities": "Opportunities created from this step.",
+ "unique_opportunities": "Unique leads with an opportunity created from this step.",
+ },
+ },
+ "account_daily_analytics": {
+ "description": "Daily analytics per sending account: sends, bounces, contacts, opens, replies, and clicks.",
+ "docs_url": "https://developer.instantly.ai/api-reference/account/get-daily-account-analytics",
+ "columns": {
+ "date": "Day the analytics row covers, in YYYY-MM-DD format.",
+ "email_account": "Sending email account the row covers.",
+ "sent": "Campaign emails sent that day by this account, including subsequence emails.",
+ "bounced": "Campaign emails from this account that bounced that day, including subsequence emails.",
+ "contacted": "Unique contacts emailed that day from this account.",
+ "new_leads_contacted": "Leads reached for the first time that day from this account.",
+ "opened": "Total email opens that day for this account.",
+ "unique_opened": "Unique leads that opened an email from this account that day.",
+ "replies": "Total replies received that day for this account.",
+ "unique_replies": "Unique leads that replied to this account that day.",
+ "replies_automatic": "Automatic replies detected that day for this account.",
+ "unique_replies_automatic": "Unique leads that sent an automatic reply to this account that day.",
+ "clicks": "Total tracked link clicks that day for this account.",
+ "unique_clicks": "Unique leads that clicked a link from this account that day.",
+ },
+ },
+ "custom_tag_mappings": {
+ "description": "An assignment of a custom tag to a campaign or a sending account.",
+ "docs_url": "https://developer.instantly.ai/api-reference/customtagmapping/list-custom-tag-mapping",
+ "columns": {
+ "id": "Unique identifier of the mapping (UUID).",
+ "tag_id": "Custom tag assigned by this mapping. Joins to custom_tags.id.",
+ "resource_id": "Campaign or account the tag is assigned to.",
+ "resource_type": "Type of the tagged resource: 1 campaign, 2 account.",
+ "timestamp_created": "When the mapping was created.",
+ "organization_id": "Workspace (organization) that owns the mapping.",
+ },
+ },
+ "subsequences": {
+ "description": "A follow-up subsequence attached to a campaign, with its trigger conditions, schedule, and email steps.",
+ "docs_url": "https://developer.instantly.ai/api-reference/campaignsubsequence/list-campaign-subsequence",
+ "columns": {
+ "id": "Unique identifier of the subsequence (UUID).",
+ "parent_campaign": "Campaign the subsequence belongs to. Joins to campaigns.id.",
+ "workspace": "Workspace the subsequence belongs to.",
+ "name": "Name of the subsequence.",
+ "status": "Subsequence status, using the same codes as campaign status.",
+ "conditions": "Conditions that move a lead into the subsequence.",
+ "subsequence_schedule": "Sending schedule of the subsequence.",
+ "sequences": "Email steps of the subsequence. Only the first element is used.",
+ "timestamp_created": "When the subsequence was created.",
+ "timestamp_leads_updated": "When the subsequence's leads were last updated.",
+ },
+ },
"webhook_events": {
"description": "Raw Instantly webhook event stream: sends, opens, replies, bounces, and lead status changes as they happen.",
"docs_url": "https://developer.instantly.ai/guides/webhook-events",
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.py
index 52c355fc9819..abd428e6dde9 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
@@ -2,7 +2,8 @@ import time
import hashlib
import secrets
import dataclasses
-from datetime import datetime
+from collections.abc import Callable, Iterable, Iterator
+from datetime import date, datetime
from typing import Any, Optional
import orjson
@@ -20,10 +21,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
+ RESTClient,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
JSONResponseCursorPaginator,
+ SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
Endpoint,
@@ -33,6 +38,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.settings import (
+ ANALYTICS_HISTORY_START_DATE,
BASE_URL,
DEFAULT_PAGE_SIZE,
EMAILS_REQUEST_INTERVAL_SECONDS,
@@ -42,6 +48,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.
)
REQUEST_TIMEOUT_SECONDS = 30
+# (connect, read). Analytics responses can span years of rows, so reads get more room than probes.
+SYNC_REQUEST_TIMEOUT_SECONDS = (10, 120)
# Bounded walk of the webhook list when reconciling ours by URL — a workspace won't have
# thousands of webhooks, so this is a defensive cap, not an expected limit.
MAX_WEBHOOK_LIST_PAGES = 10
@@ -61,7 +69,7 @@ WEBHOOK_SCOPE_ERROR = (
)
[email protected](frozen=True)
class InstantlyResumeConfig:
cursor: str
@@ -105,6 +113,12 @@ def _format_incremental_timestamp(value: Any) -> str:
return str(value)
+def _format_incremental_date(value: Any) -> str:
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%d")
+ return str(value)[:10]
+
+
def _make_paginator(config: InstantlyEndpointConfig) -> InstantlyCursorPaginator:
if config.name == "emails":
return InstantlyThrottledCursorPaginator(EMAILS_REQUEST_INTERVAL_SECONDS)
@@ -188,6 +202,20 @@ def instantly_source(
config = INSTANTLY_ENDPOINTS[endpoint]
+ if config.campaign_fanout is not None:
+ fanout_client = _make_client(api_key)
+ return _source_response(config, lambda: _campaign_fanout_pages(fanout_client, config), supports_resume=False)
+ if config.date_windowed:
+ windowed_client = _make_client(api_key)
+ start_date = (
+ _format_incremental_date(db_incremental_field_last_value)
+ if should_use_incremental_field and db_incremental_field_last_value is not None
+ else ANALYTICS_HISTORY_START_DATE
+ )
+ return _source_response(
+ config, lambda: _date_windowed_pages(windowed_client, config, start_date), supports_resume=False
+ )
+
rest_config: RESTAPIConfig = {
"client": {
"base_url": BASE_URL,
@@ -199,6 +227,7 @@ def instantly_source(
"Accept": "application/json",
"Content-Type": "application/json",
},
+ "request_timeout": SYNC_REQUEST_TIMEOUT_SECONDS,
},
"resource_defaults": {},
"resources": [get_resource(endpoint, should_use_incremental_field)],
@@ -224,9 +253,16 @@ def instantly_source(
initial_paginator_state=initial_paginator_state,
)
+ return _source_response(config, lambda: resource)
+
+
+def _source_response(
+ config: InstantlyEndpointConfig, items: Callable[[], Iterable[Any]], supports_resume: bool = True
+) -> SourceResponse:
return SourceResponse(
- name=endpoint,
- items=lambda: resource,
+ name=config.name,
+ items=items,
+ supports_resume=supports_resume,
primary_keys=config.primary_keys,
sort_mode="asc",
partition_count=1 if config.partition_key else None,
@@ -237,6 +273,65 @@ def instantly_source(
)
+def _make_client(api_key: str) -> RESTClient:
+ return RESTClient(
+ base_url=BASE_URL,
+ headers={"Accept": "application/json"},
+ auth=BearerTokenAuth(api_key),
+ request_timeout=SYNC_REQUEST_TIMEOUT_SECONDS,
+ )
+
+
+def _list_request(config: InstantlyEndpointConfig) -> tuple[dict[str, Any], BasePaginator]:
+ if config.pagination == "single":
+ return dict(config.params), SinglePagePaginator()
+ return {**config.params, "limit": DEFAULT_PAGE_SIZE}, InstantlyCursorPaginator()
+
+
+def _campaign_fanout_pages(client: RESTClient, config: InstantlyEndpointConfig) -> Iterator[list[dict[str, Any]]]:
+ """Walk every campaign and fetch the endpoint once per campaign.
+
+ Fan-out endpoints don't resume: a retry re-walks the campaigns from scratch.
+ """
+ fanout = config.campaign_fanout
+ assert fanout is not None
+ campaigns = INSTANTLY_ENDPOINTS["campaigns"]
+ for campaign_page in client.paginate(
+ path=f"/api/v2{campaigns.path}",
+ params={"limit": DEFAULT_PAGE_SIZE},
+ paginator=InstantlyCursorPaginator(),
+ data_selector=campaigns.data_selector,
+ ):
+ for campaign in campaign_page:
+ campaign_id = campaign.get("id")
+ if not campaign_id:
+ continue
+ params, paginator = _list_request(config)
+ for page in client.paginate(
+ path=f"/api/v2{config.path}",
+ params={**params, fanout.param: campaign_id},
+ paginator=paginator,
+ data_selector=config.data_selector,
+ ):
+ if fanout.stamp_field:
+ page = [{**row, fanout.stamp_field: campaign_id} for row in page]
+ if page:
+ yield page
+
+
+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 ""))
+
+
def _webhook_events_source(webhook_source_manager: Optional[WebhookSourceManager]) -> SourceResponse:
webhook_enabled = (
async_to_sync(webhook_source_manager.webhook_enabled)(webhook_only=True)
@@ -277,9 +372,14 @@ def _probe_endpoint(session: requests.Session, endpoint: str) -> requests.Respon
return session.post(url, json={"limit": 1}, timeout=REQUEST_TIMEOUT_SECONDS)
if config.pagination == "single":
# Analytics endpoints have no limit param; a one-day window keeps the probe cheap.
- params = {"start_date": "2024-01-01", "end_date": "2024-01-01", "exclude_total_leads_count": "true"}
+ params = {
+ "start_date": "2024-01-01",
+ "end_date": "2024-01-01",
+ "exclude_total_leads_count": "true",
+ **config.probe_params,
+ }
return session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
- return session.get(url, params={"limit": 1}, timeout=REQUEST_TIMEOUT_SECONDS)
+ return session.get(url, params={"limit": 1, **config.probe_params}, timeout=REQUEST_TIMEOUT_SECONDS)
def _error_message(response: requests.Response) -> str | None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/settings.py
index ea3819b9f395..7a981ea48688 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/settings.py
@@ -2,7 +2,7 @@ from dataclasses import dataclass, field
from typing import Any, Literal, Optional
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
-from products.warehouse_sources.backend.types import IncrementalField
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
BASE_URL = "https://api.instantly.ai"
API_VERSION = "v2"
@@ -14,6 +14,13 @@ DEFAULT_PAGE_SIZE = 100
# unpublished limits), so the emails stream self-throttles between pages.
EMAILS_REQUEST_INTERVAL_SECONDS = 3.0
+# Date-windowed analytics endpoints default to the last 30 days when start_date is omitted, so
+# full refresh asks for everything since before Instantly's API existed.
+ANALYTICS_HISTORY_START_DATE = "2020-01-01"
+
+# Placeholder parent id for scope probes against endpoints that require a campaign id.
+PROBE_CAMPAIGN_ID = "00000000-0000-0000-0000-000000000000"
+
# Webhook-fed event stream (no pull API — Instantly webhooks deliver event notifications,
# not full objects, so they get their own table instead of merging into the pull tables).
WEBHOOK_EVENTS_ENDPOINT = "webhook_events"
@@ -21,7 +28,15 @@ WEBHOOK_EVENTS_ENDPOINT = "webhook_events"
WEBHOOK_ROUTING_KEY = "event"
-@dataclass
+@dataclass(frozen=True)
+class CampaignFanout:
+ # Query param that scopes each request to one campaign.
+ param: str
+ # Column stamped with the campaign id, for rows that don't carry it themselves.
+ stamp_field: Optional[str] = None
+
+
+@dataclass(frozen=True)
class InstantlyEndpointConfig:
name: str
# Path under https://api.instantly.ai/api/v2.
@@ -40,6 +55,12 @@ class InstantlyEndpointConfig:
partition_key: Optional[str] = "timestamp_created"
# Only emails exposes a server-side timestamp filter (min_timestamp_created + sort_order=asc).
supports_incremental: bool = False
+ # Single-page endpoint windowed by start_date: incremental syncs pass the last synced date.
+ date_windowed: bool = False
+ # Set on endpoints the API scopes to one campaign per request; they fan out over campaigns.
+ campaign_fanout: Optional[CampaignFanout] = None
+ # Extra params the credential/scope probe needs (e.g. a required campaign id).
+ probe_params: dict[str, Any] = field(default_factory=dict)
description: Optional[str] = None
@@ -106,10 +127,46 @@ INSTANTLY_ENDPOINTS: dict[str, InstantlyEndpointConfig] = {
partition_key=None,
description="Workspace-wide daily campaign analytics: sends, opens, replies, and clicks per day.",
),
+ "campaign_step_analytics": InstantlyEndpointConfig(
+ name="campaign_step_analytics",
+ path="/campaigns/analytics/steps",
+ pagination="single",
+ data_selector=None,
+ params={"include_opportunities_count": "true"},
+ # Rows carry no campaign id, and without campaign_id the API sums steps across campaigns.
+ campaign_fanout=CampaignFanout(param="campaign_id", stamp_field="campaign_id"),
+ # step/variant are null for events the API can't attribute to a step.
+ primary_keys=["campaign_id", "step", "variant"],
+ partition_key=None,
+ description="Per-campaign analytics for each sequence step and A/B variant: sends, opens, replies, clicks, and opportunities.",
+ ),
+ "account_daily_analytics": InstantlyEndpointConfig(
+ name="account_daily_analytics",
+ path="/accounts/analytics/daily",
+ pagination="single",
+ data_selector=None,
+ date_windowed=True,
+ primary_keys=["date", "email_account"],
+ partition_key=None,
+ description="Daily analytics per sending account: sends, bounces, contacts, opens, replies, and clicks.",
+ ),
+ "custom_tag_mappings": InstantlyEndpointConfig(
+ name="custom_tag_mappings",
+ path="/custom-tag-mappings",
+ description="Assignments of custom tags to campaigns and sending accounts.",
+ ),
+ "subsequences": InstantlyEndpointConfig(
+ name="subsequences",
+ path="/subsequences",
+ campaign_fanout=CampaignFanout(param="parent_campaign"),
+ probe_params={"parent_campaign": PROBE_CAMPAIGN_ID},
+ description="Follow-up subsequences attached to campaigns, with their trigger conditions, schedules, and email steps.",
+ ),
}
ENDPOINTS = tuple(INSTANTLY_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
"emails": [incremental_field("timestamp_created")],
+ "account_daily_analytics": [incremental_field("date", IncrementalFieldType.Date)],
}
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.py
index d1ce583768cb..b2a3c749f519 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
@@ -1,5 +1,5 @@
from collections.abc import Iterable
-from datetime import UTC, datetime
+from datetime import UTC, date, datetime
import pytest
from unittest import mock
@@ -8,12 +8,15 @@ from requests import Request
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list
from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.instantly import (
+ SYNC_REQUEST_TIMEOUT_SECONDS,
WEBHOOK_PLAN_ERROR,
WEBHOOK_SECRET_HEADER,
InstantlyCursorPaginator,
InstantlyResumeConfig,
InstantlyThrottledCursorPaginator,
+ _format_incremental_date,
_format_incremental_timestamp,
+ _probe_endpoint,
_webhook_events_table_transformer,
create_webhook,
delete_webhook,
@@ -22,10 +25,24 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.
instantly_source,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.settings import (
+ ANALYTICS_HISTORY_START_DATE,
+ PROBE_CAMPAIGN_ID,
+)
MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.instantly.instantly"
+class _FakeClient:
+ def __init__(self, pages_by_path: dict[str, list[list[dict]]]):
+ self.pages_by_path = pages_by_path
+ self.calls: list[tuple[str, dict]] = []
+
+ def paginate(self, *, path, params, paginator, data_selector):
+ self.calls.append((path, params))
+ yield from self.pages_by_path.get(path, [])
+
+
def _response(body=None, status_code=200):
response = mock.MagicMock()
response.status_code = status_code
@@ -156,6 +173,106 @@ class TestInstantly:
def test_format_incremental_timestamp(self, value, expected):
assert _format_incremental_timestamp(value) == expected
+ @pytest.mark.parametrize(
+ "value,expected",
+ [
+ (date(2026, 1, 2), "2026-01-02"),
+ (datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "2026-01-02"),
+ ("2026-01-02", "2026-01-02"),
+ ("2026-01-02T00:00:00", "2026-01-02"),
+ ],
+ )
+ def test_format_incremental_date(self, value, expected):
+ assert _format_incremental_date(value) == expected
+
+ @pytest.mark.parametrize(
+ "endpoint,child_path,child_page,expected_params,expected_rows",
+ [
+ (
+ "campaign_step_analytics",
+ "/api/v2/campaigns/analytics/steps",
+ [{"step": "1", "variant": "0", "sent": 5}],
+ {"include_opportunities_count": "true", "campaign_id": "c-1"},
+ # Step rows carry no campaign id, so the fan-out stamps it for the composite key.
+ [{"step": "1", "variant": "0", "sent": 5, "campaign_id": "c-1"}],
+ ),
+ (
+ "subsequences",
+ "/api/v2/subsequences",
+ [{"id": "s-1", "parent_campaign": "c-1"}],
+ {"limit": 100, "parent_campaign": "c-1"},
+ [{"id": "s-1", "parent_campaign": "c-1"}],
+ ),
+ ],
+ )
+ def test_campaign_fanout_scopes_each_request_to_one_campaign(
+ self, endpoint, child_path, child_page, expected_params, expected_rows
+ ):
+ client = _FakeClient(
+ {
+ "/api/v2/campaigns": [[{"id": "c-1"}, {"name": "no id"}]],
+ child_path: [child_page],
+ }
+ )
+
+ with mock.patch(f"{MODULE}._make_client", return_value=client):
+ response = instantly_source(
+ api_key="key", endpoint=endpoint, team_id=1, job_id="job", resumable_source_manager=mock.MagicMock()
+ )
+ items = response.items()
+ assert isinstance(items, Iterable)
+ pages = list(items)
+
+ assert pages == [expected_rows]
+ # The fan-out keeps no cursor, so the pipeline must not treat the run as resumable.
+ assert response.supports_resume is False
+ # 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
+ ):
+ 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):
+ 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,
+ )
+ items = response.items()
+ assert isinstance(items, Iterable)
+ pages = list(items)
+
+ assert client.calls == [("/api/v2/accounts/analytics/daily", {"start_date": expected_start_date})]
+ # 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"]
+
+ def test_probe_sends_required_campaign_id_for_subsequences(self):
+ session = mock.MagicMock()
+
+ _probe_endpoint(session, "subsequences")
+
+ assert session.get.call_args.kwargs["params"] == {"limit": 1, "parent_campaign": PROBE_CAMPAIGN_ID}
+
@pytest.mark.parametrize(
"endpoint,expected_primary_keys,expected_partition_mode",
[
@@ -182,6 +299,8 @@ class TestInstantly:
assert response.name == endpoint
assert response.primary_keys == expected_primary_keys
assert response.partition_mode == expected_partition_mode
+ rest_config = mock_resource.call_args.args[0]
+ assert rest_config["client"]["request_timeout"] == SYNC_REQUEST_TIMEOUT_SECONDS
@mock.patch(f"{MODULE}.rest_api_resource")
def test_resume_state_seeds_paginator_and_saves_after_batches(self, mock_resource):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly_source.py
index 67aab7bf2ff8..3b5a174e1427 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly_source.py
@@ -17,13 +17,16 @@ class TestInstantlySource:
self.team_id = 123
self.config = InstantlySourceConfig(api_key="test-key")
- def test_get_schemas_only_emails_supports_incremental(self):
+ def test_get_schemas_only_server_filtered_endpoints_support_incremental(self):
schemas = self.source.get_schemas(self.config, self.team_id)
assert {schema.name for schema in schemas} == {*ENDPOINTS, WEBHOOK_EVENTS_ENDPOINT}
- # Only /emails exposes a server-side timestamp filter (min_timestamp_created); everything
- # else must ship full refresh.
- assert {schema.name for schema in schemas if schema.supports_incremental} == {"emails"}
+ # Only /emails (min_timestamp_created) and /accounts/analytics/daily (start_date) expose a
+ # server-side filter; everything else must ship full refresh.
+ assert {schema.name for schema in schemas if schema.supports_incremental} == {
+ "emails",
+ "account_daily_analytics",
+ }
def test_get_schemas_webhook_events_is_webhook_only(self):
schemas = self.source.get_schemas(self.config, self.team_id)