: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
feat(data-warehouse): add 5 missing tables to the Instantly source (#118923)
Tom Owersd4f0c32ec99d
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.mdindex e4f3b16ad00b..76d934e431a8 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@@ -6360,10 +6360,10 @@ Diffed against: <https://developer.instantly.ai/api-reference/openapi.json>- [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)-- [ ] `GET /api/v2/audit-logs` — workspace change history for attribution and compliance (medium)+- [x] `GET /api/v2/block-lists-entries` — suppression list explaining why leads were never contacted (medium)+- [x] `POST /api/v2/accounts/warmup-analytics` — read-shaped per-account warmup health scores (medium)+- [x] `GET /api/v2/inbox-placement-analytics + /inbox-placement-reports` — inbox vs spam placement results per deliverability test (medium)+- [x] `GET /api/v2/audit-logs` — workspace change history for attribution and compliance (medium)- [ ] `GET /api/v2/campaigns/analytics/overview` — aggregate campaign KPI rollup (low)- [ ] `GET /api/v2/workspace-members` — membership lookup for user IDs on campaigns and leads (low)- [ ] `GET /api/v2/lead-lists/{id}/verification-stats` — email verification quality per lead list (low)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.pyindex b3d4a3856f43..9f615a0f2b02 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@@ -229,6 +229,94 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"timestamp_leads_updated": "When the subsequence's leads were last updated.",},},+ "block_list_entries": {+ "description": "A blocked email address or domain. Instantly does not send to leads that match a block list entry.",+ "docs_url": "https://developer.instantly.ai/api-reference/blocklistentry/list-block-list-entry",+ "columns": {+ "id": "Unique identifier of the block list entry (UUID).",+ "timestamp_created": "When the block list entry was created.",+ "organization_id": "Workspace (organization) that owns the block list entry.",+ "bl_value": "The blocked email address or domain.",+ "is_domain": "Whether the entry blocks a whole domain rather than one email address.",+ },+ },+ "account_warmup_analytics": {+ "description": "Warmup totals and health score of a sending account.",+ "docs_url": "https://developer.instantly.ai/api-reference/account/get-warmup-analytics",+ "columns": {+ "email": "Email address of the sending account. Joins to accounts.email.",+ "sent": "Number of warmup emails the account sent.",+ "received": "Number of warmup emails the account received.",+ "landed_inbox": "Number of warmup emails that landed in the inbox.",+ "landed_spam": "Number of warmup emails that landed in spam.",+ "health_score": "Warmup health score of the account.",+ "health_score_label": "Label of the warmup health score.",+ },+ },+ "inbox_placement_analytics": {+ "description": "One email of an inbox placement test, with where it landed and its authentication results.",+ "docs_url": "https://developer.instantly.ai/api-reference/inboxplacementanalytics/list-inbox-placement-analytics",+ "columns": {+ "id": "Unique identifier of the inbox placement analytics entry (UUID).",+ "test_id": "Inbox placement test the entry belongs to.",+ "timestamp_created": "When the entry was created.",+ "timestamp_created_date": "Date when the entry was created.",+ "organization_id": "Workspace (organization) the entry belongs to.",+ "record_type": "Whether the record is for a sent or a received email.",+ "is_spam": "Whether the email landed in spam. Only set on received records.",+ "has_category": "Whether the email landed in a category tab such as promotions or social. Only set on received records.",+ "sender_email": "Email address of the sender.",+ "sender_esp": "Email service provider of the sender. Only set on received records.",+ "recipient_email": "Email address of the recipient.",+ "recipient_esp": "Email service provider of the recipient.",+ "recipient_geo": "Geographic location of the recipient.",+ "recipient_type": "Type of the recipient.",+ "spf_pass": "Whether the email passed SPF validation. Only set on received records.",+ "dkim_pass": "Whether the email passed DKIM validation. Only set on received records.",+ "dmarc_pass": "Whether the email passed DMARC validation. Only set on received records.",+ "smtp_ip_blacklist_report": "Blacklist report of the SMTP IP address. Only set on received records.",+ "authentication_failure_results": "Details of SPF, DKIM, and DMARC failures. Only set on received records.",+ },+ },+ "inbox_placement_reports": {+ "description": "Blacklist and SpamAssassin report of a sending domain in an inbox placement test.",+ "docs_url": "https://developer.instantly.ai/api-reference/inboxplacementblacklistandspamassassinreport/list-inbox-placement-blacklist-and-spamassassin-report",+ "columns": {+ "id": "Unique identifier of the inbox placement report entry (UUID).",+ "test_id": "Inbox placement test the report belongs to.",+ "timestamp_created": "When the report was created.",+ "timestamp_created_date": "Date when the report was created.",+ "organization_id": "Workspace (organization) the report belongs to.",+ "domain": "Sending domain of the report.",+ "domain_ip": "IP address of the domain.",+ "domain_blacklist_count": "Number of blacklists the domain is listed on.",+ "domain_ip_blacklist_count": "Number of blacklists the domain IP address is listed on.",+ "spam_assassin_score": "SpamAssassin score of the email. A higher score means the email is more likely spam.",+ "spam_assassin_report": "Detailed SpamAssassin analysis, with each rule that matched and its score.",+ "blacklist_report": "Detailed blacklist results of the domain or IP address, per blacklist.",+ },+ },+ "audit_logs": {+ "description": "An activity in the workspace: who did what, when, and from where.",+ "docs_url": "https://developer.instantly.ai/api-reference/auditlog/list-audit-log",+ "columns": {+ "id": "Unique identifier of the audit log entry (UUID).",+ "timestamp": "When the activity occurred.",+ "organization_id": "Workspace (organization) the activity belongs to.",+ "activity_type": "Numeric code of the activity type.",+ "user_id": "User who did the activity.",+ "user_name": "Name of the user who did the activity.",+ "user_agent": "User agent of the client that did the activity.",+ "ip_address": "IP address the activity came from.",+ "from_api": "Whether the activity came through the API.",+ "affected_count": "Number of items the activity affected.",+ "campaign_id": "Campaign the activity relates to, if any. Joins to campaigns.id.",+ "webhook_id": "Webhook the activity relates to, if any.",+ "subsequence_id": "Subsequence the activity relates to, if any. Joins to subsequences.id.",+ "list_id": "Lead list the activity relates to, if any. Joins to lead_lists.id.",+ "audit_metadata": "Additional details about the activity.",+ },+ },"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.pyindex 28ce037ff3be..d31908036a68 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@@ -45,6 +45,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.DEFAULT_PAGE_SIZE,EMAILS_REQUEST_INTERVAL_SECONDS,INSTANTLY_ENDPOINTS,+ WARMUP_ANALYTICS_BATCH_SIZE,WEBHOOK_EVENTS_ENDPOINT,InstantlyEndpointConfig,)@@ -149,12 +150,13 @@ def get_resource(endpoint: str, should_use_incremental_field: bool) -> EndpointRelse:endpoint_config["paginator"] = _make_paginator(config)params: dict[str, Any] = {**config.params, "limit": DEFAULT_PAGE_SIZE}- if config.supports_incremental and should_use_incremental_field:- params["min_timestamp_created"] = {+ incremental_filter = config.incremental_filter+ if incremental_filter is not None and should_use_incremental_field:+ params[incremental_filter.param] = {"type": "incremental",- "cursor_path": "timestamp_created",- "initial_value": "1970-01-01T00:00:00.000Z",- "convert": _format_incremental_timestamp,+ "cursor_path": incremental_filter.cursor_field,+ "initial_value": incremental_filter.initial_value,+ "convert": _format_incremental_date if incremental_filter.date_only else _format_incremental_timestamp,}endpoint_config["params"] = params@@ -207,9 +209,12 @@ def instantly_source(config = INSTANTLY_ENDPOINTS[endpoint]- if config.campaign_fanout is not None:+ if config.fanout is not None:fanout_client = _make_client(api_key)- return _source_response(config, lambda: _campaign_fanout_pages(fanout_client, config), supports_resume=False)+ return _source_response(config, lambda: _fanout_pages(fanout_client, config), supports_resume=False)+ if config.account_email_batches:+ batch_client = _make_client(api_key)+ return _source_response(config, lambda: _account_email_batch_pages(batch_client, config), supports_resume=False)if config.date_windowed:windowed_client = _make_client(api_key)start_date = (@@ -269,7 +274,7 @@ def _source_response(items=items,supports_resume=supports_resume,primary_keys=config.primary_keys,- sort_mode="asc",+ sort_mode=config.sort_mode,partition_count=1 if config.partition_key else None,partition_size=1 if config.partition_key else None,partition_mode="datetime" if config.partition_key else None,@@ -293,37 +298,67 @@ def _list_request(config: InstantlyEndpointConfig) -> tuple[dict[str, Any], Basereturn {**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.+def _fanout_pages(client: RESTClient, config: InstantlyEndpointConfig) -> Iterator[list[dict[str, Any]]]:+ """Walk every parent (campaign or inbox placement test) and fetch the endpoint once per parent.- Fan-out endpoints don't resume: a retry re-walks the campaigns from scratch.+ Fan-out endpoints don't resume: a retry re-walks the parents from scratch."""- fanout = config.campaign_fanout+ fanout = config.fanoutassert fanout is not None- campaigns = INSTANTLY_ENDPOINTS["campaigns"]- for campaign_page in client.paginate(- path=f"/api/v2{campaigns.path}",+ for parent_page in client.paginate(+ path=f"/api/v2{fanout.parent_path}",params={"limit": DEFAULT_PAGE_SIZE},paginator=InstantlyCursorPaginator(),- data_selector=campaigns.data_selector,+ data_selector="items",):- for campaign in campaign_page:- campaign_id = campaign.get("id")- if not campaign_id:+ for parent in parent_page:+ parent_id = parent.get("id")+ if not parent_id:continueparams, paginator = _list_request(config)for page in client.paginate(path=f"/api/v2{config.path}",- params={**params, fanout.param: campaign_id},+ params={**params, fanout.param: parent_id},paginator=paginator,data_selector=config.data_selector,):if fanout.stamp_field:- page = [{**row, fanout.stamp_field: campaign_id} for row in page]+ page = [{**row, fanout.stamp_field: parent_id} for row in page]if page:yield page+def _account_email_batch_pages(client: RESTClient, config: InstantlyEndpointConfig) -> Iterator[list[dict[str, Any]]]:+ """POST the sending account emails in batches and flatten the per-email stats map into rows."""+ accounts = INSTANTLY_ENDPOINTS["accounts"]+ for account_page in client.paginate(+ path=f"/api/v2{accounts.path}",+ params={"limit": DEFAULT_PAGE_SIZE},+ paginator=InstantlyCursorPaginator(),+ data_selector=accounts.data_selector,+ ):+ emails = [account["email"] for account in account_page if account.get("email")]+ for start in range(0, len(emails), WARMUP_ANALYTICS_BATCH_SIZE):+ for page in client.paginate(+ path=f"/api/v2{config.path}",+ method="post",+ json={"emails": emails[start : start + WARMUP_ANALYTICS_BATCH_SIZE]},+ paginator=SinglePagePaginator(),+ data_selector=config.data_selector,+ ):+ # aggregate_data is one object keyed by email, not a row list.+ stats_maps = page if isinstance(page, list) else [page]+ rows = [+ {**stats, "email": email}+ for stats_by_email in stats_maps+ if isinstance(stats_by_email, dict)+ for email, stats in stats_by_email.items()+ if isinstance(stats, dict)+ ]+ if rows:+ yield rows++def _today() -> date:return datetime.now(UTC).date()@@ -391,6 +426,9 @@ def _probe_endpoint(session: requests.Session, endpoint: str) -> requests.Responreturn session.get(f"{BASE_URL}/api/v2/webhooks", params={"limit": 1}, timeout=REQUEST_TIMEOUT_SECONDS)config = INSTANTLY_ENDPOINTS[endpoint]+ if config.account_email_batches:+ # Same accounts:read scope as /accounts, which needs no email list in the request.+ return session.get(f"{BASE_URL}/api/v2/accounts", params={"limit": 1}, timeout=REQUEST_TIMEOUT_SECONDS)url = f"{BASE_URL}/api/v2{config.path}"if config.method == "POST":return session.post(url, json={"limit": 1}, timeout=REQUEST_TIMEOUT_SECONDS)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.pyindex 7a981ea48688..cb4cf3e1f5ac 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@@ -18,8 +18,11 @@ EMAILS_REQUEST_INTERVAL_SECONDS = 3.0# 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"+# Placeholder parent id for scope probes against endpoints that require a campaign or test id.+PROBE_PARENT_ID = "00000000-0000-0000-0000-000000000000"++# POST /api/v2/accounts/warmup-analytics accepts at most 100 account emails per request.+WARMUP_ANALYTICS_BATCH_SIZE = 100# 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).@@ -29,11 +32,24 @@ WEBHOOK_ROUTING_KEY = "event"@dataclass(frozen=True)-class CampaignFanout:- # Query param that scopes each request to one campaign.+class ParentFanout:+ # Query param that scopes each request to one parent.param: str- # Column stamped with the campaign id, for rows that don't carry it themselves.+ # Column stamped with the parent id, for rows that don't carry it themselves.stamp_field: Optional[str] = None+ # Cursor-paginated list endpoint the parent ids come from.+ parent_path: str = "/campaigns"+++@dataclass(frozen=True)+class IncrementalFilter:+ # Server-side lower-bound filter param.+ param: str+ # Row field the filter compares against.+ cursor_field: str+ initial_value: str+ # The filter takes a YYYY-MM-DD date rather than a full timestamp.+ date_only: bool = False@dataclass(frozen=True)@@ -53,12 +69,17 @@ class InstantlyEndpointConfig:primary_keys: list[str] = field(default_factory=lambda: ["id"])# Stable creation-time field for datetime partitioning. Never an updated_at-style field.partition_key: Optional[str] = "timestamp_created"- # Only emails exposes a server-side timestamp filter (min_timestamp_created + sort_order=asc).- supports_incremental: bool = False+ # Set only on endpoints with a server-side lower-bound filter.+ incremental_filter: Optional[IncrementalFilter] = None+ # Order rows arrive in. "desc" also covers endpoints whose order is undocumented, because the+ # pipeline then promotes the watermark only when the run ends.+ sort_mode: Literal["asc", "desc"] = "asc"# 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+ # Set on endpoints the API scopes to one parent per request; they fan out over the parents.+ fanout: Optional[ParentFanout] = None+ # POST endpoint that takes a list of sending account emails; it fans out over account batches.+ account_email_batches: bool = False# 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@@ -91,7 +112,11 @@ INSTANTLY_ENDPOINTS: dict[str, InstantlyEndpointConfig] = {# sort_order=asc keeps arrival order matching sort_mode="asc" so the incremental# watermark can checkpoint safely (the API defaults to newest-first).params={"sort_order": "asc"},- supports_incremental=True,+ incremental_filter=IncrementalFilter(+ param="min_timestamp_created",+ cursor_field="timestamp_created",+ initial_value="1970-01-01T00:00:00.000Z",+ ),description="Sent and received emails from campaigns and the unified inbox (Unibox).",),"lead_lists": InstantlyEndpointConfig(@@ -134,7 +159,7 @@ INSTANTLY_ENDPOINTS: dict[str, InstantlyEndpointConfig] = {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"),+ fanout=ParentFanout(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,@@ -158,10 +183,58 @@ INSTANTLY_ENDPOINTS: dict[str, InstantlyEndpointConfig] = {"subsequences": InstantlyEndpointConfig(name="subsequences",path="/subsequences",- campaign_fanout=CampaignFanout(param="parent_campaign"),- probe_params={"parent_campaign": PROBE_CAMPAIGN_ID},+ fanout=ParentFanout(param="parent_campaign"),+ probe_params={"parent_campaign": PROBE_PARENT_ID},description="Follow-up subsequences attached to campaigns, with their trigger conditions, schedules, and email steps.",),+ "block_list_entries": InstantlyEndpointConfig(+ name="block_list_entries",+ path="/block-lists-entries",+ description="Blocked email addresses and domains that Instantly never sends to.",+ ),+ "account_warmup_analytics": InstantlyEndpointConfig(+ name="account_warmup_analytics",+ path="/accounts/warmup-analytics",+ method="POST",+ pagination="single",+ # The response also has email_date_data (a per-day breakdown); the table keeps the+ # per-account totals and health score.+ data_selector="aggregate_data",+ account_email_batches=True,+ primary_keys=["email"],+ partition_key=None,+ description="Warmup totals and health score per sending account: warmup emails sent, received, and landed in inbox or spam.",+ ),+ "inbox_placement_analytics": InstantlyEndpointConfig(+ name="inbox_placement_analytics",+ path="/inbox-placement-analytics",+ fanout=ParentFanout(param="test_id", parent_path="/inbox-placement-tests"),+ probe_params={"test_id": PROBE_PARENT_ID},+ primary_keys=["test_id", "id"],+ description="Per-email results of inbox placement tests: whether each test email landed in inbox, spam, or a category tab, with SPF, DKIM, and DMARC results.",+ ),+ "inbox_placement_reports": InstantlyEndpointConfig(+ name="inbox_placement_reports",+ path="/inbox-placement-reports",+ fanout=ParentFanout(param="test_id", parent_path="/inbox-placement-tests"),+ probe_params={"test_id": PROBE_PARENT_ID},+ primary_keys=["test_id", "id"],+ description="Blacklist and SpamAssassin reports of inbox placement tests, per sending domain.",+ ),+ "audit_logs": InstantlyEndpointConfig(+ name="audit_logs",+ path="/audit-logs",+ partition_key="timestamp",+ incremental_filter=IncrementalFilter(+ param="start_date",+ cursor_field="timestamp",+ initial_value=ANALYTICS_HISTORY_START_DATE,+ date_only=True,+ ),+ # The API documents no sort order for audit logs and has no sort param.+ sort_mode="desc",+ description="Workspace activity history: who changed what, when, and from where.",+ ),}ENDPOINTS = tuple(INSTANTLY_ENDPOINTS.keys())@@ -169,4 +242,5 @@ ENDPOINTS = tuple(INSTANTLY_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {"emails": [incremental_field("timestamp_created")],"account_daily_analytics": [incremental_field("date", IncrementalFieldType.Date)],+ "audit_logs": [incremental_field("timestamp")],}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 79d4b6900a37..028ef0bc7488 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,6 @@from collections.abc import Iterablefrom datetime import UTC, date, datetime+from typing import Anyimport pytestfrom unittest import mock@@ -27,18 +28,24 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.)from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.settings import (ANALYTICS_HISTORY_START_DATE,- PROBE_CAMPAIGN_ID,+ PROBE_PARENT_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]]]):+ def __init__(self, pages_by_path: dict[str, list[Any]]):self.pages_by_path = pages_by_pathself.calls: list[tuple[str, dict]] = []-- def paginate(self, *, path, params, paginator, data_selector):+ self.json_bodies: list[dict] = []++ def paginate(self, *, path, paginator, data_selector, params=None, method="get", json=None):+ if json is not None:+ self.json_bodies.append(json)+ pages = self.pages_by_path.get(path, [])+ yield pages[len(self.json_bodies) - 1] if len(self.json_bodies) <= len(pages) else {}+ returnself.calls.append((path, params))yield from self.pages_by_path.get(path, [])@@ -136,20 +143,33 @@ class TestInstantly:paginator.update_request(request)assert mock_sleep.call_count == 1- def test_emails_resource_sends_incremental_filter_only_when_enabled(self):- incremental = get_resource("emails", True)- full_refresh = get_resource("emails", False)+ @pytest.mark.parametrize(+ "endpoint,filter_param,cursor_path,formatted_last_value",+ [+ ("emails", "min_timestamp_created", "timestamp_created", "2026-01-02T03:04:05+00:00"),+ # The audit log filter takes a date, so the watermark's day is synced again and merged.+ ("audit_logs", "start_date", "timestamp", "2026-01-02"),+ ],+ )+ def test_resource_sends_incremental_filter_only_when_enabled(+ self, endpoint, filter_param, cursor_path, formatted_last_value+ ):+ incremental = get_resource(endpoint, True)+ full_refresh = get_resource(endpoint, False)- incremental_params = _endpoint_config(incremental)["params"]- assert incremental_params["min_timestamp_created"]["type"] == "incremental"- assert incremental_params["min_timestamp_created"]["cursor_path"] == "timestamp_created"- # sort_order=asc keeps arrival order matching sort_mode="asc" for watermark checkpointing.- assert incremental_params["sort_order"] == "asc"+ incremental_param = _endpoint_config(incremental)["params"][filter_param]+ assert incremental_param["type"] == "incremental"+ assert incremental_param["cursor_path"] == cursor_path+ assert incremental_param["convert"](datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)) == formatted_last_valueassert incremental["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}- assert "min_timestamp_created" not in _endpoint_config(full_refresh)["params"]+ assert filter_param not in _endpoint_config(full_refresh)["params"]assert full_refresh["write_disposition"] == "replace"+ def test_emails_resource_requests_ascending_order(self):+ # sort_order=asc keeps arrival order matching sort_mode="asc" for watermark checkpointing.+ assert _endpoint_config(get_resource("emails", True))["params"]["sort_order"] == "asc"+def test_leads_resource_is_post_with_json_body(self):endpoint = _endpoint_config(get_resource("leads", False))@@ -186,10 +206,11 @@ class TestInstantly:assert _format_incremental_date(value) == expected@pytest.mark.parametrize(- "endpoint,child_path,child_page,expected_params,expected_rows",+ "endpoint,parent_path,child_path,child_page,expected_params,expected_rows",[("campaign_step_analytics",+ "/api/v2/campaigns","/api/v2/campaigns/analytics/steps",[{"step": "1", "variant": "0", "sent": 5}],{"include_opportunities_count": "true", "campaign_id": "c-1"},@@ -198,19 +219,36 @@ class TestInstantly:),("subsequences",+ "/api/v2/campaigns","/api/v2/subsequences",[{"id": "s-1", "parent_campaign": "c-1"}],{"limit": 100, "parent_campaign": "c-1"},[{"id": "s-1", "parent_campaign": "c-1"}],),+ (+ "inbox_placement_analytics",+ "/api/v2/inbox-placement-tests",+ "/api/v2/inbox-placement-analytics",+ [{"id": "a-1", "test_id": "c-1", "is_spam": False}],+ {"limit": 100, "test_id": "c-1"},+ [{"id": "a-1", "test_id": "c-1", "is_spam": False}],+ ),+ (+ "inbox_placement_reports",+ "/api/v2/inbox-placement-tests",+ "/api/v2/inbox-placement-reports",+ [{"id": "r-1", "test_id": "c-1", "spam_assassin_score": 1.5}],+ {"limit": 100, "test_id": "c-1"},+ [{"id": "r-1", "test_id": "c-1", "spam_assassin_score": 1.5}],+ ),],)- def test_campaign_fanout_scopes_each_request_to_one_campaign(- self, endpoint, child_path, child_page, expected_params, expected_rows+ def test_fanout_scopes_each_request_to_one_parent(+ self, endpoint, parent_path, child_path, child_page, expected_params, expected_rows):client = _FakeClient({- "/api/v2/campaigns": [[{"id": "c-1"}, {"name": "no id"}]],+ parent_path: [[{"id": "c-1"}, {"name": "no id"}]],child_path: [child_page],})@@ -226,8 +264,40 @@ class TestInstantly: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)]+ # A parent without an id is skipped rather than sent as an unscoped request.+ assert client.calls == [(parent_path, {"limit": 100}), (child_path, expected_params)]++ def test_account_warmup_analytics_batches_account_emails_and_flattens_stats(self):+ accounts = [{"email": f"sender{i}@example.com"} for i in range(101)] + [{"name": "no email"}]+ stats = {"sent": 10, "received": 9, "landed_inbox": 8, "landed_spam": 1, "health_score": 90}+ client = _FakeClient(+ {+ "/api/v2/accounts": [accounts],+ "/api/v2/accounts/warmup-analytics": [+ {"[email protected]": stats, "[email protected]": None},+ # An empty aggregate_data (no warmup history) yields no rows.+ {},+ ],+ }+ )++ with mock.patch(f"{MODULE}._make_client", return_value=client):+ response = instantly_source(+ api_key="key",+ endpoint="account_warmup_analytics",+ team_id=1,+ job_id="job",+ resumable_source_manager=mock.MagicMock(),+ )+ items = response.items()+ assert isinstance(items, Iterable)+ pages = list(items)++ # The API takes at most 100 emails per request; an account without an email is not sent.+ assert [len(body["emails"]) for body in client.json_bodies] == [100, 1]+ assert client.json_bodies[1] == {"emails": ["[email protected]"]}+ assert pages == [[{**stats, "email": "[email protected]"}]]+ assert response.supports_resume is Falsedef test_account_daily_analytics_windows_by_start_date_and_sorts_rows(self):rows = [@@ -293,24 +363,45 @@ class TestInstantly:("/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):+ @pytest.mark.parametrize(+ "endpoint,expected_url,expected_params",+ [+ (+ "subsequences",+ "https://api.instantly.ai/api/v2/subsequences",+ {"limit": 1, "parent_campaign": PROBE_PARENT_ID},+ ),+ (+ "inbox_placement_reports",+ "https://api.instantly.ai/api/v2/inbox-placement-reports",+ {"limit": 1, "test_id": PROBE_PARENT_ID},+ ),+ # Warmup analytics needs account emails in a POST body; /accounts checks the same scope.+ ("account_warmup_analytics", "https://api.instantly.ai/api/v2/accounts", {"limit": 1}),+ ],+ )+ def test_probe_sends_required_params(self, endpoint, expected_url, expected_params):session = mock.MagicMock()- _probe_endpoint(session, "subsequences")+ _probe_endpoint(session, endpoint)- assert session.get.call_args.kwargs["params"] == {"limit": 1, "parent_campaign": PROBE_CAMPAIGN_ID}+ session.post.assert_not_called()+ assert session.get.call_args.args[0] == expected_url+ assert session.get.call_args.kwargs["params"] == expected_params@pytest.mark.parametrize(- "endpoint,expected_primary_keys,expected_partition_mode",+ "endpoint,expected_primary_keys,expected_partition_mode,expected_sort_mode",[- ("campaigns", ["id"], "datetime"),- ("accounts", ["email"], "datetime"),- ("campaign_analytics", ["campaign_id"], None),+ ("campaigns", ["id"], "datetime", "asc"),+ ("accounts", ["email"], "datetime", "asc"),+ ("campaign_analytics", ["campaign_id"], None, "asc"),+ # Audit log order is undocumented, so the watermark must only move when the run ends.+ ("audit_logs", ["id"], "datetime", "desc"),],)@mock.patch(f"{MODULE}.rest_api_resource")def test_source_response_per_endpoint(- self, mock_resource, endpoint, expected_primary_keys, expected_partition_mode+ self, mock_resource, endpoint, expected_primary_keys, expected_partition_mode, expected_sort_mode):manager = mock.MagicMock()manager.can_resume.return_value = False@@ -326,6 +417,7 @@ class TestInstantly:assert response.name == endpointassert response.primary_keys == expected_primary_keysassert response.partition_mode == expected_partition_mode+ assert response.sort_mode == expected_sort_moderest_config = mock_resource.call_args.args[0]assert rest_config["client"]["request_timeout"] == SYNC_REQUEST_TIMEOUT_SECONDSdiff --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.pyindex 3b5a174e1427..48e0a96a9b7a 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@@ -21,11 +21,12 @@ class TestInstantlySource:schemas = self.source.get_schemas(self.config, self.team_id)assert {schema.name for schema in schemas} == {*ENDPOINTS, WEBHOOK_EVENTS_ENDPOINT}- # Only /emails (min_timestamp_created) and /accounts/analytics/daily (start_date) expose a- # server-side filter; everything else must ship full refresh.+ # Only /emails (min_timestamp_created), /accounts/analytics/daily and /audit-logs (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",+ "audit_logs",}def test_get_schemas_webhook_events_is_webhook_only(self):