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 marketo folder, channel and membership tables (#122653)

Tom Owerse0a10b9fc91e
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 9c8ab4b6ecff..c483a4703c55 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
@@ -7655,14 +7655,14 @@ Note: Mailtrap publishes 10 OpenAPI specs covering five distinct products (email
## Marketo — gaps
-Today (10): `activities`, `activity_types`, `campaigns`, `emails`, `forms`, `landing_pages`, `leads`, `lists`, `programs`, `smart_campaigns`
+Today (14): `activities`, `activity_types`, `campaigns`, `channels`, `emails`, `folders`, `forms`, `landing_pages`, `leads`, `list_members`, `lists`, `program_members`, `programs`, `smart_campaigns`
Diffed against: <https://raw.githubusercontent.com/AdobeDocs/marketo-apis/main/static/swagger-mapi.json>
-- [ ] `Folders (GET /rest/asset/v1/folders.json)` — resolve folder IDs on programs, emails, forms, and landing pages (high)
-- [ ] `Channels (GET /rest/asset/v1/channels.json)` — supply program statuses and success flags for conversion analysis (high)
-- [ ] `Program members (GET /rest/v1/programs/{programId}/members.json)` — measure program participation, member status, and marketing success by lead (high)
-- [ ] `List members (GET /rest/v1/lists/{listId}/leads.json)` — materialize static-list membership for audience and campaign analysis (high)
+- [x] `Folders (GET /rest/asset/v1/folders.json)` — resolve folder IDs on programs, emails, forms, and landing pages (high). Added as `folders` (full refresh, browsed 20 levels deep, keyed on `id` + `folderType` because folder and program ids are numbered separately).
+- [x] `Channels (GET /rest/asset/v1/channels.json)` — supply program statuses and success flags for conversion analysis (high). Added as `channels` (full refresh).
+- [x] `Program members (GET /rest/v1/programs/{programId}/members.json)` — measure program participation, member status, and marketing success by lead (high). Added as `program_members` (fan-out over programs in 7-day `updatedAt` windows from the start date, incremental on `updatedAt`).
+- [x] `List members (GET /rest/v1/lists/{listId}/leads.json)` — materialize static-list membership for audience and campaign analysis (high). Added as `list_members` (fan-out over static lists, full refresh).
- [ ] `Opportunities (GET /rest/v1/opportunities.json)` — connect marketing activity with pipeline and revenue outcomes (high)
- [ ] `Companies (GET /rest/v1/companies.json)` — resolve company references on leads for account-level marketing analysis (high)
- [ ] `SalesPersons (GET /rest/v1/salespersons.json)` — resolve sales-owner references for lead routing and performance analysis (high)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/canonical_descriptions.py
index a142b2d661e7..13b0a81005bf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/canonical_descriptions.py
@@ -174,4 +174,66 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updatedAt": "Datetime the smart campaign was last modified.",
},
},
+ "folders": {
+ "description": "Folders and programs in the Marketing Activities, Design Studio and Lead Database trees. Join on folder references from programs, emails, forms and landing pages to resolve where an asset lives.",
+ "docs_url": "https://developer.adobe.com/marketo-apis/api/asset/#tag/Folders",
+ "columns": {
+ "id": "Identifier of the folder or program. Folder and program ids are numbered separately.",
+ "name": "Name of the folder.",
+ "description": "Description of the folder.",
+ "folderType": "Type of folder, such as Marketing Folder, Zone or Marketing Program.",
+ "folderId": "Folder reference with the id and whether it is a Folder or a Program.",
+ "parent": "Reference to the parent folder or program.",
+ "path": "Full path of the folder in the folder tree.",
+ "isArchive": "Whether the folder is archived.",
+ "isSystem": "Whether the folder is managed by Marketo rather than a user.",
+ "workspace": "Workspace the folder belongs to.",
+ "url": "URL of the folder in the Marketo UI.",
+ "createdAt": "Datetime the folder was created.",
+ "updatedAt": "Datetime the folder was last modified.",
+ },
+ },
+ "channels": {
+ "description": "Program channels, with the member statuses each channel allows and which of them count as success.",
+ "docs_url": "https://developer.adobe.com/marketo-apis/api/asset/#tag/Channels",
+ "columns": {
+ "id": "Unique identifier of the channel.",
+ "name": "Name of the channel, which programs reference as their channel.",
+ "applicableProgramType": "Type of program the channel applies to.",
+ "progressionStatuses": "Member statuses available to programs with this channel, with their step order and success flag.",
+ "createdAt": "Datetime the channel was created.",
+ "updatedAt": "Datetime the channel was last modified.",
+ },
+ },
+ "program_members": {
+ "description": "Membership of leads in programs, with each member's status and success. Covers members updated since the source's start date.",
+ "docs_url": "https://developer.adobe.com/marketo-apis/api/mapi/#tag/Program-Members",
+ "columns": {
+ "programId": "Identifier of the program, joinable to the programs table.",
+ "leadId": "Identifier of the lead, joinable to the leads table.",
+ "statusName": "Current program status of the member, as defined by the program's channel.",
+ "reachedSuccess": "Whether the member has reached the program's success status.",
+ "reachedSuccessDate": "Datetime the member reached success.",
+ "acquiredBy": "Whether the program acquired the lead.",
+ "membershipDate": "Datetime the lead first became a member of the program.",
+ "isExhausted": "Whether the member has run out of content in an engagement program.",
+ "nurtureCadence": "Cadence of the member in an engagement program.",
+ "trackName": "Engagement program stream the member is in.",
+ "createdAt": "Datetime the membership record was created.",
+ "updatedAt": "Datetime the membership record was last modified.",
+ },
+ },
+ "list_members": {
+ "description": "Membership of leads in static lists. Each row is a lead record with the id of the list it belongs to.",
+ "docs_url": "https://developer.adobe.com/marketo-apis/api/mapi/#tag/Static-Lists",
+ "columns": {
+ "listId": "Identifier of the static list, joinable to the lists table.",
+ "id": "Identifier of the lead, joinable to the leads table.",
+ "email": "Email address of the lead.",
+ "firstName": "First name of the lead.",
+ "lastName": "Last name of the lead.",
+ "createdAt": "Datetime the lead was created in Marketo.",
+ "updatedAt": "Datetime the lead record was last modified.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py
index 901cc86efebd..733536598308 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py
@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.marketo.se
ASSET_MAX_RETURN,
BULK_WINDOW_DAYS,
MARKETO_ENDPOINTS,
+ PROGRAM_MEMBER_WINDOW_DAYS,
REST_BATCH_SIZE,
MarketoEndpointConfig,
)
@@ -40,6 +41,10 @@ BULK_CHUNK_ROWS = 2000
# Bulk lead exports name every column explicitly; keep the request body bounded on instances
# with thousands of custom fields.
MAX_LEAD_EXPORT_FIELDS = 300
+# Program member queries send the field list in a GET query string, which Marketo caps at 8KB.
+MAX_PROGRAM_MEMBER_FIELDS = 100
+# Requested even when describe omits them: they carry the key, the partition and the cursor.
+PROGRAM_MEMBER_REQUIRED_FIELDS = ("leadId", "programId", "membershipDate", "updatedAt")
DEFAULT_BULK_LOOKBACK_DAYS = 365
@@ -66,17 +71,30 @@ class MarketoAuthError(MarketoAPIError):
pass
[email protected](frozen=True)
class MarketoResumeConfig:
"""Cursor for whichever transport the endpoint uses.
- Only one of the three is populated per endpoint; they are kept on one dataclass because the
- resume manager stores a single dataclass type per source.
+ Top-level endpoints populate one of the first three. Fan-out endpoints set `parent_id` to the
+ parent the cursor is in, plus `next_page_token` and `window_start` for the position in it. With
+ neither, that parent is finished.
+ They are kept on one dataclass because the resume manager stores a single dataclass type per
+ source.
"""
next_page_token: Optional[str] = None
offset: Optional[int] = None
window_start: Optional[str] = None
+ parent_id: Optional[int] = None
+ # Program members only: the end of the run's updatedAt range. A resumed run keeps it, so the
+ # programs it skips and the programs it still reads cover the same range.
+ query_end: Optional[str] = None
+
+
[email protected](frozen=True)
+class FanOutParent:
+ id: int
+ created_at: Optional[datetime]
def build_base_url(munchkin_id: str) -> str:
@@ -123,6 +141,13 @@ def parse_datetime(value: Any) -> Optional[datetime]:
return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+def parse_marketo_datetime(value: Any) -> Optional[datetime]:
+ """Parse a timestamp from either API. Asset timestamps add an offset after the ``Z``."""
+ if isinstance(value, str):
+ value = re.sub(r"Z([+-]\d{4})$", r"\1", value.strip())
+ return parse_datetime(value)
+
+
def raise_for_marketo_errors(body: Mapping[str, Any]) -> None:
"""Marketo reports failures in a 200 body: ``{"success": false, "errors": [...]}``."""
if body.get("success", True):
@@ -467,6 +492,187 @@ def _asset_offset_rows(
resumable_source_manager.save_state(MarketoResumeConfig(offset=offset))
+def _has_more_pages(body: Mapping[str, Any]) -> bool:
+ """A page token means more pages unless the response says otherwise; some responses omit ``moreResult``."""
+ return bool(body.get("nextPageToken")) and body.get("moreResult") is not False
+
+
+def _fan_out_parents(
+ client: MarketoClient,
+ parent: MarketoEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[MarketoResumeConfig],
+) -> list[FanOutParent]:
+ """List every parent, ordered by id so a resumed run can skip the parents it finished."""
+ parents: list[FanOutParent] = []
+ offset = 0
+ next_token: Optional[str] = None
+ while True:
+ params: dict[str, Any] = dict(parent.extra_params)
+ if parent.transport == "asset_offset":
+ params.update(offset=offset, maxReturn=ASSET_MAX_RETURN)
+ else:
+ params["batchSize"] = REST_BATCH_SIZE
+ if next_token:
+ params["nextPageToken"] = next_token
+
+ body = client.request_json("GET", parent.path, params=params)
+ rows = body.get("result") or []
+ for row in rows:
+ if row.get("id") is not None:
+ parents.append(FanOutParent(id=int(row["id"]), created_at=parse_marketo_datetime(row.get("createdAt"))))
+ # Listing parents yields nothing, so the committed cursor still covers every row.
+ resumable_source_manager.safe_point()
+
+ if parent.transport == "asset_offset":
+ if len(rows) < ASSET_MAX_RETURN:
+ break
+ offset += len(rows)
+ else:
+ if not _has_more_pages(body):
+ break
+ next_token = body.get("nextPageToken")
+
+ return sorted(parents, key=lambda item: item.id)
+
+
+def _list_member_rows(
+ client: MarketoClient,
+ config: MarketoEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[MarketoResumeConfig],
+ resume: Optional[MarketoResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ assert config.parent is not None and config.parent_key is not None
+ parents = _fan_out_parents(client, MARKETO_ENDPOINTS[config.parent], resumable_source_manager)
+
+ for parent in parents:
+ next_token: Optional[str] = None
+ if resume is not None and resume.parent_id is not None and parent.id <= resume.parent_id:
+ if parent.id < resume.parent_id or not resume.next_page_token:
+ continue
+ next_token = resume.next_page_token
+ path = config.path.format(parent_id=parent.id)
+
+ while True:
+ params: dict[str, Any] = {"batchSize": REST_BATCH_SIZE}
+ if next_token:
+ params["nextPageToken"] = next_token
+ body = client.request_json("GET", path, params=params)
+ rows = [{**row, config.parent_key: parent.id} for row in body.get("result") or []]
+
+ more = _has_more_pages(body)
+ next_token = body.get("nextPageToken") if more else None
+ resumable_source_manager.save_state(MarketoResumeConfig(parent_id=parent.id, next_page_token=next_token))
+
+ if rows:
+ yield rows
+ else:
+ resumable_source_manager.safe_point()
+ if not more:
+ break
+
+
+def _program_member_fields(client: MarketoClient) -> list[str]:
+ body = client.request_json("GET", "/rest/v1/programs/members/describe.json")
+ names = list(PROGRAM_MEMBER_REQUIRED_FIELDS)
+ for description in body.get("result") or []:
+ for entry in description.get("fields") or []:
+ name = entry.get("name")
+ if name and name not in names:
+ names.append(name)
+ return names[:MAX_PROGRAM_MEMBER_FIELDS]
+
+
+def _in_window(row: Mapping[str, Any], window_start: datetime, window_end: datetime, is_last: bool) -> bool:
+ """Keep each member in exactly one window.
+
+ Marketo doesn't document whether ``endAt`` is inclusive, so a member updated on a boundary
+ could come back from two adjacent windows. Treat every window but the last as half-open.
+ """
+ updated_at = parse_marketo_datetime(row.get("updatedAt"))
+ if updated_at is None:
+ return True
+ if updated_at < window_start:
+ return False
+ return is_last or updated_at < window_end
+
+
+def _program_member_rows(
+ client: MarketoClient,
+ config: MarketoEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[MarketoResumeConfig],
+ resume: Optional[MarketoResumeConfig],
+ start: datetime,
+ end: datetime,
+) -> Iterator[list[dict[str, Any]]]:
+ assert config.parent is not None and config.parent_key is not None
+ if resume is not None and resume.query_end is not None:
+ end = parse_datetime(resume.query_end) or end
+ query_end = format_datetime(end)
+ parents = _fan_out_parents(client, MARKETO_ENDPOINTS[config.parent], resumable_source_manager)
+ fields = ",".join(_program_member_fields(client))
+
+ for parent in parents:
+ # No member of a program can change before the program exists.
+ parent_start = max(start, parent.created_at) if parent.created_at is not None else start
+ next_token: Optional[str] = None
+ if resume is not None and resume.parent_id is not None and parent.id <= resume.parent_id:
+ resumed_window = parse_datetime(resume.window_start)
+ if parent.id < resume.parent_id or resumed_window is None:
+ continue
+ parent_start = resumed_window
+ next_token = resume.next_page_token
+ path = config.path.format(parent_id=parent.id)
+
+ windows = bulk_windows(parent_start, end, PROGRAM_MEMBER_WINDOW_DAYS)
+ if not windows:
+ resumable_source_manager.save_state(MarketoResumeConfig(parent_id=parent.id, query_end=query_end))
+ resumable_source_manager.safe_point()
+ continue
+
+ for index, (window_start, window_end) in enumerate(windows):
+ is_last = index == len(windows) - 1
+ while True:
+ params: dict[str, Any] = {
+ "filterType": "updatedAt",
+ "startAt": format_datetime(window_start),
+ "endAt": format_datetime(window_end),
+ "fields": fields,
+ "batchSize": REST_BATCH_SIZE,
+ }
+ if next_token:
+ params["nextPageToken"] = next_token
+ body = client.request_json("GET", path, params=params)
+ rows = [
+ {**row, config.parent_key: parent.id}
+ for row in body.get("result") or []
+ if _in_window(row, window_start, window_end, is_last)
+ ]
+
+ more = _has_more_pages(body)
+ next_token = body.get("nextPageToken") if more else None
+ if more:
+ state = MarketoResumeConfig(
+ parent_id=parent.id,
+ window_start=format_datetime(window_start),
+ next_page_token=next_token,
+ query_end=query_end,
+ )
+ elif is_last:
+ state = MarketoResumeConfig(parent_id=parent.id, query_end=query_end)
+ else:
+ state = MarketoResumeConfig(
+ parent_id=parent.id, window_start=format_datetime(window_end), query_end=query_end
+ )
+ resumable_source_manager.save_state(state)
+
+ if rows:
+ yield rows
+ else:
+ resumable_source_manager.safe_point()
+ if not more:
+ break
+
+
def _resume_state(
resumable_source_manager: ResumableSourceManager[MarketoResumeConfig],
) -> Optional[MarketoResumeConfig]:
@@ -517,6 +723,11 @@ def get_rows(
if config.transport == "bulk":
start = resolve_bulk_start(resume, should_use_incremental_field, db_incremental_field_last_value, start_date)
yield from _bulk_rows(client, config, start, datetime.now(UTC), resumable_source_manager, logger)
+ elif config.transport == "program_members":
+ start = resolve_bulk_start(None, should_use_incremental_field, db_incremental_field_last_value, start_date)
+ yield from _program_member_rows(client, config, resumable_source_manager, resume, start, datetime.now(UTC))
+ elif config.transport == "list_members":
+ yield from _list_member_rows(client, config, resumable_source_manager, resume)
elif config.transport == "asset_offset":
start_offset = resume.offset if resume is not None and resume.offset is not None else 0
yield from _asset_offset_rows(client, config, resumable_source_manager, start_offset)
@@ -557,5 +768,6 @@ def marketo_source(
partition_mode="datetime" if config.partition_key else None,
partition_format="month" if config.partition_key else None,
partition_keys=[config.partition_key] if config.partition_key else None,
- sort_mode="asc",
+ # Fan-out rows arrive one parent at a time, so they are not one ordered series.
+ sort_mode=None if config.parent else "asc",
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/settings.py
index bd440619a634..f758691e1354 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/settings.py
@@ -10,7 +10,13 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# - ``asset_offset``: /rest/asset/v1 endpoints paginated with ``offset`` + ``maxReturn`` (200 max).
# - ``bulk``: the async Bulk Extract API (create -> enqueue -> poll -> download CSV). Leads and
# activities have no usable synchronous list endpoint, so they can only come this way.
-MarketoTransport = Literal["rest_token", "asset_offset", "bulk"]
+#
+# Two fan-out shapes walk a parent endpoint and page a /rest/v1 child per parent row:
+#
+# - ``list_members``: ``nextPageToken`` paging per static list.
+# - ``program_members``: ``nextPageToken`` paging per program and per ``updatedAt`` window, because
+# the endpoint needs a filter and only ``updatedAt`` reaches every member.
+MarketoTransport = Literal["rest_token", "asset_offset", "bulk", "list_members", "program_members"]
# Marketo caps a bulk export's date filter at 31 days; stay under it.
BULK_WINDOW_DAYS = 30
@@ -18,6 +24,10 @@ BULK_WINDOW_DAYS = 30
ASSET_MAX_RETURN = 200
# /rest/v1 list endpoints cap batchSize at 300.
REST_BATCH_SIZE = 300
+# Marketo rejects a program member updatedAt range longer than seven days.
+PROGRAM_MEMBER_WINDOW_DAYS = 7
+# Folder browse defaults to two levels; nested program trees go deeper than that.
+FOLDER_MAX_DEPTH = 20
def _datetime_field(name: str) -> IncrementalField:
@@ -34,12 +44,14 @@ class MarketoEndpointConfig:
name: str
transport: MarketoTransport
# For rest_token/asset_offset this is the request path. For bulk it is the export object
- # segment ("leads" / "activities") used to build /bulk/v1/<object>/export/... .
+ # segment ("leads" / "activities") used to build /bulk/v1/<object>/export/... . Fan-out paths
+ # carry a ``{parent_id}`` placeholder.
path: str
primary_key: list[str]
# Set only where a real server-side timestamp filter exists (bulk exports filter on a
- # mandatory createdAt range). Asset and /rest/v1 list endpoints stay full refresh: their
- # updated-since filters are undocumented for some resources and the collections are small.
+ # mandatory createdAt range, program members on updatedAt). Asset and other /rest/v1 list
+ # endpoints stay full refresh: their updated-since filters are undocumented for some resources
+ # and the collections are small.
incremental_field: Optional[str] = None
partition_key: Optional[str] = None
# CSV columns to coerce back to integers — bulk downloads arrive as all-string CSV.
@@ -47,6 +59,10 @@ class MarketoEndpointConfig:
# Bulk lead exports must name every column they want; activities have a fixed column set.
needs_field_list: bool = False
extra_params: dict[str, str] = field(default_factory=dict)
+ # Fan-out only: the endpoint whose rows are the parents, and the column that carries the
+ # parent id on each child row.
+ parent: Optional[str] = None
+ parent_key: Optional[str] = None
@property
def incremental_fields(self) -> list[IncrementalField]:
@@ -128,6 +144,40 @@ MARKETO_ENDPOINTS: dict[str, MarketoEndpointConfig] = {
path="/rest/asset/v1/smartCampaigns.json",
primary_key=["id"],
),
+ # Folders and programs number their ids separately, and folderType tells the two apart.
+ "folders": MarketoEndpointConfig(
+ name="folders",
+ transport="asset_offset",
+ path="/rest/asset/v1/folders.json",
+ primary_key=["id", "folderType"],
+ extra_params={"maxDepth": str(FOLDER_MAX_DEPTH)},
+ ),
+ "channels": MarketoEndpointConfig(
+ name="channels",
+ transport="asset_offset",
+ path="/rest/asset/v1/channels.json",
+ primary_key=["id"],
+ ),
+ "program_members": MarketoEndpointConfig(
+ name="program_members",
+ transport="program_members",
+ path="/rest/v1/programs/{parent_id}/members.json",
+ primary_key=["programId", "leadId"],
+ incremental_field="updatedAt",
+ partition_key="membershipDate",
+ parent="programs",
+ parent_key="programId",
+ ),
+ "list_members": MarketoEndpointConfig(
+ name="list_members",
+ transport="list_members",
+ path="/rest/v1/lists/{parent_id}/leads.json",
+ # Each row is a lead record, so `id` is the lead id.
+ primary_key=["listId", "id"],
+ partition_key="createdAt",
+ parent="lists",
+ parent_key="listId",
+ ),
}
ENDPOINTS = tuple(MARKETO_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/source.py
index 8292b23288ef..ce2ea6064945 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/source.py
@@ -80,7 +80,7 @@ class MarketoSource(ResumableSource[MarketoSourceConfig, MarketoResumeConfig]):
In Marketo, open **Admin → Web Services** for your Munchkin account ID, then **Admin → LaunchPoint** to create a custom service and copy its client ID and secret. The service's API role needs read access to leads, activities, campaigns, and assets.
-Leads and activities come through Marketo's Bulk Extract API, so the first sync backfills from the start date you set below.""",
+Leads, activities, and program members backfill from the start date you set below on the first sync.""",
iconPath="/static/services/marketo.png",
docsUrl="https://posthog.com/docs/cdp/sources/marketo",
releaseStatus=ReleaseStatus.BETA,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo.py
index fb327741cc54..9989dd22930d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo.py
@@ -133,6 +133,10 @@ def _token_response(token: str = "tok-1") -> ScriptedResponse:
return ScriptedResponse(json=_token_body(token=token))
+def _ok(body: dict[str, Any]) -> ScriptedResponse:
+ return ScriptedResponse(json={"success": True, **body})
+
+
def _recent_start() -> str:
return format_datetime(datetime.now(UTC) - timedelta(days=5))
@@ -531,3 +535,142 @@ class TestMarketo:
assert network.session_options == []
assert network.requests_log == []
+
+ def test_list_members_walk_every_list_in_id_order(self) -> None:
+ result = _driver().run(
+ "list_members",
+ [
+ _token_response(),
+ _ok({"result": [{"id": 20}, {"id": 10}], "nextPageToken": "l2", "moreResult": True}),
+ _ok({"result": [{"id": 5}], "moreResult": False}),
+ _ok({"result": []}),
+ # A page token with no moreResult still means another page.
+ _ok({"result": [{"id": 1}], "nextPageToken": "t2"}),
+ _ok({"result": [{"id": 2}], "moreResult": False}),
+ _ok({"result": [{"id": 3}], "moreResult": False}),
+ ],
+ )
+
+ assert result.raised is None
+ assert result.paths[3:] == [
+ "/rest/v1/lists/5/leads.json",
+ "/rest/v1/lists/10/leads.json",
+ "/rest/v1/lists/10/leads.json",
+ "/rest/v1/lists/20/leads.json",
+ ]
+ assert result.params("nextPageToken")[3:] == [None, None, "t2", None]
+ assert result.rows == [{"id": 1, "listId": 10}, {"id": 2, "listId": 10}, {"id": 3, "listId": 20}]
+ assert result.saved_states == [
+ MarketoResumeConfig(parent_id=5),
+ MarketoResumeConfig(parent_id=10, next_page_token="t2"),
+ MarketoResumeConfig(parent_id=10),
+ MarketoResumeConfig(parent_id=20),
+ ]
+ assert result.final_state is None
+ assert result.response is not None and result.response.sort_mode is None
+
+ @pytest.mark.parametrize(
+ "resume,expected_paths,expected_tokens",
+ [
+ (
+ MarketoResumeConfig(parent_id=10, next_page_token="t2"),
+ ["/rest/v1/lists/10/leads.json", "/rest/v1/lists/20/leads.json"],
+ ["t2", None],
+ ),
+ (MarketoResumeConfig(parent_id=10), ["/rest/v1/lists/20/leads.json"], [None]),
+ # The list the cursor was in is gone, so the next list starts from its first page.
+ (MarketoResumeConfig(parent_id=15, next_page_token="t9"), ["/rest/v1/lists/20/leads.json"], [None]),
+ ],
+ )
+ def test_list_members_resume_skips_finished_lists(
+ self,
+ resume: MarketoResumeConfig,
+ expected_paths: list[str],
+ expected_tokens: list[Optional[str]],
+ ) -> None:
+ result = _driver().run(
+ "list_members",
+ [
+ _token_response(),
+ _ok({"result": [{"id": 5}, {"id": 10}, {"id": 20}], "moreResult": False}),
+ *[_ok({"result": [{"id": 1}], "moreResult": False}) for _ in expected_paths],
+ ],
+ resume_state=resume,
+ )
+
+ assert result.raised is None
+ assert result.paths[2:] == expected_paths
+ assert result.params("nextPageToken")[2:] == expected_tokens
+
+ def test_program_members_query_each_program_in_seven_day_windows_from_its_creation(self) -> None:
+ start = (datetime.now(UTC) - timedelta(days=10)).replace(microsecond=0)
+ boundary = start + timedelta(days=7)
+ created = (datetime.now(UTC) - timedelta(days=3)).replace(microsecond=0)
+ member = {"leadId": 1, "statusName": "Member"}
+ result = _driver(format_datetime(start)).run(
+ "program_members",
+ [
+ _token_response(),
+ # Asset timestamps carry an offset after the Z.
+ _ok(
+ {
+ "result": [
+ {"id": 2, "createdAt": "2015-01-01T00:00:00Z+0000"},
+ {"id": 1, "createdAt": format_datetime(created) + "+0000"},
+ ]
+ }
+ ),
+ _ok({"result": [{"fields": [{"name": "leadId"}, {"name": "statusName"}]}]}),
+ _ok({"result": [{**member, "updatedAt": format_datetime(created)}], "moreResult": False}),
+ # A member updated on the boundary comes back from both windows and is kept once.
+ _ok({"result": [{**member, "leadId": 2, "updatedAt": format_datetime(boundary)}]}),
+ _ok({"result": [{**member, "leadId": 2, "updatedAt": format_datetime(boundary)}]}),
+ ],
+ )
+
+ assert result.raised is None
+ members = [request for request in result.requests if request.path.endswith("/members.json")]
+ assert [request.path for request in members] == [
+ "/rest/v1/programs/1/members.json",
+ "/rest/v1/programs/2/members.json",
+ "/rest/v1/programs/2/members.json",
+ ]
+ assert [request.param("startAt") for request in members] == [
+ format_datetime(created),
+ format_datetime(start),
+ format_datetime(boundary),
+ ]
+ assert members[1].param("endAt") == format_datetime(boundary)
+ assert {request.param("filterType") for request in members} == {"updatedAt"}
+ assert members[0].param("fields") == "leadId,programId,membershipDate,updatedAt,statusName"
+ assert [(row["programId"], row["leadId"]) for row in result.rows] == [(1, 1), (2, 2)]
+ assert [(state.parent_id, state.window_start) for state in result.saved_states] == [
+ (1, None),
+ (2, format_datetime(boundary)),
+ (2, None),
+ ]
+ assert {state.query_end for state in result.saved_states} == {members[0].param("endAt")}
+ assert result.response is not None and result.response.sort_mode is None
+
+ def test_program_members_resume_inside_the_saved_window_with_the_saved_end(self) -> None:
+ window_start = format_datetime((datetime.now(UTC) - timedelta(days=2)).replace(microsecond=0))
+ query_end = format_datetime((datetime.now(UTC) - timedelta(days=1)).replace(microsecond=0))
+ result = _driver().run(
+ "program_members",
+ [
+ _token_response(),
+ _ok({"result": [{"id": 1, "createdAt": "2015-01-01T00:00:00Z+0000"}, {"id": 2}]}),
+ _ok({"result": []}),
+ _ok({"result": [{"leadId": 7, "updatedAt": window_start}], "moreResult": False}),
+ ],
+ resume_state=MarketoResumeConfig(
+ parent_id=2, window_start=window_start, next_page_token="p3", query_end=query_end
+ ),
+ )
+
+ assert result.raised is None
+ assert result.paths[3:] == ["/rest/v1/programs/2/members.json"]
+ assert result.params("startAt")[3:] == [window_start]
+ assert result.params("endAt")[3:] == [query_end]
+ assert result.params("nextPageToken")[3:] == ["p3"]
+ assert result.rows == [{"leadId": 7, "updatedAt": window_start, "programId": 2}]