: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 reply.io email activity and sequence tables (#127361)
Tom Owers3424629d621a
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 cae094c4dafa..f4504c0e67ea 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@@ -10230,12 +10230,12 @@ Today (11): `account_lists`, `accounts`, `contact_lists`, `contacts`, `custom_fiDiffed against: <https://docs.reply.io/llms.txt>-- [ ] `reports/list-email-activity` — per-message send/open/click/reply/bounce events - the core outreach fact table (high)-- [ ] `sequence-contacts/list-contacts-in-sequence (and list-contacts-in-sequence-with-extended-state)` — membership table joining contacts to sequences with per-sequence status; without it sequences and contacts cannot be related (high)-- [ ] `sequence-steps/list-all-sequence-steps (and list-step-variants)` — lookup resolving the step and variant IDs referenced by activity, plus A/B variant analysis (high)+- [x] `reports/list-email-activity` — per-message send/open/click/reply/bounce events - the core outreach fact table (high). Added as `email_activity`, a full refresh of the all-time report including one-off emails. Not incremental: the engagement flags change after delivery, and the `from` filter is read in the account's time zone+- [x] `sequence-contacts/list-contacts-in-sequence (and list-contacts-in-sequence-with-extended-state)` — membership table joining contacts to sequences with per-sequence status; without it sequences and contacts cannot be related (high). Added as `sequence_contacts`, one walk per sequence. The extended-state variant is not synced: it pages at 100 rows instead of 1000 for the same membership rows+- [x] `sequence-steps/list-all-sequence-steps (and list-step-variants)` — lookup resolving the step and variant IDs referenced by activity, plus A/B variant analysis (high). Added as `sequence_steps`, one request per sequence. Variants need no table of their own: every email and LinkedIn step row already carries its `variants` array, and a separate table would cost one more request per step- [ ] `reports/list-meetings` — booked meetings, the outcome metric outreach performance is judged on (high)- [ ] `sequences/get-stats-for-all-sequences` — vendor-computed per-sequence delivery and reply rates (high)-- [ ] `user-account/list-team-users` — lookup resolving the owner/user IDs carried on contacts, accounts, sequences and tasks (high)+- [x] `user-account/list-team-users` — lookup resolving the owner/user IDs carried on contacts, accounts, sequences and tasks (high). Added as `team_users`, one row per user per team- [ ] `inbox/list-messages-in-an-inbox-thread` — message-level rows under the inbox_threads already synced (medium)- [ ] `inbox/list-inbox-categories` — lookup for the category IDs assigned to inbox threads (medium)- [ ] `reports/list-call-activity` — call outcomes and durations, the phone channel equivalent of email activity (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/canonical_descriptions.pyindex 67fc51b48496..ec05aa92eff2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/canonical_descriptions.py@@ -183,4 +183,81 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"status": "Aggregated thread state, derived from the latest message.",},},+ "team_users": {+ "description": "A member of a team (workspace) in your Reply organization, one row per user per team. Resolves the user IDs carried on contacts, accounts, sequences and tasks.",+ "docs_url": "https://docs.reply.io/api-reference/user-account/list-team-users",+ "columns": {+ "teamId": "The team (workspace) ID.",+ "teamName": "The team (workspace) name.",+ "userId": "The user's ID.",+ "userName": "The user's display name.",+ "userEmail": "The user's email address.",+ "isOwner": "Whether the user owns the team.",+ "teamRole": "Name of the permission role the user holds in this team; null for the team owner.",+ "organizationRole": "Name of the permission role the user holds in the organization; null when the user holds none.",+ },+ },+ "email_activity": {+ "description": "One email sent by Reply, with its contact, sending account, sequence step, A/B variant, and delivery and engagement outcome.",+ "docs_url": "https://docs.reply.io/api-reference/reports/list-email-activity",+ "columns": {+ "contactId": "ID of the contact the email was sent to.",+ "firstName": "Contact's first name.",+ "lastName": "Contact's last name.",+ "email": "Contact's email address.",+ "company": "Contact's company name.",+ "emailAccountId": "ID of the email account the email was sent from.",+ "emailAccountEmail": "Email address of the sending account.",+ "sequenceId": "ID of the sequence; null for a one-off email sent outside any sequence.",+ "sequenceName": "Name of the sequence.",+ "sequenceStepNumber": "Step number within the sequence.",+ "sequenceStepDisplayName": "Display name of the sequence step.",+ "deliveryDate": "When the email was delivered.",+ "isDelivered": "Whether the email was delivered.",+ "isOpened": "Whether the email was opened.",+ "isClicked": "Whether a link in the email was clicked.",+ "isReplied": "Whether the contact replied to the email.",+ "isInterested": "Whether the reply was marked as interested.",+ "isBounced": "Whether the email bounced.",+ "isOptedOut": "Whether the contact opted out.",+ "variantId": "ID of the step's A/B variant the email was sent from; null when the email has no variant.",+ },+ },+ "sequence_contacts": {+ "description": "A contact's enrollment in a sequence, with their status and current step in that sequence. Joins contacts to sequences.",+ "docs_url": "https://docs.reply.io/api-reference/sequence-contacts/list-contacts-in-sequence",+ "columns": {+ "sequenceId": "ID of the sequence.",+ "contactId": "ID of the contact.",+ "email": "Contact email address.",+ "firstName": "Contact first name.",+ "lastName": "Contact last name.",+ "company": "Contact company name.",+ "title": "Contact job title.",+ "statusInSequence": "Contact's status in this sequence (active, paused, finished, inactive, outOfOffice).",+ "isOptedOut": "Whether the contact has opted out (contact-level, not sequence-scoped).",+ "callStatus": "Contact-level call status (none, toCall, called).",+ "meetingStatus": "Contact-level meeting status (none, meetingBooked).",+ "emailDisposition": "Reply and bounce flags for the latest email sent to the contact in this sequence; null when no email was sent yet.",+ "currentStep": "Step the contact is on; stepId is null and displayName is Finished when no step is in progress.",+ "addingDate": "When the contact was added to the sequence.",+ "emailAccountId": "ID of the email account sending to the contact in this sequence.",+ "linkedInAccountId": "ID of the LinkedIn account used for the contact in this sequence.",+ },+ },+ "sequence_steps": {+ "description": "A step in a sequence (email, LinkedIn, call, SMS, WhatsApp, Zapier, task, or condition), with its A/B variants.",+ "docs_url": "https://docs.reply.io/api-reference/sequence-steps/list-all-sequence-steps",+ "columns": {+ "id": "Unique identifier for the step.",+ "sequenceId": "ID of the sequence the step belongs to.",+ "parentId": "ID of the parent step, for branching.",+ "ifConditionPositive": "Whether the step is on the positive branch of a condition.",+ "type": "Step type (email, linkedIn, call, sms, whatsApp, zapier, task, condition); decides which other fields are set.",+ "actionType": "LinkedIn action subtype for LinkedIn steps.",+ "delayInMinutes": "Delay in minutes before the step runs.",+ "executionMode": "Whether an email step runs automatically or manually.",+ "variants": "A/B variants of the step, each with its ID, subject, message and attachment flag.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/reply_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/reply_io.pyindex 1bc5625adbe5..85bd8d0b19b7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/reply_io.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/reply_io.py@@ -8,25 +8,35 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resRESTAPIConfig,rest_api_resource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (BasePaginator,SinglePagePaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.settings import REPLY_IO_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.settings import (+ REPLY_IO_ENDPOINTS,+ ReplyIoEndpointConfig,+)REPLY_IO_BASE_URL = "https://api.reply.io/v3"-# List endpoints accept `top` up to 1000 (default 25); the largest page minimises round trips-# against Reply's 100 requests/minute rate limit.-PAGE_SIZE = 1000[email protected](frozen=True)class ReplyIoResumeConfig:# Reply paginates with `top`/`skip` offsets. A crashed full-refresh sync resumes from the# offset after the last yielded page; merge dedupes any re-pulled rows on `id`.skip: int = 0+ # The per-sequence endpoints save the `build_dependent_resource` checkpoint (which sequences+ # finished, where the current one stopped) here instead of `skip`.+ fanout_state: dict[str, Any] | None = Nonedef _headers() -> dict[str, str]:@@ -88,6 +98,87 @@ class ReplyIoOffsetPaginator(BasePaginator):self._has_next_page = True+def _client_config(api_key: str) -> ClientConfig:+ return {+ "base_url": REPLY_IO_BASE_URL,+ "headers": _headers(),+ "auth": {"type": "bearer", "token": api_key},+ }+++def _page_endpoint(config: ReplyIoEndpointConfig) -> Endpoint:+ if config.paginated:+ paginator: BasePaginator = ReplyIoOffsetPaginator(limit=config.page_size)+ # Paginated list endpoints wrap rows in {"items": [...], "hasMore": bool}.+ data_selector: Optional[str] = "items"+ else:+ # Small catalog endpoints (custom fields, template folders, sequence steps) return a bare,+ # unpaginated array.+ paginator = SinglePagePaginator()+ data_selector = None++ endpoint: Endpoint = {+ "paginator": paginator,+ "data_selector": data_selector,+ # A 200 whose body isn't the expected list shape (paginated: not a dict with an+ # `items` list; unpaginated: not a bare array) is treated as transient and+ # retried, matching the hand-rolled source's defensive payload check.+ "data_selector_malformed_retryable": True,+ }+ if config.method != "GET":+ endpoint["method"] = config.method+ if config.json is not None:+ endpoint["json"] = config.json+ return endpoint+++def _fanout_source(+ api_key: str,+ config: ReplyIoEndpointConfig,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[ReplyIoResumeConfig],+) -> SourceResponse:+ assert config.fanout is not None+ parent = REPLY_IO_ENDPOINTS[config.fanout.parent_name]++ initial_fanout_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_fanout_state = resume.fanout_state++ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state:+ resumable_source_manager.save_state(ReplyIoResumeConfig(fanout_state=state))++ resource = build_dependent_resource(+ endpoint_configs={config.name: config, parent.name: parent},+ child_endpoint=config.name,+ fanout=config.fanout,+ client_config=_client_config(api_key),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ # The offset paginator sends `top` itself.+ page_size_param=None,+ parent_endpoint_extra=_page_endpoint(parent),+ child_endpoint_extra=_page_endpoint(config),+ child_params_extra=config.params,+ resume_hook=save_fanout_checkpoint,+ initial_paginator_state=initial_fanout_state,+ )++ return SourceResponse(+ name=config.name,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )++def reply_io_source(api_key: str,endpoint: str,@@ -97,36 +188,16 @@ def reply_io_source() -> SourceResponse:config = REPLY_IO_ENDPOINTS[endpoint]- if config.paginated:- paginator: BasePaginator = ReplyIoOffsetPaginator(limit=PAGE_SIZE)- # Paginated list endpoints wrap rows in {"items": [...], "hasMore": bool}.- data_selector: Optional[str] = "items"- else:- # Small catalog endpoints (custom fields, template folders) return a bare, unpaginated array.- paginator = SinglePagePaginator()- data_selector = None+ if config.fanout is not None:+ return _fanout_source(api_key, config, team_id, job_id, resumable_source_manager)++ endpoint_config = _page_endpoint(config)+ endpoint_config["path"] = config.pathrest_config: RESTAPIConfig = {- "client": {- "base_url": REPLY_IO_BASE_URL,- "headers": _headers(),- "auth": {"type": "bearer", "token": api_key},- },+ "client": _client_config(api_key),"resource_defaults": {},- "resources": [- {- "name": endpoint,- "endpoint": {- "path": config.path,- "paginator": paginator,- "data_selector": data_selector,- # A 200 whose body isn't the expected list shape (paginated: not a dict with an- # `items` list; unpaginated: not a bare array) is treated as transient and- # retried, matching the hand-rolled source's defensive payload check.- "data_selector_malformed_retryable": True,- },- }- ],+ "resources": [{"name": endpoint, "endpoint": endpoint_config}],}initial_paginator_state: Optional[dict[str, Any]] = None@@ -160,7 +231,25 @@ def reply_io_source()-def check_access(api_key: str, path: str, paginated: bool = False) -> tuple[int, Optional[str]]:+def _probe_target(config: ReplyIoEndpointConfig) -> ReplyIoEndpointConfig:+ # A per-sequence endpoint has no path to probe without a sequence ID; its parent listing needs+ # the same scope.+ return REPLY_IO_ENDPOINTS[config.fanout.parent_name] if config.fanout is not None else config+++def _missing_access_message(config: ReplyIoEndpointConfig) -> str:+ if config.scope is None:+ return "Reply only lists team users for accounts that belong to an organization"+ return f"Your Reply API key is missing the `{config.scope}` scope"+++def check_access(+ api_key: str,+ path: str,+ paginated: bool = False,+ method: str = "GET",+ json: Optional[dict[str, Any]] = None,+) -> tuple[int, Optional[str]]:"""Probe an endpoint with the smallest possible request.Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a@@ -170,9 +259,11 @@ def check_access(api_key: str, path: str, paginated: bool = False) -> tuple[int,headers={"Authorization": f"Bearer {api_key}", **_headers()}, redact_values=(api_key,))try:- response = session.get(+ response = session.request(+ method,f"{REPLY_IO_BASE_URL}{path}",params={"top": 1} if paginated else None,+ json=json,timeout=15,)except Exception as e:@@ -187,13 +278,21 @@ def check_access(api_key: str, path: str, paginated: bool = False) -> tuple[int,return 200, None+def _probe(api_key: str, config: ReplyIoEndpointConfig) -> tuple[int, Optional[str]]:+ target = _probe_target(config)+ # Reporting endpoints require a `filters` body; an empty one reads only the last seven days,+ # which keeps the probe cheap.+ body: Optional[dict[str, Any]] = {"filters": {}} if target.json is not None else None+ return check_access(api_key, target.path, paginated=target.paginated, method=target.method, json=body)++def validate_credentials(api_key: str, endpoint: Optional[str] = None) -> tuple[bool, str | None]:"""Validate the API key against `/whoami` (needs no scope), or a specific endpoint's scope."""if endpoint is not None:config = REPLY_IO_ENDPOINTS[endpoint]- status, message = check_access(api_key, config.path, paginated=config.paginated)+ status, message = _probe(api_key, config)if status == 403:- return False, f"Your Reply API key is missing the `{config.scope}` scope"+ return False, _missing_access_message(config)else:status, message = check_access(api_key, "/whoami")@@ -208,7 +307,7 @@ def check_endpoint_permissions(api_key: str, endpoints: list[str]) -> dict[str,"""Per-table scope status for the schema picker. ``None`` = reachable, str = why not.Endpoints sharing a scope share one probe, so the whole check costs at most one request per- distinct scope. Only a real 403 counts as a missing scope — throttles, 5xx, and network blips+ distinct scope (endpoints with no scope are probed on their own path). Only a real 403 counts as a missing scope — throttles, 5xx, and network blipsare reported as reachable so a transient error never blocks the picker."""verdict_by_scope: dict[str, str | None] = {}@@ -218,10 +317,9 @@ def check_endpoint_permissions(api_key: str, endpoints: list[str]) -> dict[str,if config is None:results[name] = Nonecontinue- if config.scope not in verdict_by_scope:- status, _ = check_access(api_key, config.path, paginated=config.paginated)- verdict_by_scope[config.scope] = (- f"Your Reply API key is missing the `{config.scope}` scope" if status == 403 else None- )- results[name] = verdict_by_scope[config.scope]+ verdict_key = config.scope or config.path+ if verdict_key not in verdict_by_scope:+ status, _ = _probe(api_key, config)+ verdict_by_scope[verdict_key] = _missing_access_message(config) if status == 403 else None+ results[name] = verdict_by_scope[verdict_key]return resultsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/settings.pyindex 3f231b187af7..29fffed535a2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/settings.py@@ -1,19 +1,36 @@from dataclasses import dataclass, field+from typing import Any, Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.types import IncrementalField+# List endpoints accept `top` up to 1000 (default 25); the largest page minimises round trips+# against Reply's 100 requests/minute rate limit.+PAGE_SIZE = 1000-@dataclass++@dataclass(frozen=True)class ReplyIoEndpointConfig:name: strpath: str# Scope the endpoint requires, per the Reply API docs (a broader scope that includes it also works).- scope: str+ # None for endpoints any valid key can call.+ scope: str | None# Most list endpoints paginate with `top`/`skip` and wrap rows in {"items": [...], "hasMore": bool};# a few small catalogs return a bare, unpaginated JSON array.paginated: bool = True# Reply object IDs are unique per resource within an account, so `id` is a safe primary key.primary_keys: list[str] = field(default_factory=lambda: ["id"])+ method: Literal["GET", "POST"] = "GET"+ params: dict[str, Any] = field(default_factory=dict)+ json: dict[str, Any] | None = None+ # Per-sequence child endpoints: `path` carries an `{id}` placeholder resolved from each parent row.+ fanout: DependentEndpointConfig | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ page_size: int = PAGE_SIZE# Reply API v3 list endpoints (https://docs.reply.io/api-reference). All are full refresh only:@@ -35,6 +52,57 @@ REPLY_IO_ENDPOINTS: dict[str, ReplyIoEndpointConfig] = {),"email_accounts": ReplyIoEndpointConfig(name="email_accounts", path="/email-accounts", scope="channels:read"),"inbox_threads": ReplyIoEndpointConfig(name="inbox_threads", path="/inbox/threads", scope="inbox:read"),+ # One row per user per team, so a user in several teams appears once for each.+ "team_users": ReplyIoEndpointConfig(+ name="team_users",+ path="/whoami/team-users",+ scope=None,+ paginated=False,+ primary_keys=["teamId", "userId"],+ ),+ # One row per email sent. The report has no row ID; one mailbox never delivers two emails to the+ # same contact at the same instant, so the three fields together identify an email.+ "email_activity": ReplyIoEndpointConfig(+ name="email_activity",+ path="/reporting/emails",+ scope="reporting:read",+ method="POST",+ # Without a window the report returns only the last seven days. The `from` filter is read in+ # the account's time zone, and the open/click/reply flags change after delivery, so the+ # table is a full refresh of all time rather than an incremental read on `deliveryDate`.+ json={"filters": {"dateRangePreset": "allTime", "includeOutOfSequence": True}},+ primary_keys=["contactId", "emailAccountId", "deliveryDate"],+ ),+ "sequence_contacts": ReplyIoEndpointConfig(+ name="sequence_contacts",+ path="/sequences/{id}/contacts",+ scope="sequences:read",+ # An explicit ascending sort keeps offset pages stable while contacts are added mid-sync.+ params={"sort_by": "addingDate", "sort_direction": "asc"},+ fanout=DependentEndpointConfig(+ parent_name="sequences",+ resolve_param="id",+ resolve_field="id",+ include_from_parent=[],+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+ ),+ primary_keys=["sequenceId", "contactId"],+ ),+ "sequence_steps": ReplyIoEndpointConfig(+ name="sequence_steps",+ path="/sequences/{id}/steps",+ scope="sequences:read",+ paginated=False,+ fanout=DependentEndpointConfig(+ parent_name="sequences",+ resolve_param="id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "sequenceId"},+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+ ),+ primary_keys=["sequenceId", "id"],+ ),}ENDPOINTS = tuple(REPLY_IO_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/source.pyindex 0e328168342e..4661994c3ea1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/source.py@@ -58,7 +58,7 @@ class ReplyIoSource(ResumableSource[ReplyIoSourceConfig, ReplyIoResumeConfig]):releaseStatus=ReleaseStatus.BETA,caption="""Enter your Reply API key to pull your sales engagement data into the PostHog Data warehouse.-You can create an API key under **Settings → API Keys** in [Reply](https://run.reply.io). To sync every table the key needs the `contacts:read`, `sequences:read`, `tasks:read`, `channels:read`, and `inbox:read` scopes (or broader scopes that include them) — tables whose scope is missing can be deselected in the table picker.+You can create an API key under **Settings → API Keys** in [Reply](https://run.reply.io). To sync every table the key needs the `contacts:read`, `sequences:read`, `tasks:read`, `channels:read`, `inbox:read`, and `reporting:read` scopes (or broader scopes that include them) — tables whose scope is missing can be deselected in the table picker.""",iconPath="/static/services/reply_io.png",docsUrl="https://posthog.com/docs/cdp/sources/reply-io",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/tests/test_reply_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/tests/test_reply_io.pyindex e35018c80a2d..77230c285b83 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/tests/test_reply_io.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/tests/test_reply_io.py@@ -11,19 +11,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tesScriptedResponse,SourceDriver,always,+ route,scripted_network,)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.replyio import (ReplyIoSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.reply_io import (- PAGE_SIZE,ReplyIoResumeConfig,check_endpoint_permissions,validate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.settings import (ENDPOINTS,+ PAGE_SIZE,REPLY_IO_ENDPOINTS,)from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.source import ReplyIoSource@@ -83,6 +84,78 @@ class TestPagination:assert isinstance(result.raised, RESTClientRetryableError)+ def test_email_activity_posts_all_time_filters_on_every_page(self) -> None:+ result = _driver().run(+ "email_activity",+ [+ _paged([{"contactId": 1, "emailAccountId": 9, "deliveryDate": "2026-01-01T10:00:00Z"}], has_more=True),+ _paged([{"contactId": 2, "emailAccountId": 9, "deliveryDate": "2026-01-02T10:00:00Z"}], has_more=False),+ ],+ )++ assert [r["contactId"] for r in result.rows] == [1, 2]+ assert [r.method for r in result.requests] == ["POST", "POST"]+ assert result.params("skip") == ["0", "1"]+ # Without a window the report returns only the last seven days.+ expected_body = {"filters": {"dateRangePreset": "allTime", "includeOutOfSequence": True}}+ assert [r.json() for r in result.requests] == [expected_body, expected_body]++ def test_sequence_contacts_pages_each_sequence_in_adding_order(self) -> None:+ result = _driver().run(+ "sequence_contacts",+ route(+ {+ "/sequences": [_paged([{"id": 7}, {"id": 8}], has_more=False)],+ "/sequences/7/contacts": [+ _paged([{"sequenceId": 7, "contactId": 1}], has_more=True),+ _paged([{"sequenceId": 7, "contactId": 2}], has_more=False),+ ],+ "/sequences/8/contacts": [_paged([{"sequenceId": 8, "contactId": 1}], has_more=False)],+ }+ ),+ )++ assert [(r["sequenceId"], r["contactId"]) for r in result.rows] == [(7, 1), (7, 2), (8, 1)]+ child_requests = [r for r in result.requests if r.path.endswith("/contacts")]+ assert [(r.path, r.param("skip")) for r in child_requests] == [+ ("/v3/sequences/7/contacts", "0"),+ ("/v3/sequences/7/contacts", "1"),+ ("/v3/sequences/8/contacts", "0"),+ ]+ assert all(r.param("sort_by") == "addingDate" and r.param("sort_direction") == "asc" for r in child_requests)++ def test_sequence_steps_carry_sequence_id_and_skip_deleted_sequences(self) -> None:+ result = _driver().run(+ "sequence_steps",+ route(+ {+ "/sequences": [_paged([{"id": 7}, {"id": 8}], has_more=False)],+ "/sequences/7/steps": [_bare([{"id": 50, "type": "email"}, {"id": 51, "type": "call"}])],+ # A sequence deleted between the listing and its step fetch.+ "/sequences/8/steps": [ScriptedResponse(status=404, json={})],+ }+ ),+ )++ assert result.raised is None+ assert [(r["sequenceId"], r["id"]) for r in result.rows] == [(7, 50), (7, 51)]+ assert all("_sequences_id" not in r for r in result.rows)++ def test_fanout_resumes_after_finished_sequences(self) -> None:+ script = {+ "/sequences": [_paged([{"id": 7}, {"id": 8}], has_more=False)],+ "/sequences/7/steps": [_bare([{"id": 50}])],+ "/sequences/8/steps": [_bare([{"id": 60}])],+ }+ first = _driver().run("sequence_steps", route(script))+ checkpoint = first.saved_states[0]+ assert checkpoint.fanout_state is not None++ resumed = _driver().run("sequence_steps", route(script), resume_state=checkpoint)++ assert [r["id"] for r in resumed.rows] == [60]+ assert "/v3/sequences/7/steps" not in resumed.paths+def test_unpaginated_non_array_body_is_retryable(self) -> None:result = _driver().run("custom_fields", always(_bare({"items": []})))@@ -108,11 +181,32 @@ class TestCredentials:with scripted_network(always(ScriptedResponse(status=status, json={}))):assert validate_credentials("reply-key") == (expected_valid, expected_message)- def test_validate_credentials_for_endpoint_names_missing_scope(self) -> None:- with scripted_network(always(ScriptedResponse(status=403, json={}))):- valid, message = validate_credentials("reply-key", endpoint="sequences")- assert valid is False- assert message == "Your Reply API key is missing the `sequences:read` scope"+ @parameterized.expand(+ [+ ("sequences", "GET", "/v3/sequences", "Your Reply API key is missing the `sequences:read` scope"),+ # Per-sequence endpoints probe the sequence listing, which needs the same scope.+ ("sequence_steps", "GET", "/v3/sequences", "Your Reply API key is missing the `sequences:read` scope"),+ (+ "email_activity",+ "POST",+ "/v3/reporting/emails",+ "Your Reply API key is missing the `reporting:read` scope",+ ),+ (+ "team_users",+ "GET",+ "/v3/whoami/team-users",+ "Reply only lists team users for accounts that belong to an organization",+ ),+ ]+ )+ def test_validate_credentials_for_endpoint_reports_denied_access(+ self, endpoint: str, method: str, path: str, expected_message: str+ ) -> None:+ with scripted_network(always(ScriptedResponse(status=403, json={}))) as network:+ valid, message = validate_credentials("reply-key", endpoint=endpoint)+ assert (valid, message) == (False, expected_message)+ assert [(r.method, r.path) for r in network.requests_log] == [(method, path)]class TestEndpointPermissions:@@ -138,11 +232,14 @@ class TestEndpointPermissions:class TestReplyIoSourceResponse:@parameterized.expand([(e,) for e in ENDPOINTS])def test_source_response_shape(self, endpoint: str) -> None:- empty = _paged([], has_more=False) if REPLY_IO_ENDPOINTS[endpoint].paginated else _bare([])+ config = REPLY_IO_ENDPOINTS[endpoint]+ first_request = REPLY_IO_ENDPOINTS[config.fanout.parent_name] if config.fanout else config+ empty = _paged([], has_more=False) if first_request.paginated else _bare([])result = _driver().run(endpoint, [empty])+ assert result.raised is Noneassert result.response is not Noneassert result.response.name == endpoint- assert result.response.primary_keys == ["id"]+ assert result.response.primary_keys == config.primary_keys# Most Reply resources expose no stable creation timestamp, so we don't partition.assert result.response.partition_mode is None