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 courier lists, tenant users, journeys and digest tables (#104393)

Tom Owers290e0b78e675
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 022644b989a0..1e9132a31745 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
@@ -2104,19 +2104,19 @@ Note: Coupa Core API is very large (several hundred documented resources across
## Courier — gaps
-Today (9): `AudienceMembers`, `Audiences`, `AuditEvents`, `Brands`, `ListSubscriptions`, `MessageHistory`, `Messages`, `NotificationTemplates`, `Tenants`
+Today (14): `AudienceMembers`, `Audiences`, `AuditEvents`, `Brands`, `DigestInstances`, `JourneyVersions`, `Journeys`, `ListSubscriptions`, `Lists`, `MessageHistory`, `Messages`, `NotificationTemplates`, `TenantUsers`, `Tenants`
Diffed against: <https://www.courier.com/docs/llms.txt>
-- [ ] `lists (GET /lists)` — core recipient grouping object; currently no way to see which lists exist (high)
+- [x] `lists (GET /lists)` — core recipient grouping object; currently no way to see which lists exist (high)
- [x] `lists/{list_id}/subscriptions` — membership table mapping users to lists - required for any audience-size or churn analysis (high)
- [x] `notification-templates (GET /notifications)` — lookup table resolving the template IDs carried on every synced message (high)
- [x] `messages/{id}/history` — per-message state transition history (queued, sent, delivered, opened, clicked) - the deliverability funnel (high)
- [x] `audiences/{audience_id}/members` — membership table for audiences we already sync; audiences without members are just filter definitions (high)
-- [ ] `tenants/{tenant_id}/users` — membership table joining users to the tenants we already sync (medium)
+- [x] `tenants/{tenant_id}/users` — membership table joining users to the tenants we already sync (medium)
- [ ] `automations (GET /automations)` — lookup for saved automation templates that trigger sends (medium)
-- [ ] `journeys (GET /journeys, plus journey versions)` — journey definitions and versions needed to attribute messages to a flow (medium)
-- [ ] `digests (list digest instances)` — digest batching data explaining why messages were grouped or delayed (medium)
+- [x] `journeys (GET /journeys, plus journey versions)` — journey definitions and versions needed to attribute messages to a flow (medium)
+- [x] `digests (list digest instances)` — digest batching data explaining why messages were grouped or delayed (medium). Digest schedules have no listing endpoint; their ids are flattened out of `GET /preferences/sections`, where Courier nests them under each topic's digest config.
- [ ] `notification-templates/{id}/versions` — template version history for before/after performance comparison (low)
- [ ] `workspace-preferences (topics and sections)` — lookup for subscription topics referenced by user preference data (low)
- [ ] `user-preferences (GET /users/{id}/preferences)` — per-user subscription state for opt-out analysis (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/canonical_descriptions.py
index d993afe847ab..71fe6934e364 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/canonical_descriptions.py
@@ -81,6 +81,16 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"version": "Version identifier of the brand.",
},
},
+ "Lists": {
+ "description": "A named group of recipients that a send can target as a whole, instead of one user at a time.",
+ "docs_url": "https://www.courier.com/docs/api-reference/lists/list-lists",
+ "columns": {
+ "id": "Unique identifier for the list.",
+ "name": "Name of the list.",
+ "created": "Timestamp at which the list was created.",
+ "updated": "Timestamp at which the list was last updated.",
+ },
+ },
"ListSubscriptions": {
"description": "A user's subscription to a list, with the notification preferences recorded for that subscription.",
"docs_url": "https://www.courier.com/docs/api-reference/lists/list-subscriptions-for-a-list",
@@ -106,6 +116,55 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"event_ids": "Event ids mapped to this template.",
},
},
+ "TenantUsers": {
+ "description": "A user's membership of a tenant, which is who a tenant-scoped send reaches.",
+ "docs_url": "https://www.courier.com/docs/api-reference/tenants/get-users-in-tenant",
+ "columns": {
+ "tenant_id": "Unique identifier of the tenant the user belongs to.",
+ "user_id": "Unique identifier of the user.",
+ "type": "Type of the association. Always `user`.",
+ "profile": "Tenant-specific profile that overrides the user's workspace profile for sends in this tenant.",
+ },
+ },
+ "Journeys": {
+ "description": "A journey in the workspace: the multi-step flow a message can be attributed to. Lists the published version of each journey.",
+ "docs_url": "https://www.courier.com/docs/api-reference/journeys/list-journeys",
+ "columns": {
+ "id": "Unique identifier of the journey.",
+ "name": "Name of the journey.",
+ "version": "Which version of the journey this row describes (`published` or `draft`).",
+ "createdAt": "Timestamp at which the journey was created.",
+ "updatedAt": "Timestamp at which the journey was last updated.",
+ },
+ },
+ "JourneyVersions": {
+ "description": "A published version of a journey, most recent first, giving the publish history behind a journey's current behaviour.",
+ "docs_url": "https://www.courier.com/docs/api-reference/journeys/list-versions-of-a-journey",
+ "columns": {
+ "journey_id": "Unique identifier of the journey this version belongs to.",
+ "version": "Version identifier, used to roll the journey back to this publish.",
+ "name": "Name the journey carried at this version.",
+ "created": "Timestamp at which the version was created.",
+ "creator": "User who created the version.",
+ "published": "Timestamp at which the version was published.",
+ },
+ },
+ "DigestInstances": {
+ "description": "What a digest schedule has accumulated for one user, explaining why their messages were batched or held back.",
+ "docs_url": "https://www.courier.com/docs/api-reference/digests/list-digest-instances",
+ "columns": {
+ "schedule_id": "Unique identifier of the digest schedule the instance belongs to.",
+ "digest_instance_id": "Unique identifier for the digest instance.",
+ "status": "Whether the instance is still accumulating events (`IN_PROGRESS`) or has been released (`COMPLETED`).",
+ "event_count": "Total number of events received for this instance.",
+ "user_id": "Unique identifier of the user the instance belongs to.",
+ "tenant_id": "Unique identifier of the tenant the instance belongs to, if any.",
+ "categories": "Categories configured for the digest, with how events are retained in each.",
+ "category_key_counts": "Number of events received per category key.",
+ "disabled": "Whether the digest instance has been disabled.",
+ "created_at": "Timestamp at which the digest instance was created.",
+ },
+ },
"Tenants": {
"description": "A tenant used to scope notification sending and preferences for a group of recipients (e.g. a customer account).",
"docs_url": "https://www.courier.com/docs/reference/tenants/list",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/courier.py b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/courier.py
index 77b6b76c121f..5f00db4bf211 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/courier.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/courier.py
@@ -1,8 +1,12 @@
import dataclasses
+from collections.abc import Callable
from datetime import UTC, datetime
from typing import Any, Optional, cast
+from urllib.parse import quote
+import structlog
from dateutil import parser as date_parser
+from requests import Response
from posthog.dataclasses import frozen
@@ -15,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
build_dependent_resource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponseCursorPaginator,
SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
@@ -41,6 +46,28 @@ AUTH_ERROR_MESSAGE = "Invalid or missing authentication credentials"
DEFAULT_INCREMENTAL_START = "1970-01-01T00:00:00Z"
+logger = structlog.get_logger(__name__)
+
+
+class CourierCursorPaginator(JSONResponseCursorPaginator):
+ """Cursor paginator that stops once the cursor stops advancing.
+
+ Courier's journey-versions endpoint returns a `paging.cursor` and its reference calls the
+ endpoint cursor-paged, but it documents no `cursor` request param. An API that ignores the
+ param returns the same page and the same cursor forever, so a repeated cursor ends the walk
+ here the way a repeated next URL ends it in `BaseNextUrlPaginator`.
+ """
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ previous_cursor = self._cursor_value
+ super().update_state(response, data)
+ if self._has_next_page and self._cursor_value == previous_cursor:
+ logger.warning(
+ "Pagination is not advancing (repeated cursor); treating as last page",
+ paginator=str(self),
+ )
+ self._has_next_page = False
+
@frozen
class CourierResumeConfig:
@@ -82,6 +109,20 @@ def _normalize_row(item: dict[str, Any], timestamp_fields: tuple[str, ...]) -> d
return item
+def _encode_parent_field(source_field: str, target_field: str) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ """Percent-encode a parent id into the field the child path binds.
+
+ `process_parent_data_item` binds the path with `str.format`, so a digest schedule id in the
+ legacy `sch/{uuid}` form would splice an unescaped "/" into the path and 404.
+ """
+
+ def _mapper(item: dict[str, Any]) -> dict[str, Any]:
+ item[target_field] = quote(str(item[source_field]), safe="")
+ return item
+
+ return _mapper
+
+
def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:
config = ENDPOINTS_CONFIG[name]
@@ -229,6 +270,10 @@ def _fanout_resource(
}
if not config.paginated:
child_endpoint_extra["paginator"] = SinglePagePaginator()
+ elif config.child_cursor_path:
+ child_endpoint_extra["paginator"] = CourierCursorPaginator(
+ cursor_path=config.child_cursor_path, cursor_param="cursor"
+ )
def no_child_time_filter(_field: str) -> IncrementalConfig | None:
# No Courier fan-out child accepts a timestamp filter of its own; an incremental run is
@@ -248,9 +293,15 @@ def _fanout_resource(
incremental_config_factory=no_child_time_filter,
parent_endpoint_extra={
"data_selector": parent_config.data_selector,
- "data_selector_required": True,
+ "data_selector_required": parent_config.data_selector_required,
},
child_endpoint_extra=child_endpoint_extra,
+ parent_data_map=(
+ _encode_parent_field(config.encode_parent_field, fanout.resolve_field)
+ if config.encode_parent_field is not None
+ else None
+ ),
+ page_size_param=config.fanout_page_size_param,
resume_hook=save_checkpoint,
initial_paginator_state=initial_state,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/settings.py
index ae8ed7db2083..cdab1d763430 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/settings.py
@@ -52,9 +52,21 @@ class CourierEndpointConfig:
page_size: int = COURIER_PAGE_SIZE
# False where the endpoint returns every record in one response and takes no cursor.
paginated: bool = True
+ # False where a missing `data_selector` key is a legitimate empty response rather than an
+ # envelope change worth failing the sync over.
+ data_selector_required: bool = True
# Set where the endpoint only exists per parent record, so rows are collected by walking the
# parent listing first.
fanout: DependentEndpointConfig | None = None
+ # Page-size param the fan-out sends to both its parent and child listing. None for a parent
+ # that documents no page-size param at all; the child then carries its own in `child_params`.
+ fanout_page_size_param: str | None = "limit"
+ # Where a fan-out child finds its own next-page cursor, when that differs from the parent's
+ # `cursor_path`. One paginator config is shared by both halves of a fan-out otherwise.
+ child_cursor_path: str | None = None
+ # Parent field percent-encoded into the fan-out's `resolve_field` before the child path is
+ # bound, for an id that can contain a literal "/".
+ encode_parent_field: str | None = None
# Filter param on the *parent* listing, for a fan-out child whose own endpoint takes no
# timestamp filter. Bounding the parent walk is the only way such a child can sync
# incrementally instead of re-fetching every parent's records every run.
@@ -67,10 +79,15 @@ class CourierEndpointConfig:
# Parent listings a fan-out endpoint walks that are not themselves syncable tables.
FANOUT_ONLY_CONFIGS: dict[str, CourierEndpointConfig] = {
- "Lists": CourierEndpointConfig(
- name="Lists",
- path="/lists",
- data_selector="items",
+ # Digest schedules have no listing endpoint of their own: Courier only exposes a schedule id
+ # nested inside the digest config of a workspace preference's topics, so they are flattened
+ # out of the one unpaginated preferences response. A workspace with no digest configured
+ # matches nothing here, which is why the selector is not required.
+ "DigestSchedules": CourierEndpointConfig(
+ name="DigestSchedules",
+ path="/preferences/sections",
+ data_selector="results[*].topics[*].digest.schedules[*]",
+ data_selector_required=False,
),
}
@@ -161,6 +178,16 @@ ENDPOINTS_CONFIG: dict[str, CourierEndpointConfig] = {
data_selector="results",
primary_keys=("id",),
),
+ # The recipient groups every list-targeted send resolves through. No server-side timestamp
+ # filter, so full refresh only.
+ "Lists": CourierEndpointConfig(
+ name="Lists",
+ path="/lists",
+ data_selector="items",
+ primary_keys=("id",),
+ partition_key="created",
+ timestamp_fields=("created", "updated"),
+ ),
# Who is subscribed to each list. Courier documents no timestamp filter on either the list
# walk or the subscriptions, so full refresh only.
"ListSubscriptions": CourierEndpointConfig(
@@ -199,6 +226,90 @@ ENDPOINTS_CONFIG: dict[str, CourierEndpointConfig] = {
primary_keys=("id",),
cursor_path="cursor",
),
+ # Who belongs to each tenant, which is who a tenant-scoped send reaches. The association
+ # carries no timestamp, so full refresh only.
+ "TenantUsers": CourierEndpointConfig(
+ name="TenantUsers",
+ path="/tenants/{tenant_id}/users",
+ data_selector="items",
+ # The association repeats its own `tenant_id`, but a user belongs to many tenants, so the
+ # parent's id is projected in as well rather than trusting an optional field to key rows.
+ primary_keys=("tenant_id", "user_id"),
+ cursor_path="cursor",
+ fanout=DependentEndpointConfig(
+ parent_name="Tenants",
+ resolve_param="tenant_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "tenant_id"},
+ # A tenant deleted between the listing and this fetch 404s; skip that parent rather
+ # than failing the whole fan-out.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
+ # The flow definitions a message is attributed to. Returns the published version of each
+ # journey; no server-side timestamp filter, so full refresh only.
+ "Journeys": CourierEndpointConfig(
+ name="Journeys",
+ path="/journeys",
+ data_selector="templates",
+ primary_keys=("id",),
+ partition_key="createdAt",
+ timestamp_fields=("createdAt", "updatedAt"),
+ cursor_path="cursor",
+ ),
+ # Each journey's publish history, for comparing performance across versions.
+ "JourneyVersions": CourierEndpointConfig(
+ name="JourneyVersions",
+ path="/journeys/{templateId}/versions",
+ data_selector="results",
+ # The version entry carries no reference back to its journey, so the parent's id is
+ # projected in to make rows joinable and unique across journeys.
+ primary_keys=("journey_id", "version"),
+ partition_key="created",
+ timestamp_fields=("created", "published"),
+ # The parent /journeys walk finds its cursor at the top level; this endpoint nests its
+ # own under `paging`.
+ cursor_path="cursor",
+ child_cursor_path="paging.cursor",
+ fanout=DependentEndpointConfig(
+ parent_name="Journeys",
+ resolve_param="templateId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "journey_id"},
+ # A journey archived between the listing and this fetch 404s; skip that parent
+ # rather than failing the whole fan-out.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
+ # What each digest schedule has accumulated per user, explaining why messages were batched or
+ # held back. No server-side timestamp filter, so full refresh only.
+ "DigestInstances": CourierEndpointConfig(
+ name="DigestInstances",
+ path="/digests/schedules/{schedule_id}/instances",
+ data_selector="items",
+ # `digest_instance_id` is documented as unique to the instance, but an instance only
+ # exists within its schedule, so the schedule is part of the key.
+ primary_keys=("schedule_id", "digest_instance_id"),
+ partition_key="created_at",
+ timestamp_fields=("created_at",),
+ cursor_path="cursor",
+ encode_parent_field="schedule_id",
+ # The preferences listing the schedule ids come from takes no params at all.
+ fanout_page_size_param=None,
+ fanout=DependentEndpointConfig(
+ parent_name="DigestSchedules",
+ resolve_param="schedule_id",
+ resolve_field="encoded_schedule_id",
+ include_from_parent=["schedule_id"],
+ parent_field_renames={"schedule_id": "schedule_id"},
+ child_params={"limit": COURIER_PAGE_SIZE},
+ # A schedule removed between the preferences read and this fetch 404s; skip it
+ # rather than failing the whole fan-out.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
}
# Every config a fan-out can resolve a parent against, syncable or not.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/tests/test_courier.py b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/tests/test_courier.py
index ec1b815b6e36..a42ad82108e1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/tests/test_courier.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/tests/test_courier.py
@@ -52,6 +52,26 @@ def _page(endpoint: str, rows: list[dict[str, Any]], cursor: str | None) -> Resp
return _make_http_response(body)
+def _versions_page(rows: list[dict[str, Any]], cursor: str | None) -> Response:
+ """Build a journey-versions response, whose cursor nests under `paging`.
+
+ The endpoint's parent listing carries its cursor at the response's top level instead, so
+ `_page` builds the wrong shape for this one.
+ """
+ return _make_http_response({"results": rows, "paging": {"more": cursor is not None, "cursor": cursor}})
+
+
+def _preferences_page(schedules: list[dict[str, Any]] | None) -> Response:
+ """Build a `/preferences/sections` response with `schedules` nested where Courier puts them.
+
+ `None` is a workspace whose topics have no digest configured at all.
+ """
+ topic: dict[str, Any] = {"id": "pt_1", "name": "Product updates"}
+ if schedules is not None:
+ topic["digest"] = {"schedules": schedules}
+ return _make_http_response({"results": [{"id": "ps_1", "topics": [topic]}]})
+
+
class TestGetResource:
def test_incremental_uses_enqueued_after_filter(self) -> None:
resource = get_resource("Messages", should_use_incremental_field=True)
@@ -61,7 +81,16 @@ class TestGetResource:
assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
@parameterized.expand(
- [("Messages",), ("AuditEvents",), ("Audiences",), ("Brands",), ("NotificationTemplates",), ("Tenants",)]
+ [
+ ("Messages",),
+ ("AuditEvents",),
+ ("Audiences",),
+ ("Brands",),
+ ("Lists",),
+ ("NotificationTemplates",),
+ ("Tenants",),
+ ("Journeys",),
+ ]
)
def test_full_refresh_sends_no_timestamp_filter(self, endpoint: str) -> None:
resource = get_resource(endpoint, should_use_incremental_field=False)
@@ -69,7 +98,17 @@ class TestGetResource:
assert set(params) == {"limit"}
assert resource["write_disposition"] == "replace"
- @parameterized.expand([("AuditEvents",), ("Audiences",), ("Brands",), ("NotificationTemplates",), ("Tenants",)])
+ @parameterized.expand(
+ [
+ ("AuditEvents",),
+ ("Audiences",),
+ ("Brands",),
+ ("Lists",),
+ ("NotificationTemplates",),
+ ("Tenants",),
+ ("Journeys",),
+ ]
+ )
def test_endpoints_without_a_server_filter_ignore_incremental_flag(self, endpoint: str) -> None:
# These endpoints have no documented server-side timestamp filter, so even if asked for
# an incremental run there is no filter param to add.
@@ -118,8 +157,10 @@ class TestCourierSourceTransport:
("AuditEvents",),
("Audiences",),
("Brands",),
+ ("Lists",),
("NotificationTemplates",),
("Tenants",),
+ ("Journeys",),
]
)
def test_rows_extracted_from_endpoint_envelope(self, endpoint: str) -> None:
@@ -151,20 +192,21 @@ class TestCourierSourceTransport:
saved = [call.args[0] for call in manager.save_state.call_args_list]
assert saved == [CourierResumeConfig(cursor="cursor-1"), CourierResumeConfig(cursor="cursor-2")]
- def test_tenants_pages_on_top_level_cursor(self) -> None:
- # Tenants is the one endpoint whose cursor lives at the response's top level rather than
- # nested under `paging` — a regression here silently disables pagination.
+ @parameterized.expand([("Tenants",), ("Journeys",)])
+ def test_pages_on_top_level_cursor(self, endpoint: str) -> None:
+ # These endpoints return their cursor at the response's top level rather than nested
+ # under `paging`, so a regression here silently disables pagination.
manager = MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False
responses = [
- _page("Tenants", [{"id": "t1"}], cursor="cursor-1"),
- _page("Tenants", [{"id": "t2"}], cursor=None),
+ _page(endpoint, [{"id": "r1"}], cursor="cursor-1"),
+ _page(endpoint, [{"id": "r2"}], cursor=None),
]
- _, sent_params, rows = self._drive("Tenants", manager, responses)
+ _, sent_params, rows = self._drive(endpoint, manager, responses)
assert [p.get("cursor") for p in sent_params] == [None, "cursor-1"]
- assert [row["id"] for row in rows] == ["t1", "t2"]
+ assert [row["id"] for row in rows] == ["r1", "r2"]
def test_resume_seeds_paginator_with_saved_cursor(self) -> None:
manager = MagicMock(spec=ResumableSourceManager)
@@ -244,8 +286,10 @@ class TestCourierSourceTransport:
("AuditEvents", ["timestamp"], "asc"),
("Audiences", ["created_at"], "asc"),
("Brands", None, "asc"),
+ ("Lists", ["created"], "asc"),
("NotificationTemplates", None, "asc"),
("Tenants", None, "asc"),
+ ("Journeys", ["createdAt"], "asc"),
]
)
def test_source_response_partitioning_and_sort_mode(
@@ -373,6 +417,122 @@ class TestCourierFanout:
assert all("enqueued_after" not in p for p in params)
+ def test_tenant_users_are_fetched_per_tenant(self) -> None:
+ # A user belongs to many tenants, so without the projected parent id the primary key
+ # collapses to the user and rows collide across tenants.
+ paths, params, rows = self._drive(
+ "TenantUsers",
+ [
+ _page("Tenants", [{"id": "tenant-a"}, {"id": "tenant-b"}], cursor=None),
+ _page("TenantUsers", [{"user_id": "u1", "type": "user"}], cursor=None),
+ _page("TenantUsers", [{"user_id": "u2", "type": "user"}], cursor=None),
+ ],
+ )
+
+ assert paths == ["/tenants", "/tenants/tenant-a/users", "/tenants/tenant-b/users"]
+ assert [(row["tenant_id"], row["user_id"]) for row in rows] == [("tenant-a", "u1"), ("tenant-b", "u2")]
+ assert all(p["limit"] == 100 for p in params)
+
+ def test_journey_versions_carry_their_journey_id(self) -> None:
+ paths, _, rows = self._drive(
+ "JourneyVersions",
+ [
+ _page("Journeys", [{"id": "jry-1", "createdAt": "2026-01-15T10:30:00Z"}], cursor=None),
+ _page("JourneyVersions", [{"version": "v2", "created": 1_700_000_000_000}], cursor=None),
+ ],
+ )
+
+ assert paths == ["/journeys", "/journeys/jry-1/versions"]
+ assert rows[0]["journey_id"] == "jry-1"
+ # The table partitions on `created`, which arrives as epoch millis.
+ assert rows[0]["created"] == datetime.fromtimestamp(1_700_000_000_000 / 1000, tz=UTC)
+
+ def test_journey_versions_page_on_their_own_nested_cursor(self) -> None:
+ # The parent /journeys walk finds its cursor at the top level, so a child that reused it
+ # would stop after one page and drop most of a journey's publish history.
+ paths, params, rows = self._drive(
+ "JourneyVersions",
+ [
+ _page("Journeys", [{"id": "jry-1"}], cursor=None),
+ _versions_page([{"version": "v2"}], cursor="cursor-1"),
+ _versions_page([{"version": "v1"}], cursor=None),
+ ],
+ )
+
+ assert paths == ["/journeys", "/journeys/jry-1/versions", "/journeys/jry-1/versions"]
+ assert [p.get("cursor") for p in params] == [None, None, "cursor-1"]
+ assert [row["version"] for row in rows] == ["v2", "v1"]
+
+ def test_journey_versions_stop_when_the_cursor_repeats(self) -> None:
+ # Courier documents no cursor param on this endpoint. If it ignores the one we send, the
+ # same page and cursor come back forever, so a repeated cursor has to end the walk.
+ paths, _, rows = self._drive(
+ "JourneyVersions",
+ [
+ _page("Journeys", [{"id": "jry-1"}], cursor=None),
+ _versions_page([{"version": "v1"}], cursor="stuck"),
+ _versions_page([{"version": "v1"}], cursor="stuck"),
+ ],
+ )
+
+ assert paths == ["/journeys", "/journeys/jry-1/versions", "/journeys/jry-1/versions"]
+ assert [row["version"] for row in rows] == ["v1", "v1"]
+
+ def test_digest_instances_flatten_schedule_ids_out_of_the_preferences_response(self) -> None:
+ # Courier exposes no listing of digest schedules, so the ids come from the schedules
+ # nested inside each preference topic's digest config.
+ paths, params, rows = self._drive(
+ "DigestInstances",
+ [
+ _preferences_page([{"schedule_id": "sch_01abc"}, {"schedule_id": "sch_02def"}]),
+ _page("DigestInstances", [{"digest_instance_id": "di-1", "user_id": "u1"}], cursor=None),
+ _page("DigestInstances", [{"digest_instance_id": "di-2", "user_id": "u2"}], cursor=None),
+ ],
+ )
+
+ assert paths == [
+ "/preferences/sections",
+ "/digests/schedules/sch_01abc/instances",
+ "/digests/schedules/sch_02def/instances",
+ ]
+ assert [(row["schedule_id"], row["digest_instance_id"]) for row in rows] == [
+ ("sch_01abc", "di-1"),
+ ("sch_02def", "di-2"),
+ ]
+ # The preferences listing documents no params at all; the child still pages at 100.
+ assert params[0] == {}
+ assert params[1]["limit"] == 100
+
+ def test_digest_instances_percent_encode_a_legacy_schedule_id(self) -> None:
+ # Schedule ids created before the `sch_...` format contain a literal "/", which would
+ # otherwise be spliced into the path unescaped and 404.
+ paths, _, rows = self._drive(
+ "DigestInstances",
+ [
+ _preferences_page([{"schedule_id": "sch/00000000-0000-0000-0000-000000000000"}]),
+ _page(
+ "DigestInstances",
+ [{"digest_instance_id": "di-1", "created_at": "2026-01-15T10:30:00Z"}],
+ cursor=None,
+ ),
+ ],
+ )
+
+ assert paths == [
+ "/preferences/sections",
+ "/digests/schedules/sch%2F00000000-0000-0000-0000-000000000000/instances",
+ ]
+ assert rows[0]["schedule_id"] == "sch/00000000-0000-0000-0000-000000000000"
+ assert rows[0]["created_at"] == datetime(2026, 1, 15, 10, 30, 0, tzinfo=UTC)
+
+ def test_digest_instances_sync_nothing_when_no_digest_is_configured(self) -> None:
+ # A workspace with no digests has no `digest` key to match, which is a legitimate empty
+ # result rather than the envelope change a required selector fails the sync over.
+ paths, _, rows = self._drive("DigestInstances", [_preferences_page(None)])
+
+ assert paths == ["/preferences/sections"]
+ assert rows == []
+
class TestValidateCredentials:
@parameterized.expand(