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.

fix(clerk): stop plan-gated and removed endpoints failing the sync (#78198)

Tom Owers5da0959e2b2f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
index 80ba98f8a4f6..2163a7825e41 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
@@ -330,7 +330,9 @@ Four tables, and the two that matter most for an auth provider are missing.
- [x] `allowlist_identifiers`, `blocklist_identifiers`.
- [x] `domains`, `saml_connections`, `enterprise_connections` — enterprise SSO configuration.
- [x] `billing` and `commerce` — Clerk's newer billing surface (shipped as `commerce_plans` and `commerce_subscription_items`)
-- [x] `oauth_applications`, `api_keys`, `m2m_tokens`, `machines`, `clients`.
+- [x] `oauth_applications`, `api_keys`, `m2m_tokens`, `machines`.
+- [ ] `clients` — retired. Clerk deprecated `GET /v1/clients` and it now answers 410, with no
+ replacement listing endpoint.
- [ ] `email_addresses`, `phone_numbers` as their own tables.
- [x] `jwt_templates`, `redirect_urls`, `role_sets`, `email_templates`, `sms_templates`
- [ ] `actor_tokens`, `sign_in_tokens`, `webhooks`
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/canonical_descriptions.py
index 5ba28cdaa34a..ffb41d725bc7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/canonical_descriptions.py
@@ -96,18 +96,6 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
abandon_at="Time the session is abandoned, as a Unix timestamp in milliseconds.",
),
},
- "clients": {
- "description": "A client representing a browser or native app the Clerk instance has seen.",
- "docs_url": "https://clerk.com/docs/reference/backend-api/tag/Clients",
- "columns": _columns(
- session_ids="IDs of the sessions that belong to the client.",
- sessions="The sessions that belong to the client.",
- sign_in_id="ID of the sign-in attempt in progress on the client.",
- sign_up_id="ID of the sign-up attempt in progress on the client.",
- last_active_session_id="ID of the session that was last active on the client.",
- last_authentication_strategy="The authentication strategy last used to authenticate on the client.",
- ),
- },
"organization_invitations": {
"description": "An invitation asking a user to join an organization in the Clerk instance.",
"docs_url": "https://clerk.com/docs/reference/backend-api/tag/Organization-Invitations",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/clerk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/clerk.py
index 1928af5fac39..d1a8842d95b5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/clerk.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/clerk.py
@@ -1,15 +1,21 @@
import functools
import dataclasses
+from collections.abc import Iterator
from typing import Any, Optional
from requests import Request, Response
-from requests.exceptions import RequestException
+from requests.exceptions import HTTPError, RequestException
+from structlog.types import FilteringBoundLogger
-from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.settings import CLERK_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.settings import (
+ CLERK_ENDPOINTS,
+ RETIRED_ENDPOINTS,
+ ClerkEndpointConfig,
+)
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,
+ rest_api_resources,
)
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 (
@@ -24,25 +30,24 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
class ClerkResumeConfig:
"""Resume state for Clerk endpoints.
- All Clerk endpoints use offset-based pagination, so the checkpoint is just
- the next offset to fetch. On resume we start fetching from the saved offset
- (at-least-once semantics): any duplicates from a batch that was yielded but
- whose checkpoint did not persist are deduped by the ``id`` primary key.
+ Flat endpoints use offset-based pagination, so the checkpoint is just the next offset to
+ fetch. Fan-out endpoints checkpoint per parent instead, and store the framework's own
+ dependent-resource state under ``fan_out``. On resume we start fetching from the saved
+ position (at-least-once semantics): any duplicates from a batch that was yielded but whose
+ checkpoint did not persist are deduped by the ``id`` primary key.
"""
- offset: int
-
-
-def get_resource(name: str) -> EndpointResource:
- config = CLERK_ENDPOINTS[name]
+ offset: int = 0
+ fan_out: Optional[dict[str, Any]] = None
- params: dict[str, Any] = {
- "limit": config.page_size,
- }
+def _resource(name: str, config: ClerkEndpointConfig, path: str, params: dict[str, Any]) -> EndpointResource:
endpoint_config: Endpoint = {
- "path": config.path,
+ "path": path,
"params": params,
+ # A fan-out's parent and child paginate different response shapes, so each resource
+ # carries its own paginator rather than sharing one at the client level.
+ "paginator": ClerkPaginator(limit=config.page_size, data_key=config.data_key),
}
# Only set data_selector for endpoints that return wrapped responses {data: [...], total_count: ...}
@@ -50,14 +55,33 @@ def get_resource(name: str) -> EndpointResource:
endpoint_config["data_selector"] = config.data_key
return {
- "name": config.name,
- "table_name": config.name,
+ "name": name,
+ "table_name": name,
"write_disposition": "replace",
"endpoint": endpoint_config,
"table_format": "delta",
}
+def get_resources(name: str) -> list[EndpointResource]:
+ """Resources needed to sync `name` — the endpoint itself, preceded by its parent when it fans out."""
+ config = CLERK_ENDPOINTS[name]
+ fan_out = config.fan_out
+
+ if fan_out is None:
+ return [_resource(name, config, config.path, {"limit": config.page_size})]
+
+ parent_config = CLERK_ENDPOINTS[fan_out.parent]
+ child_params: dict[str, Any] = {
+ fan_out.query_param: {"type": "resolve", "resource": fan_out.parent, "field": fan_out.parent_field},
+ "limit": config.page_size,
+ }
+ return [
+ _resource(fan_out.parent, parent_config, parent_config.path, {"limit": parent_config.page_size}),
+ _resource(name, config, f"{config.path}?{fan_out.query_param}={{{fan_out.query_param}}}", child_params),
+ ]
+
+
class ClerkPaginator(BasePaginator):
"""Paginator for Clerk API using offset-based pagination."""
@@ -174,13 +198,15 @@ def _convert_timestamps(item: dict[str, Any]) -> dict[str, Any]:
return item
-# Redeemable invitation links Clerk returns on invitation rows. Anyone who can read the
-# warehouse table could otherwise copy one of these and accept the invitation, so drop them
-# before the row is stored. Values are dotted paths into each endpoint's row shape.
+# Secrets Clerk returns on list rows that would let a reader impersonate the object: redeemable
+# invitation links, and the reusable `token` on each m2m_token that authenticates as its machine.
+# Anyone who can read the warehouse table could otherwise copy one, so drop them before the row
+# is stored. Values are dotted paths into each endpoint's row shape.
SENSITIVE_FIELDS_BY_ENDPOINT: dict[str, tuple[str, ...]] = {
"invitations": ("url",),
"organization_invitations": ("url",),
"waitlist_entries": ("invitation.url",),
+ "m2m_tokens": ("token",),
}
@@ -224,14 +250,58 @@ def validate_credentials(secret_key: str) -> tuple[bool, str | None]:
return False, str(e)
+# Clerk error codes meaning "this account has not switched the feature on". Paired with the
+# statuses Clerk returns them under: 402 carries no body code, so the status alone is the signal.
+_FEATURE_DISABLED_CODES = frozenset({"billing_not_enabled", "feature_not_enabled"})
+
+
+def _is_feature_disabled(response: Optional[Response]) -> bool:
+ if response is None:
+ return False
+ if response.status_code == 402:
+ return True
+ if response.status_code not in (400, 403):
+ return False
+
+ try:
+ body = response.json()
+ except ValueError:
+ return False
+
+ errors = body.get("errors") if isinstance(body, dict) else None
+ if not isinstance(errors, list):
+ return False
+ return any(isinstance(error, dict) and error.get("code") in _FEATURE_DISABLED_CODES for error in errors)
+
+
+def _skip_when_feature_disabled(
+ items: Iterator[Any], endpoint: str, gated_feature: str, logger: FilteringBoundLogger
+) -> Iterator[Any]:
+ try:
+ yield from items
+ except HTTPError as err:
+ if not _is_feature_disabled(err.response):
+ raise
+ logger.warning(
+ f"{gated_feature} is not enabled on this Clerk account, so the {endpoint} table synced no rows. "
+ "Turn it on in your Clerk dashboard, or turn off syncing for this table."
+ )
+
+
def clerk_source(
secret_key: str,
endpoint: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[ClerkResumeConfig],
+ logger: FilteringBoundLogger,
) -> SourceResponse:
+ retired_reason = RETIRED_ENDPOINTS.get(endpoint)
+ if retired_reason is not None:
+ raise ValueError(retired_reason)
+
endpoint_config = CLERK_ENDPOINTS[endpoint]
+ resources = get_resources(endpoint)
config: RESTAPIConfig = {
"client": {
@@ -243,54 +313,65 @@ def clerk_source(
"headers": {
"Content-Type": "application/json",
},
- "paginator": ClerkPaginator(limit=endpoint_config.page_size, data_key=endpoint_config.data_key),
},
"resource_defaults": {
"write_disposition": "replace",
- "endpoint": {
- "params": {
- "limit": endpoint_config.page_size,
- },
- },
},
- "resources": [get_resource(endpoint)],
+ "resources": list(resources),
}
- # Seed the paginator from the saved checkpoint when resuming.
+ # Seed the paginator from the saved checkpoint when resuming. A fan-out endpoint checkpoints
+ # per parent, so its state passes through untouched rather than as a flat offset.
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
resume_config = resumable_source_manager.load_state()
- if resume_config is not None and resume_config.offset > 0:
- initial_paginator_state = {"offset": resume_config.offset}
+ if resume_config is not None:
+ if endpoint_config.fan_out is not None:
+ initial_paginator_state = resume_config.fan_out
+ elif resume_config.offset > 0:
+ initial_paginator_state = {"offset": resume_config.offset}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
# rest_client passes None once the paginator is exhausted; nothing to persist then.
- if state and state.get("offset") is not None:
+ if not state:
+ return
+ if endpoint_config.fan_out is not None:
+ resumable_source_manager.save_state(ClerkResumeConfig(fan_out=state))
+ elif state.get("offset") is not None:
resumable_source_manager.save_state(ClerkResumeConfig(offset=int(state["offset"])))
- resource = rest_api_resource(
+ built = rest_api_resources(
config,
team_id,
job_id,
None,
resume_hook=save_checkpoint,
initial_paginator_state=initial_paginator_state,
- ).add_map(_convert_timestamps)
+ )
+ resource = next(candidate for candidate in built if candidate.name == endpoint).add_map(_convert_timestamps)
sensitive_fields = SENSITIVE_FIELDS_BY_ENDPOINT.get(endpoint)
if sensitive_fields:
resource = resource.add_map(functools.partial(_strip_sensitive_fields, paths=sensitive_fields))
+ gated_feature = endpoint_config.gated_feature
+
+ def items() -> Iterator[Any]:
+ if gated_feature is None:
+ yield from resource
+ return
+ yield from _skip_when_feature_disabled(iter(resource), endpoint, gated_feature, logger)
+
if endpoint_config.partition_key is None:
return SourceResponse(
name=endpoint,
- items=lambda: resource,
+ items=items,
primary_keys=["id"],
)
return SourceResponse(
name=endpoint,
- items=lambda: resource,
+ items=items,
primary_keys=["id"],
partition_count=1,
partition_size=1,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/settings.py
index 97a7e1db72a5..01782d9a20c4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/settings.py
@@ -2,6 +2,20 @@ from dataclasses import dataclass
from typing import Optional
+@dataclass(frozen=True, kw_only=True)
+class ClerkFanOut:
+ """A Clerk list endpoint that only answers when filtered by a parent object's id.
+
+ `/sessions` needs `user_id` (or `client_id`) and `/m2m_tokens` needs `subject`; unfiltered
+ calls are rejected. The filter travels as a query param, and the framework only substitutes
+ resolved params into the path, so the child path carries the placeholder in its query string.
+ """
+
+ parent: str # key in CLERK_ENDPOINTS whose rows drive the fan-out
+ parent_field: str # field on each parent row supplying the filter value
+ query_param: str # query param the child endpoint filters on
+
+
@dataclass
class ClerkEndpointConfig:
name: str
@@ -14,6 +28,11 @@ class ClerkEndpointConfig:
is_wrapped_response: bool = False
# Key holding the row array in a wrapped response — `/m2m_tokens` uses `m2m_tokens`, not `data`.
data_key: str = "data"
+ fan_out: Optional[ClerkFanOut] = None
+ # Names a Clerk feature that instances have to switch on. Clerk answers 402, or 400/403 with a
+ # `*_not_enabled` code, for every account that hasn't. No retry or credential change fixes
+ # that, so the table syncs zero rows and logs this name instead of failing the whole schema.
+ gated_feature: Optional[str] = None
# Note: Clerk API does not support filtering by updated_at, so only full refresh is supported.
@@ -24,8 +43,11 @@ CLERK_ENDPOINTS: dict[str, ClerkEndpointConfig] = {
name="organization_memberships", path="/organization_memberships", is_wrapped_response=True
),
"invitations": ClerkEndpointConfig(name="invitations", path="/invitations"),
- "sessions": ClerkEndpointConfig(name="sessions", path="/sessions"),
- "clients": ClerkEndpointConfig(name="clients", path="/clients"),
+ "sessions": ClerkEndpointConfig(
+ name="sessions",
+ path="/sessions",
+ fan_out=ClerkFanOut(parent="users", parent_field="id", query_param="user_id"),
+ ),
"organization_invitations": ClerkEndpointConfig(
name="organization_invitations", path="/organization_invitations", is_wrapped_response=True
),
@@ -42,9 +64,16 @@ CLERK_ENDPOINTS: dict[str, ClerkEndpointConfig] = {
"waitlist_entries": ClerkEndpointConfig(
name="waitlist_entries", path="/waitlist_entries", is_wrapped_response=True
),
- "allowlist_identifiers": ClerkEndpointConfig(name="allowlist_identifiers", path="/allowlist_identifiers"),
+ "allowlist_identifiers": ClerkEndpointConfig(
+ name="allowlist_identifiers",
+ path="/allowlist_identifiers",
+ gated_feature="Restrictions (the allow-list and block-list)",
+ ),
"blocklist_identifiers": ClerkEndpointConfig(
- name="blocklist_identifiers", path="/blocklist_identifiers", is_wrapped_response=True
+ name="blocklist_identifiers",
+ path="/blocklist_identifiers",
+ is_wrapped_response=True,
+ gated_feature="Restrictions (the allow-list and block-list)",
),
"domains": ClerkEndpointConfig(name="domains", path="/domains", partition_key=None, is_wrapped_response=True),
"saml_connections": ClerkEndpointConfig(
@@ -60,17 +89,41 @@ CLERK_ENDPOINTS: dict[str, ClerkEndpointConfig] = {
# /api_keys and /m2m_tokens cap `limit` at 100 rather than 500.
"api_keys": ClerkEndpointConfig(name="api_keys", path="/api_keys", is_wrapped_response=True),
"m2m_tokens": ClerkEndpointConfig(
- name="m2m_tokens", path="/m2m_tokens", is_wrapped_response=True, data_key="m2m_tokens"
+ name="m2m_tokens",
+ path="/m2m_tokens",
+ is_wrapped_response=True,
+ data_key="m2m_tokens",
+ fan_out=ClerkFanOut(parent="machines", parent_field="id", query_param="subject"),
),
"redirect_urls": ClerkEndpointConfig(name="redirect_urls", path="/redirect_urls"),
"jwt_templates": ClerkEndpointConfig(name="jwt_templates", path="/jwt_templates"),
"email_templates": ClerkEndpointConfig(name="email_templates", path="/templates/email"),
"sms_templates": ClerkEndpointConfig(name="sms_templates", path="/templates/sms"),
"commerce_plans": ClerkEndpointConfig(
- name="commerce_plans", path="/commerce/plans", partition_key=None, is_wrapped_response=True
+ name="commerce_plans",
+ path="/commerce/plans",
+ partition_key=None,
+ is_wrapped_response=True,
+ gated_feature="Billing",
),
"commerce_subscription_items": ClerkEndpointConfig(
- name="commerce_subscription_items", path="/commerce/subscription_items", is_wrapped_response=True
+ name="commerce_subscription_items",
+ path="/commerce/subscription_items",
+ is_wrapped_response=True,
+ gated_feature="Billing",
+ ),
+}
+
+# Tables whose Clerk endpoint no longer exists. Dropping the name from CLERK_ENDPOINTS is what
+# retires the table: schema discovery stops listing it, which disables syncing and leaves any
+# already-imported rows in place. The reason lives here so a job that starts before the next
+# discovery run explains itself rather than raising a KeyError.
+RETIRED_ENDPOINTS: dict[str, str] = {
+ # https://clerk.com/docs/reference/backend-api — GET /v1/clients is marked deprecated and now
+ # answers 410. Clerk offers no replacement listing endpoint.
+ "clients": (
+ "Clerk removed the clients endpoint from its API, so the clients table can't sync any more. "
+ "Turn off syncing for this table."
),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/source.py
index 0f446b07bb59..ee67f2a02add 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/source.py
@@ -14,7 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.cler
clerk_source,
validate_credentials as validate_clerk_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.settings import ENDPOINTS, RETIRED_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
@@ -105,6 +105,10 @@ The secret key starts with `sk_live_`.
return {
"401 Client Error: Unauthorized for url: https://api.clerk.com": "Your Clerk secret key is invalid or has been revoked. Please update the secret key in your Clerk dashboard and reconnect.",
"403 Client Error: Forbidden for url: https://api.clerk.com": "Your Clerk secret key does not have permission to access this endpoint. Please check the key's permissions in your Clerk dashboard.",
+ # Clerk answers 410 for endpoints it has removed. Schema discovery retires the table
+ # within a few hours, so this only covers runs that start in between.
+ "410 Client Error: Gone for url: https://api.clerk.com": "Clerk removed this endpoint from its API, so this table can't sync any more. Turn off syncing for this table.",
+ **{reason: reason for reason in RETIRED_ENDPOINTS.values()},
}
def validate_credentials(
@@ -127,4 +131,5 @@ The secret key starts with `sk_live_`.
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk.py
index e5c11e118d5b..bc2a6d7d8243 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk.py
@@ -7,6 +7,7 @@ import pytest
from unittest.mock import MagicMock, patch
from requests import Request, Response
+from requests.exceptions import HTTPError
from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.clerk import (
ClerkPaginator,
@@ -14,9 +15,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.cler
_convert_timestamps,
_strip_sensitive_fields,
clerk_source,
- get_resource,
+ get_resources,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.settings import (
+ CLERK_ENDPOINTS,
+ RETIRED_ENDPOINTS,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.settings import CLERK_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -168,37 +172,44 @@ def _partial_page(endpoint: str, ids: list[str]) -> Any:
return items
+def _drive(
+ endpoint: str, manager: MagicMock, responses: list[Response], logger: Any = None
+) -> list[tuple[str, dict[str, Any]]]:
+ """Drive ``clerk_source`` against a mocked HTTP session, returning the (url, params)
+ of each request sent. Params are shallow copies — the paginator mutates the underlying
+ Request in-place between pages."""
+ sent: list[tuple[str, dict[str, Any]]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent.append((request.url, dict(request.params)))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ source_response = clerk_source(
+ secret_key="sk_live_test",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ logger=logger if logger is not None else MagicMock(),
+ )
+ list(cast(Iterable[Any], source_response.items()))
+ return sent
+
+
class TestClerkSourceResumeBehavior:
"""End-to-end resume behaviour through the shared ``rest_api_resource`` path."""
def _drive(self, endpoint: str, manager: MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Drive ``clerk_source`` with a mocked HTTP session and return the
- params dict sent with each request (shallow copies — the paginator
- mutates the underlying Request in-place between pages)."""
- sent_params: list[dict[str, Any]] = []
- response_iter = iter(responses)
-
- def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
- sent_params.append(dict(request.params))
- return next(response_iter)
-
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
- ) as MockSession:
- mock_session = MockSession.return_value
- mock_session.headers = {}
- mock_session.prepare_request.side_effect = lambda req: req
- mock_session.send.side_effect = fake_send
-
- source_response = clerk_source(
- secret_key="sk_live_test",
- endpoint=endpoint,
- team_id=123,
- job_id="test_job",
- resumable_source_manager=manager,
- )
- list(cast(Iterable[Any], source_response.items()))
- return sent_params
+ return [params for _url, params in _drive(endpoint, manager, responses)]
@pytest.mark.parametrize("endpoint", [_DIRECT_ARRAY_ENDPOINT, _WRAPPED_ENDPOINT])
def test_fresh_run_saves_offset_after_each_non_terminal_page(self, endpoint: str) -> None:
@@ -262,8 +273,16 @@ class TestClerkSourceResumeBehavior:
assert [p.get("offset") for p in sent_params] == [None]
- def test_resume_config_serialization_round_trip(self) -> None:
- cfg = ClerkResumeConfig(offset=1500)
+ @pytest.mark.parametrize(
+ "cfg",
+ [
+ ClerkResumeConfig(offset=1500),
+ ClerkResumeConfig(
+ fan_out={"completed": ["/sessions?user_id=user_1"], "current": None, "child_state": None}
+ ),
+ ],
+ )
+ def test_resume_config_serialization_round_trip(self, cfg: ClerkResumeConfig) -> None:
as_json = json.dumps(dataclasses.asdict(cfg))
reconstituted = ClerkResumeConfig(**json.loads(as_json))
assert reconstituted == cfg
@@ -273,12 +292,21 @@ class TestClerkEndpoints:
@pytest.mark.parametrize("endpoint", sorted(CLERK_ENDPOINTS))
def test_resource_targets_the_configured_path(self, endpoint: str) -> None:
config = CLERK_ENDPOINTS[endpoint]
- resource = get_resource(endpoint)
+ resources = get_resources(endpoint)
+ resource = next(candidate for candidate in resources if candidate["name"] == endpoint)
endpoint_definition = cast(Endpoint, resource["endpoint"])
assert resource["table_name"] == endpoint
- assert endpoint_definition["path"] == config.path
assert config.path.startswith("/")
+ if config.fan_out is None:
+ assert endpoint_definition["path"] == config.path
+ else:
+ # The parent must be fetched first, and the filter rides in the child's query string.
+ assert [candidate["name"] for candidate in resources] == [config.fan_out.parent, endpoint]
+ assert (
+ endpoint_definition["path"]
+ == f"{config.path}?{config.fan_out.query_param}={{{config.fan_out.query_param}}}"
+ )
# Rows are only found under the wrapper key the endpoint actually uses; the default
# `data` selector silently yields nothing for /m2m_tokens.
assert endpoint_definition.get("data_selector") == (config.data_key if config.is_wrapped_response else None)
@@ -358,6 +386,7 @@ class TestClerkSourceResponse:
team_id=123,
job_id="test_job",
resumable_source_manager=manager,
+ logger=MagicMock(),
)
@pytest.mark.parametrize("endpoint", sorted(CLERK_ENDPOINTS))
@@ -379,7 +408,15 @@ class TestClerkSourceResponse:
def test_rows_are_read_from_the_endpoints_wrapper_key(self) -> None:
manager = MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False
- response = _make_http_response({"m2m_tokens": [{"id": "mt_1", "created_at": 1700000000000}], "total_count": 1})
+ responses = [
+ _make_http_response({"data": [{"id": "mch_1"}], "total_count": 1}),
+ _make_http_response(
+ {
+ "m2m_tokens": [{"id": "mt_1", "created_at": 1700000000000, "token": "mt_secret"}],
+ "total_count": 1,
+ }
+ ),
+ ]
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
@@ -387,7 +424,7 @@ class TestClerkSourceResponse:
mock_session = MockSession.return_value
mock_session.headers = {}
mock_session.prepare_request.side_effect = lambda req: req
- mock_session.send.return_value = response
+ mock_session.send.side_effect = responses
source_response = clerk_source(
secret_key="sk_live_test",
@@ -395,7 +432,118 @@ class TestClerkSourceResponse:
team_id=123,
job_id="test_job",
resumable_source_manager=manager,
+ logger=MagicMock(),
)
pages = list(cast(Iterable[Any], source_response.items()))
+ # The reusable `token` secret must be stripped before the row reaches the warehouse.
assert pages == [[{"id": "mt_1", "created_at": 1700000000}]]
+
+
+class TestClerkFilteredEndpoints:
+ """Clerk rejects `/sessions` and `/m2m_tokens` unless the request carries a parent filter."""
+
+ @pytest.mark.parametrize(
+ ("endpoint", "parent_path", "parent_page", "parent_id", "child_page"),
+ [
+ ("sessions", "/users", [{"id": "user_1"}], "user_1", [{"id": "sess_1"}]),
+ (
+ "m2m_tokens",
+ "/machines",
+ {"data": [{"id": "mch_1"}], "total_count": 1},
+ "mch_1",
+ {"m2m_tokens": [{"id": "mt_1"}], "total_count": 1},
+ ),
+ ],
+ )
+ def test_endpoint_is_filtered_by_its_parent(
+ self,
+ endpoint: str,
+ parent_path: str,
+ parent_page: Any,
+ parent_id: str,
+ child_page: Any,
+ ) -> None:
+ # Unfiltered, Clerk answers 422 (`/sessions`) or 400 (`/m2m_tokens`) and the sync dies.
+ config = CLERK_ENDPOINTS[endpoint]
+ assert config.fan_out is not None
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ sent = _drive(
+ endpoint,
+ manager,
+ [_make_http_response(parent_page), _make_http_response(child_page)],
+ )
+
+ assert [url for url, _params in sent] == [
+ f"https://api.clerk.com/v1{parent_path}",
+ f"https://api.clerk.com/v1{config.path}?{config.fan_out.query_param}={parent_id}",
+ ]
+ # The resolve placeholder must not leak into the query params as well.
+ assert config.fan_out.query_param not in sent[1][1]
+ # Fan-out state is per parent, not a flat offset — a retry must not restart the walk.
+ saved = manager.save_state.call_args.args[0]
+ assert saved.fan_out == {
+ "completed": [f"{config.path}?{config.fan_out.query_param}={parent_id}"],
+ "current": None,
+ "child_state": None,
+ }
+
+
+class TestClerkFeatureGatedEndpoints:
+ def _drive_with_error(self, endpoint: str, error_response: Response, logger: Any) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ _drive(endpoint, manager, [error_response], logger=logger)
+
+ @pytest.mark.parametrize(
+ ("endpoint", "status_code", "body"),
+ [
+ ("allowlist_identifiers", 402, {"errors": [{"code": "payment_required"}]}),
+ ("blocklist_identifiers", 402, {"errors": [{"code": "payment_required"}]}),
+ ("commerce_plans", 400, {"errors": [{"code": "billing_not_enabled"}]}),
+ ("commerce_subscription_items", 400, {"errors": [{"code": "billing_not_enabled"}]}),
+ ("commerce_plans", 403, {"errors": [{"code": "feature_not_enabled"}]}),
+ ],
+ )
+ def test_feature_not_enabled_syncs_no_rows_instead_of_failing(
+ self, endpoint: str, status_code: int, body: dict[str, Any]
+ ) -> None:
+ logger = MagicMock()
+
+ self._drive_with_error(endpoint, _make_http_response(body, status_code=status_code), logger)
+
+ assert CLERK_ENDPOINTS[endpoint].gated_feature in logger.warning.call_args.args[0]
+
+ @pytest.mark.parametrize(
+ ("endpoint", "status_code", "body"),
+ [
+ # A gated endpoint failing for an unrelated reason must still fail the sync.
+ ("commerce_plans", 400, {"errors": [{"code": "invalid_request"}]}),
+ # A table with no feature gate never swallows an error.
+ ("users", 402, {"errors": [{"code": "payment_required"}]}),
+ ],
+ )
+ def test_other_errors_still_fail_the_sync(self, endpoint: str, status_code: int, body: dict[str, Any]) -> None:
+ with pytest.raises(HTTPError):
+ self._drive_with_error(endpoint, _make_http_response(body, status_code=status_code), MagicMock())
+
+
+class TestClerkRetiredEndpoints:
+ @pytest.mark.parametrize("endpoint", sorted(RETIRED_ENDPOINTS))
+ def test_retired_endpoint_is_off_the_catalog_and_explains_itself(self, endpoint: str) -> None:
+ # Discovery drops the table because it left CLERK_ENDPOINTS; a job already in flight has
+ # to say why rather than blow up on a missing key.
+ assert endpoint not in CLERK_ENDPOINTS
+
+ manager = MagicMock(spec=ResumableSourceManager)
+ with pytest.raises(ValueError, match="Turn off syncing for this table"):
+ clerk_source(
+ secret_key="sk_live_test",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ logger=MagicMock(),
+ )