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(convertkit): add broadcast stats and subscriber junction tables (#103459)

Tom Owers1b304c3c2266
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 28056265ef6d..b6685821050e 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
@@ -2009,10 +2009,10 @@ Today (8): `broadcasts`, `custom_fields`, `email_templates`, `forms`, `purchases
Diffed against: <https://developers.kit.com/llms.txt>
-- [ ] `GET /v4/broadcasts/stats (get-stats-for-a-list-of-broadcasts) and /v4/broadcasts/{id}/stats` — opens, clicks, unsubscribes per broadcast - the headline email metric; broadcasts sync today with no performance data (high)
-- [ ] `GET /v4/tags/{id}/subscribers` — tag<->subscriber junction; without it the synced tags table cannot be joined to people (high)
-- [ ] `GET /v4/forms/{id}/subscribers` — form<->subscriber junction, the signup-source attribution table (high)
-- [ ] `GET /v4/sequences/{id}/subscribers` — sequence membership and per-subscriber sequence state (high)
+- [x] `GET /v4/broadcasts/stats (get-stats-for-a-list-of-broadcasts) and /v4/broadcasts/{id}/stats` — opens, clicks, unsubscribes per broadcast - the headline email metric; broadcasts sync today with no performance data (high)
+- [x] `GET /v4/tags/{id}/subscribers` — tag<->subscriber junction; without it the synced tags table cannot be joined to people (high)
+- [x] `GET /v4/forms/{id}/subscribers` — form<->subscriber junction, the signup-source attribution table (high)
+- [x] `GET /v4/sequences/{id}/subscribers` — sequence membership and per-subscriber sequence state (high)
- [ ] `GET /v4/segments` — segment lookup table, entirely unsynced (high)
- [ ] `GET /v4/sequences/{id}/emails (list-sequence-emails)` — the individual emails inside each sequence - line items for the sequences already synced (medium)
- [ ] `GET /v4/broadcasts/{id}/clicks (get-link-clicks-for-a-broadcast)` — per-link click breakdown within a broadcast (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/canonical_descriptions.py
index 0901cb3c11f8..a576486f54ec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/canonical_descriptions.py
@@ -109,4 +109,58 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"is_default": "Whether this is the account's default template.",
},
},
+ "broadcast_stats": {
+ "description": "Delivery and engagement stats for a broadcast: recipients, opens, clicks and unsubscribes.",
+ "docs_url": "https://developers.kit.com/api-reference/broadcasts/get-stats-for-a-list-of-broadcasts",
+ "columns": {
+ "id": "Unique identifier of the broadcast the stats belong to.",
+ "subject": "Subject line of the broadcast email.",
+ "send_at": "Scheduled send date and time of the broadcast.",
+ "stats": "Delivery and engagement counters: recipients, emails_opened, open_rate, click_rate, total_clicks, unsubscribes, unsubscribe_rate, status, progress, and the open/click tracking flags.",
+ },
+ },
+ "form_subscribers": {
+ "description": "A subscriber who joined through, or was added to, a form. This is the form-to-subscriber junction.",
+ "docs_url": "https://developers.kit.com/api-reference/forms/list-subscribers-for-a-form",
+ "columns": {
+ "form_id": "Identifier of the form the subscriber belongs to.",
+ "id": "Unique identifier for the subscriber.",
+ "first_name": "First name of the subscriber.",
+ "email_address": "Email address of the subscriber.",
+ "state": "State of the subscriber (active, inactive, bounced, complained, cancelled).",
+ "created_at": "Date and time the subscriber was created.",
+ "added_at": "Date and time the subscriber was added to the form.",
+ "referrer": "URL the subscriber came from when they signed up.",
+ "referrer_utm_parameters": "UTM source, medium, campaign, term and content parsed from the referrer.",
+ "fields": "Custom field values stored for the subscriber.",
+ },
+ },
+ "tag_subscribers": {
+ "description": "A subscriber carrying a tag. This is the tag-to-subscriber junction.",
+ "docs_url": "https://developers.kit.com/api-reference/tags/list-subscribers-for-a-tag",
+ "columns": {
+ "tag_id": "Identifier of the tag applied to the subscriber.",
+ "id": "Unique identifier for the subscriber.",
+ "first_name": "First name of the subscriber.",
+ "email_address": "Email address of the subscriber.",
+ "state": "State of the subscriber (active, inactive, bounced, complained, cancelled).",
+ "created_at": "Date and time the subscriber was created.",
+ "tagged_at": "Date and time the tag was applied to the subscriber.",
+ "fields": "Custom field values stored for the subscriber.",
+ },
+ },
+ "sequence_subscribers": {
+ "description": "A subscriber enrolled in a sequence. This is the sequence-to-subscriber junction.",
+ "docs_url": "https://developers.kit.com/api-reference/sequences/list-subscribers-for-a-sequence",
+ "columns": {
+ "sequence_id": "Identifier of the sequence the subscriber is enrolled in.",
+ "id": "Unique identifier for the subscriber.",
+ "first_name": "First name of the subscriber.",
+ "email_address": "Email address of the subscriber.",
+ "state": "State of the subscriber (active, inactive, bounced, complained, cancelled).",
+ "created_at": "Date and time the subscriber was created.",
+ "added_at": "Date and time the subscriber entered the sequence.",
+ "fields": "Custom field values stored for the subscriber.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/convertkit.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/convertkit.py
index 728deb154ab9..a957ca8f208b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/convertkit.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/convertkit.py
@@ -1,15 +1,23 @@
-import dataclasses
from datetime import UTC, date, datetime
-from typing import Any, Optional
+from typing import Any, Optional, cast
from requests import Request, Response
+from posthog.dataclasses import frozen
+
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,
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
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ IncrementalConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -20,13 +28,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.convertkit
# Kit (formerly ConvertKit) v4 API. v3 (api.convertkit.com) is deprecated.
CONVERTKIT_BASE_URL = "https://api.kit.com"
-PAGE_SIZE = 1000 # v4 max per_page
REQUEST_TIMEOUT = 60
+# Sent as the cursor floor on a fan-out child's first sync, because the framework binds the
+# filter param whether or not a watermark exists yet.
+EPOCH_CURSOR = "1970-01-01T00:00:00Z"
+@frozen
class ConvertKitResumeConfig:
+ # Top-level endpoints resume from the `after` cursor of the last fully-yielded page.
after: Optional[str] = None
+ # Fan-out endpoints resume by parent: the child paths already fully synced, the path in
+ # progress, and that path's paginator state. See
+ # `common.rest_source.__init__._make_paginate_dependent_resource`.
+ completed: Optional[list[str]] = None
+ current: Optional[str] = None
+ child_state: Optional[dict[str, Any]] = None
def _get_headers() -> dict[str, str]:
@@ -107,7 +124,7 @@ def _build_params(
db_incremental_field_last_value: Any,
incremental_field: str | None,
) -> dict[str, Any]:
- params: dict[str, Any] = {"per_page": PAGE_SIZE}
+ params: dict[str, Any] = {"per_page": config.page_size}
params.update(config.extra_params)
if (
@@ -129,33 +146,48 @@ def _build_params(
return params
-def convertkit_source(
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": CONVERTKIT_BASE_URL,
+ "headers": _get_headers(),
+ "auth": {"type": "api_key", "api_key": api_key, "name": "X-Kit-Api-Key", "location": "header"},
+ "paginator": ConvertKitPaginator(),
+ }
+
+
+def _incremental_config(config: ConvertKitEndpointConfig, cursor_path: str) -> Optional[IncrementalConfig]:
+ filter_param = config.incremental_param_map.get(cursor_path)
+ if not filter_param:
+ return None
+ return {
+ "start_param": filter_param,
+ "cursor_path": cursor_path,
+ "initial_value": EPOCH_CURSOR,
+ "convert": _format_incremental_value,
+ }
+
+
+def _top_level_resource(
+ config: ConvertKitEndpointConfig,
api_key: str,
endpoint: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[ConvertKitResumeConfig],
- should_use_incremental_field: bool = False,
- db_incremental_field_last_value: Optional[Any] = None,
- incremental_field: str | None = None,
-) -> SourceResponse:
- config = CONVERTKIT_ENDPOINTS[endpoint]
-
- params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field)
-
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+ incremental_field: str | None,
+) -> Any:
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": CONVERTKIT_BASE_URL,
- "headers": _get_headers(),
- "auth": {"type": "api_key", "api_key": api_key, "name": "X-Kit-Api-Key", "location": "header"},
- "paginator": ConvertKitPaginator(),
- },
+ "client": _client_config(api_key),
"resources": [
{
"name": endpoint,
"endpoint": {
"path": config.path,
- "params": params,
+ "params": _build_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ ),
"data_selector": config.data_key,
},
}
@@ -174,7 +206,7 @@ def convertkit_source(
if state and state.get("after"):
resumable_source_manager.save_state(ConvertKitResumeConfig(after=str(state["after"])))
- resource = rest_api_resource(
+ return rest_api_resource(
rest_config,
team_id,
job_id,
@@ -183,6 +215,103 @@ def convertkit_source(
initial_paginator_state=initial_paginator_state,
)
+
+def _fanout_resource(
+ config: ConvertKitEndpointConfig,
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ConvertKitResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+ incremental_field: str | None,
+) -> Any:
+ assert config.fanout is not None
+ parent_config = CONVERTKIT_ENDPOINTS[config.fanout.parent_name]
+
+ initial_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and (resume.completed or resume.current):
+ initial_state = {
+ "completed": resume.completed or [],
+ "current": resume.current,
+ "child_state": resume.child_state,
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(
+ ConvertKitResumeConfig(
+ completed=state.get("completed"),
+ current=state.get("current"),
+ child_state=state.get("child_state"),
+ )
+ )
+
+ return cast(
+ Any,
+ build_dependent_resource(
+ endpoint_configs=CONVERTKIT_ENDPOINTS,
+ child_endpoint=endpoint,
+ 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=db_incremental_field_last_value if should_use_incremental_field else None,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ incremental_config_factory=lambda cursor_path: _incremental_config(config, cursor_path),
+ parent_endpoint_extra={"data_selector": parent_config.data_key},
+ child_endpoint_extra={"data_selector": config.data_key},
+ child_params_extra=dict(config.extra_params),
+ page_size_param="per_page",
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_state,
+ ),
+ )
+
+
+def convertkit_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ConvertKitResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = CONVERTKIT_ENDPOINTS[endpoint]
+
+ resource: Any
+ if config.fanout is not None:
+ resource = _fanout_resource(
+ config,
+ api_key,
+ endpoint,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ incremental_field,
+ )
+ else:
+ resource = _top_level_resource(
+ config,
+ api_key,
+ endpoint,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ incremental_field,
+ )
+
return SourceResponse(
name=endpoint,
items=lambda: resource,
@@ -193,9 +322,12 @@ def convertkit_source(
partition_format="month" if config.partition_key else None,
partition_keys=[config.partition_key] if config.partition_key else None,
column_hints=resource.column_hints,
- # The API does not guarantee ascending order; the merge cursor still advances to the
- # max incremental value across all pages, which we read in full each sync.
- sort_mode="asc",
+ # "asc" endpoints are read in full each sync, so the merge cursor advances to the max
+ # incremental value across all pages even though the API guarantees no page order.
+ # "desc" holds the watermark until the sync completes; settings.py says why. The
+ # earliest-value backfill scrolling that "desc" also enables stays unused, because the
+ # resumable manager checkpoints fan-out progress per parent instead.
+ sort_mode=config.sort_mode,
)
@@ -208,6 +340,10 @@ def validate_credentials(api_key: str, endpoint: str | None = None) -> tuple[boo
if endpoint and endpoint not in CONVERTKIT_ENDPOINTS:
return False, f"Unknown Kit endpoint: {endpoint}"
config = CONVERTKIT_ENDPOINTS[endpoint] if endpoint else CONVERTKIT_ENDPOINTS["subscribers"]
+ if config.fanout is not None:
+ # A fan-out path is only reachable per parent record, so probe the parent listing the
+ # child is walked from, which is the call the sync makes first anyway.
+ config = CONVERTKIT_ENDPOINTS[config.fanout.parent_name]
url = f"{CONVERTKIT_BASE_URL}{config.path}?per_page=1"
ok, status = validate_via_probe(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/settings.py
index 2bda6f1becb0..f9cb5eccae16 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/settings.py
@@ -1,10 +1,18 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Optional
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+DEFAULT_PAGE_SIZE = 1000 # v4 max per_page
+
-@dataclass
+@frozen
class ConvertKitEndpointConfig:
name: str
path: str
@@ -20,6 +28,18 @@ class ConvertKitEndpointConfig:
incremental_param_map: dict[str, str] = field(default_factory=dict)
# Static query params always sent to the endpoint (e.g. status=all to include every record).
extra_params: dict[str, str] = field(default_factory=dict)
+ page_size: int = DEFAULT_PAGE_SIZE
+ # Set where the endpoint is only reachable per parent record, so rows are collected by
+ # walking the parent listing first.
+ fanout: Optional[DependentEndpointConfig] = None
+ # "desc" holds the incremental watermark until the sync completes. Fan-out rows arrive
+ # grouped by parent rather than in global time order, so a per-batch checkpoint would
+ # advance the watermark past parents a crashed run has not reached yet.
+ sort_mode: SortMode = "asc"
+
+ @property
+ def default_incremental_field(self) -> Optional[str]:
+ return self.incremental_fields[0]["field"] if self.incremental_fields else None
def _datetime_field(name: str) -> IncrementalField:
@@ -86,6 +106,72 @@ CONVERTKIT_ENDPOINTS: dict[str, ConvertKitEndpointConfig] = {
path="/v4/email_templates",
data_key="email_templates",
),
+ "broadcast_stats": ConvertKitEndpointConfig(
+ name="broadcast_stats",
+ path="/v4/broadcasts/stats",
+ data_key="broadcasts",
+ # Opens and clicks keep accumulating after a broadcast is sent, so the sent_after
+ # window would freeze the numbers of every broadcast already synced.
+ ),
+ "form_subscribers": ConvertKitEndpointConfig(
+ name="form_subscribers",
+ path="/v4/forms/{form_id}/subscribers",
+ data_key="subscribers",
+ # A subscriber id is unique per account but repeats across forms.
+ primary_keys=["form_id", "id"],
+ # added_at is the row's own timestamp, but a subscriber removed and re-added to a form
+ # gets a new one, so partition on the subscriber's immutable creation date instead.
+ partition_key="created_at",
+ supports_incremental=True,
+ incremental_fields=[_datetime_field("added_at")],
+ incremental_param_map={"added_at": "added_after"},
+ extra_params={"status": "all"},
+ sort_mode="desc",
+ fanout=DependentEndpointConfig(
+ parent_name="forms",
+ resolve_param="form_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "form_id"},
+ parent_params={"status": "all"},
+ ),
+ ),
+ "tag_subscribers": ConvertKitEndpointConfig(
+ name="tag_subscribers",
+ path="/v4/tags/{tag_id}/subscribers",
+ data_key="subscribers",
+ primary_keys=["tag_id", "id"],
+ partition_key="created_at",
+ # Tags can be removed from subscribers. A full snapshot lets the load replace stale
+ # junction rows that an addition-only tagged_after cursor can never emit.
+ extra_params={"status": "all"},
+ fanout=DependentEndpointConfig(
+ parent_name="tags",
+ resolve_param="tag_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "tag_id"},
+ ),
+ ),
+ "sequence_subscribers": ConvertKitEndpointConfig(
+ name="sequence_subscribers",
+ path="/v4/sequences/{sequence_id}/subscribers",
+ data_key="subscribers",
+ primary_keys=["sequence_id", "id"],
+ partition_key="created_at",
+ supports_incremental=True,
+ incremental_fields=[_datetime_field("added_at")],
+ incremental_param_map={"added_at": "added_after"},
+ extra_params={"status": "all"},
+ sort_mode="desc",
+ fanout=DependentEndpointConfig(
+ parent_name="sequences",
+ resolve_param="sequence_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "sequence_id"},
+ ),
+ ),
}
ENDPOINTS = tuple(CONVERTKIT_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/tests/test_convertkit.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/tests/test_convertkit.py
index 9a50b474f940..e060f026c960 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/tests/test_convertkit.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convertkit/tests/test_convertkit.py
@@ -307,3 +307,218 @@ class TestConvertKitSource:
assert [r["id"] for r in rows] == [7]
manager.can_resume.assert_called_once()
+
+
+def _wire_calls(session: mock.MagicMock, responses: list[Response]) -> list[tuple[str, dict[str, Any]]]:
+ """Like ``_wire``, but snapshots the URL alongside the params of each request."""
+ session.headers = {}
+ calls: list[tuple[str, dict[str, Any]]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ calls.append((request.url, dict(request.params or {})))
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return calls
+
+
+class TestBroadcastStats:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_reads_the_account_wide_stats_list(self, MockSession) -> None:
+ session = MockSession.return_value
+ calls = _wire_calls(session, [_page("broadcasts", [205, 204], has_next=False, end_cursor=None)])
+
+ rows = _rows(_source("broadcast_stats", _make_manager()))
+
+ assert [r["id"] for r in rows] == [205, 204]
+ assert calls[0][0].endswith("/v4/broadcasts/stats")
+ # Stats keep moving after a send, so no timestamp window is applied.
+ assert "sent_after" not in calls[0][1]
+
+
+JUNCTIONS = [
+ ("form_subscribers", "forms", "/v4/forms/{}/subscribers", "form_id", "added_after"),
+ ("tag_subscribers", "tags", "/v4/tags/{}/subscribers", "tag_id", "tagged_after"),
+ ("sequence_subscribers", "sequences", "/v4/sequences/{}/subscribers", "sequence_id", "added_after"),
+]
+INCREMENTAL_JUNCTIONS = [JUNCTIONS[0], JUNCTIONS[2]]
+
+
+class TestSubscriberJunctions:
+ @parameterized.expand(JUNCTIONS)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fans_out_over_parents_and_injects_the_parent_id(
+ self, endpoint: str, parent_key: str, child_path: str, parent_column: str, _filter: str, MockSession
+ ) -> None:
+ session = MockSession.return_value
+ calls = _wire_calls(
+ session,
+ [
+ _page(parent_key, [11, 12], has_next=False, end_cursor=None),
+ _page("subscribers", [1], has_next=False, end_cursor=None),
+ _page("subscribers", [2], has_next=False, end_cursor=None),
+ ],
+ )
+
+ rows = _rows(_source(endpoint, _make_manager()))
+
+ # Every row carries the parent it came from, which is what makes the key unique table-wide.
+ assert [(r[parent_column], r["id"]) for r in rows] == [(11, 1), (12, 2)]
+ assert calls[1][0].endswith(child_path.format(11))
+ assert calls[2][0].endswith(child_path.format(12))
+ # Every subscriber state, not just the active ones Kit returns by default.
+ assert calls[1][1]["status"] == "all"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_form_parent_listing_includes_archived_forms(self, MockSession) -> None:
+ session = MockSession.return_value
+ calls = _wire_calls(
+ session,
+ [
+ _page("forms", [11], has_next=False, end_cursor=None),
+ _page("subscribers", [1], has_next=False, end_cursor=None),
+ ],
+ )
+
+ _rows(_source("form_subscribers", _make_manager()))
+
+ assert calls[0][1]["status"] == "all"
+
+ @parameterized.expand(INCREMENTAL_JUNCTIONS)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_watermark_narrows_each_child_request(
+ self, endpoint: str, parent_key: str, _child_path: str, _parent_column: str, filter_param: str, MockSession
+ ) -> None:
+ session = MockSession.return_value
+ calls = _wire_calls(
+ session,
+ [
+ _page(parent_key, [11], has_next=False, end_cursor=None),
+ _page("subscribers", [1], has_next=False, end_cursor=None),
+ ],
+ )
+
+ _rows(
+ _source(
+ endpoint,
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
+ incremental_field=filter_param.replace("_after", "_at"),
+ )
+ )
+
+ assert calls[1][1][filter_param] == "2026-01-02T03:04:05Z"
+ # The parent listing is walked in full, so only the child is windowed.
+ assert filter_param not in calls[0][1]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_first_incremental_sync_sends_the_epoch_floor(self, MockSession) -> None:
+ session = MockSession.return_value
+ calls = _wire_calls(
+ session,
+ [
+ _page("forms", [11], has_next=False, end_cursor=None),
+ _page("subscribers", [1], has_next=False, end_cursor=None),
+ ],
+ )
+
+ _rows(
+ _source(
+ "form_subscribers",
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="added_at",
+ )
+ )
+
+ # The framework binds the filter param whether or not a watermark exists, so the floor
+ # has to be a real timestamp rather than the string "None".
+ assert calls[1][1]["added_after"] == "1970-01-01T00:00:00Z"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_sends_no_window(self, MockSession) -> None:
+ session = MockSession.return_value
+ calls = _wire_calls(
+ session,
+ [
+ _page("tags", [11], has_next=False, end_cursor=None),
+ _page("subscribers", [1], has_next=False, end_cursor=None),
+ ],
+ )
+
+ _rows(
+ _source(
+ "tag_subscribers",
+ _make_manager(),
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2026, 1, 2, tzinfo=UTC),
+ incremental_field="tagged_at",
+ )
+ )
+
+ assert "tagged_after" not in calls[1][1]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_checkpoints_each_parent_once_its_children_are_yielded(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire_calls(
+ session,
+ [
+ _page("forms", [11, 12], has_next=False, end_cursor=None),
+ _page("subscribers", [1], has_next=False, end_cursor=None),
+ _page("subscribers", [2], has_next=False, end_cursor=None),
+ ],
+ )
+
+ manager = _make_manager()
+ _rows(_source("form_subscribers", manager))
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved[-1] == ConvertKitResumeConfig(
+ completed=["/v4/forms/11/subscribers", "/v4/forms/12/subscribers"], current=None, child_state=None
+ )
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resume_skips_synced_parents_and_continues_the_one_in_flight(self, MockSession) -> None:
+ session = MockSession.return_value
+ calls = _wire_calls(
+ session,
+ [
+ _page("forms", [11, 12], has_next=False, end_cursor=None),
+ _page("subscribers", [2], has_next=False, end_cursor=None),
+ ],
+ )
+
+ manager = _make_manager(
+ ConvertKitResumeConfig(
+ completed=["/v4/forms/11/subscribers"],
+ current="/v4/forms/12/subscribers",
+ child_state={"after": "C9"},
+ )
+ )
+ rows = _rows(_source("form_subscribers", manager))
+
+ assert [r["form_id"] for r in rows] == [12]
+ assert [url for url, _ in calls] == [
+ "https://api.kit.com/v4/forms",
+ "https://api.kit.com/v4/forms/12/subscribers",
+ ]
+ assert calls[1][1]["after"] == "C9"
+
+
+class TestValidateFanoutCredentials:
+ @mock.patch(CONVERTKIT_SESSION_PATCH)
+ def test_probes_the_parent_listing(self, mock_session) -> None:
+ response = mock.MagicMock()
+ response.status_code = 200
+ mock_session.return_value.get.return_value = response
+
+ is_valid, _error = validate_credentials("key", "form_subscribers")
+
+ assert is_valid is True
+ # The child path carries an unresolved id placeholder, so probing it would 404 and
+ # report a working key as broken.
+ assert mock_session.return_value.get.call_args.args[0] == "https://api.kit.com/v4/forms?per_page=1"