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): support clever API version v3.1 (#113227)

Tom Owerscd5356d42c7c
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.md
index 837f7cf1f4d6..d930545cf3ca 100644
--- a/.agents/skills/warehouse-source-new-version/SKILL.md
+++ b/.agents/skills/warehouse-source-new-version/SKILL.md
@@ -91,6 +91,7 @@ The opposite gap also occurs: a reference rendered from one version-blind OpenAP
- A new version that only widens an accepted enum on a resource the source reads (an extra breakdown/pivot value, a new status) clears the gate — the label is a real divergence and a request input — but it needs no request branch while the source keeps requesting the existing values, and the table that would expose the new value is a separate feature, not part of the bump.
- A version bump often changes **webhook payloads** too — if the source is a `WebhookSource`, check whether webhook-created clients (created at source-setup time, not sync time) also need the version and whether existing webhook subscriptions must be updated.
- Credential-validation paths (`validate_credentials`, permission probes) run at creation time with no row pin; they may use the default/legacy version. Changing them is optional per version bump — verify the vendor accepts the validation calls under the new version before switching them.
+- A vendor can gate a new version per integration ("contact us for access") while it still serves the old one. Flipping the default then makes new sources fail creation for integrators without access, while existing pins are unaffected. Call out that access requirement in the PR, so a reviewer can decide if the default flip waits.
- A passing credential probe is not evidence sync works — the probe hits one endpoint, `get_rows` hits the rest; when they diverge per version, the probe passes while every table 404s.
- Version → header/path maps must cover every supported label — a `.get()` fallthrough silently sends no version header (tracking "latest", the drift this framework prevents). Assert coverage or raise.
- When a vendor dates each endpoint separately and rejects a date an endpoint was not published under, the source label is a baseline, not the header value. An endpoint published after the baseline sends its own published date under that pin, so store the selector per endpoint.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clever/clever.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/clever.py
index d53912595205..afe9ffd37bac 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clever/clever.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/clever.py
@@ -6,9 +6,9 @@ from requests import Request, Response
from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.clever.settings import (
- CLEVER_BASE_URL,
CLEVER_ENDPOINTS,
CLEVER_PAGE_SIZE,
+ clever_base_url,
)
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 (
@@ -84,6 +84,7 @@ class CleverPaginator(BasePaginator):
def clever_source(
bearer_token: str,
+ api_version: str,
endpoint: str,
team_id: int,
job_id: str,
@@ -98,7 +99,7 @@ def clever_source(
rest_config: RESTAPIConfig = {
"client": {
- "base_url": CLEVER_BASE_URL,
+ "base_url": clever_base_url(api_version),
"auth": {"type": "bearer", "token": bearer_token},
"paginator": CleverPaginator(),
# Clever responses carry student, guardian, and staff PII (names, DOBs, contact
@@ -156,10 +157,10 @@ def clever_source(
)
-def validate_credentials(bearer_token: str) -> tuple[bool, str | None]:
+def validate_credentials(bearer_token: str, api_version: str) -> tuple[bool, str | None]:
try:
response = make_tracked_session(redact_values=(bearer_token,)).get(
- f"{CLEVER_BASE_URL}/districts",
+ f"{clever_base_url(api_version)}/districts",
headers={"Authorization": f"Bearer {bearer_token}"},
params={"limit": 1},
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clever/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/settings.py
index e87a4d3400df..c5fc9799cd41 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clever/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/settings.py
@@ -5,7 +5,14 @@ from posthog.dataclasses import frozen
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-CLEVER_BASE_URL = "https://api.clever.com/v3.0"
+CLEVER_API_VERSION_V3_0 = "v3.0"
+CLEVER_API_VERSION_V3_1 = "v3.1"
+
+# Clever selects the API version by the first URL path segment.
+CLEVER_BASE_URLS: dict[str, str] = {
+ CLEVER_API_VERSION_V3_0: "https://api.clever.com/v3.0",
+ CLEVER_API_VERSION_V3_1: "https://api.clever.com/v3.1",
+}
# Clever's documented maximum page size (the default is 100 if omitted); requesting the max
# means fewer round trips for a full district roster sync.
@@ -58,6 +65,14 @@ CLEVER_ENDPOINTS: dict[str, CleverEndpointConfig] = {
"Events": CleverEndpointConfig(name="Events", path="/events", incremental=True, partition_key="created"),
}
+
+def clever_base_url(api_version: str) -> str:
+ try:
+ return CLEVER_BASE_URLS[api_version]
+ except KeyError:
+ raise ValueError(f"Unsupported Clever API version: {api_version}")
+
+
ENDPOINTS = tuple(CLEVER_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clever/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/source.py
index 0e0357b61493..35bec080712b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clever/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/source.py
@@ -13,6 +13,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clever.cle
validate_credentials as validate_clever_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.clever.settings import (
+ CLEVER_API_VERSION_V3_0,
+ CLEVER_API_VERSION_V3_1,
CLEVER_ENDPOINTS,
ENDPOINTS,
INCREMENTAL_FIELDS,
@@ -35,9 +37,9 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class CleverSource(ResumableSource[CleverSourceConfig, CleverResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
- supported_versions = ("v3.0",)
- default_version = "v3.0"
- api_docs_url = "https://dev.clever.com/docs/new-in-api-v3"
+ supported_versions = (CLEVER_API_VERSION_V3_0, CLEVER_API_VERSION_V3_1)
+ default_version = CLEVER_API_VERSION_V3_1
+ api_docs_url = "https://dev.clever.com/docs/api-v31"
@property
def source_type(self) -> ExternalDataSourceType:
@@ -104,7 +106,7 @@ Rostering data beyond districts requires the district's Clever Secure Sync (Clev
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- return validate_clever_credentials(config.bearer_token)
+ return validate_clever_credentials(config.bearer_token, self.resolve_api_version(api_version))
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CleverResumeConfig]:
return ResumableSourceManager[CleverResumeConfig](inputs, CleverResumeConfig)
@@ -118,6 +120,7 @@ Rostering data beyond districts requires the district's Clever Secure Sync (Clev
endpoint_config = CLEVER_ENDPOINTS[inputs.schema_name]
resource = clever_source(
bearer_token=config.bearer_token,
+ api_version=self.resolve_api_version(inputs.api_version),
endpoint=inputs.schema_name,
team_id=inputs.team_id,
job_id=inputs.job_id,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clever/tests/test_clever.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/tests/test_clever.py
index 902c86fcc2cf..6f7f09261ea7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clever/tests/test_clever.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/tests/test_clever.py
@@ -13,6 +13,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clever.cle
clever_source,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.clever.settings import (
+ CLEVER_API_VERSION_V3_0,
+ CLEVER_API_VERSION_V3_1,
+ clever_base_url,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
CLEVER_SESSION_PATCH = (
@@ -134,12 +139,16 @@ class TestCleverSourceResumeBehavior:
responses: list[Response],
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
+ api_version: str = CLEVER_API_VERSION_V3_1,
+ sent_urls: list[str] | None = None,
) -> tuple[MagicMock, list[dict[str, Any]]]:
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 or {}))
+ if sent_urls is not None:
+ sent_urls.append(request.url)
return next(response_iter)
with patch(CLIENT_SESSION_PATCH) as MockSession:
@@ -150,6 +159,7 @@ class TestCleverSourceResumeBehavior:
resource = clever_source(
bearer_token="test-token",
+ api_version=api_version,
endpoint=endpoint,
team_id=123,
job_id="test_job",
@@ -181,6 +191,26 @@ class TestCleverSourceResumeBehavior:
CleverResumeConfig(starting_after="r2"),
]
+ @pytest.mark.parametrize(
+ ("api_version", "expected_url"),
+ [
+ (CLEVER_API_VERSION_V3_0, "https://api.clever.com/v3.0/users"),
+ (CLEVER_API_VERSION_V3_1, "https://api.clever.com/v3.1/users"),
+ ],
+ )
+ def test_requests_target_the_pinned_api_version(self, api_version: str, expected_url: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response({"data": [{"data": {"id": "u1"}}], "links": [_next_link("u1")]}),
+ _make_http_response({"data": [{"data": {"id": "u2"}}], "links": []}),
+ ]
+ sent_urls: list[str] = []
+ self._drive("Users", manager, responses, api_version=api_version, sent_urls=sent_urls)
+
+ assert sent_urls == [expected_url, expected_url]
+
def test_contacts_endpoint_sends_role_filter(self) -> None:
manager = MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False
@@ -266,7 +296,7 @@ class TestValidateCredentials:
self, mock_session: MagicMock, status_code: int, expected_valid: bool
) -> None:
mock_session.return_value.get.return_value = MagicMock(status_code=status_code)
- is_valid, message = validate_credentials("test-token")
+ is_valid, message = validate_credentials("test-token", CLEVER_API_VERSION_V3_1)
assert is_valid is expected_valid
if expected_valid:
assert message is None
@@ -276,12 +306,33 @@ class TestValidateCredentials:
@patch(CLEVER_SESSION_PATCH)
def test_validate_credentials_swallows_exceptions(self, mock_session: MagicMock) -> None:
mock_session.return_value.get.side_effect = Exception("boom")
- is_valid, message = validate_credentials("test-token")
+ is_valid, message = validate_credentials("test-token", CLEVER_API_VERSION_V3_1)
assert is_valid is False
assert message is not None
@patch(CLEVER_SESSION_PATCH)
def test_validate_credentials_redacts_token(self, mock_session: MagicMock) -> None:
mock_session.return_value.get.return_value = MagicMock(status_code=200)
- validate_credentials("super-secret-token")
+ validate_credentials("super-secret-token", CLEVER_API_VERSION_V3_1)
mock_session.assert_called_once_with(redact_values=("super-secret-token",))
+
+ @pytest.mark.parametrize(
+ ("api_version", "expected_url"),
+ [
+ (CLEVER_API_VERSION_V3_0, "https://api.clever.com/v3.0/districts"),
+ (CLEVER_API_VERSION_V3_1, "https://api.clever.com/v3.1/districts"),
+ ],
+ )
+ @patch(CLEVER_SESSION_PATCH)
+ def test_validate_credentials_probes_the_requested_api_version(
+ self, mock_session: MagicMock, api_version: str, expected_url: str
+ ) -> None:
+ mock_session.return_value.get.return_value = MagicMock(status_code=200)
+ validate_credentials("test-token", api_version)
+ assert mock_session.return_value.get.call_args.args[0] == expected_url
+
+
+def test_clever_base_url_rejects_unknown_version() -> None:
+ # Falling back to another version would silently move a pinned source.
+ with pytest.raises(ValueError):
+ clever_base_url("v2.1")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clever/tests/test_clever_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/tests/test_clever_source.py
index 2c5b367f1cef..2347a7e7d082 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clever/tests/test_clever_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/tests/test_clever_source.py
@@ -4,6 +4,10 @@ import requests
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.clever import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.clever.settings import (
+ CLEVER_API_VERSION_V3_0,
+ CLEVER_API_VERSION_V3_1,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.clever.source import CleverSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.clever import CleverSourceConfig
@@ -13,6 +17,7 @@ def _inputs(
schema_name: str = "Districts",
should_use_incremental_field: bool = False,
db_incremental_field_last_value: object = None,
+ api_version: str | None = None,
) -> SourceInputs:
return SourceInputs(
schema_name=schema_name,
@@ -27,6 +32,7 @@ def _inputs(
job_id="job-id",
logger=MagicMock(),
reset_pipeline=False,
+ api_version=api_version,
)
@@ -75,6 +81,40 @@ class TestCleverSource:
assert kwargs["should_use_incremental_field"] is True
assert kwargs["db_incremental_field_last_value"] == "evt-123"
+ def test_new_sources_default_to_v3_1(self) -> None:
+ assert self.source.supported_versions == (CLEVER_API_VERSION_V3_0, CLEVER_API_VERSION_V3_1)
+ assert self.source.default_version == CLEVER_API_VERSION_V3_1
+
+ @parameterized.expand(
+ [
+ ("pinned_v3_0", CLEVER_API_VERSION_V3_0, CLEVER_API_VERSION_V3_0),
+ ("pinned_v3_1", CLEVER_API_VERSION_V3_1, CLEVER_API_VERSION_V3_1),
+ ("unpinned", None, CLEVER_API_VERSION_V3_1),
+ ]
+ )
+ def test_source_for_pipeline_passes_resolved_api_version(
+ self, _name: str, pinned: str | None, expected: str
+ ) -> None:
+ with patch.object(source_module, "clever_source") as mock_source:
+ self.source.source_for_pipeline(self.config, MagicMock(), _inputs(api_version=pinned))
+
+ assert mock_source.call_args.kwargs["api_version"] == expected
+
+ @parameterized.expand(
+ [
+ ("pinned_v3_0", CLEVER_API_VERSION_V3_0, CLEVER_API_VERSION_V3_0),
+ ("pinned_v3_1", CLEVER_API_VERSION_V3_1, CLEVER_API_VERSION_V3_1),
+ ("pre_creation", None, CLEVER_API_VERSION_V3_1),
+ ]
+ )
+ def test_validate_credentials_uses_resolved_api_version(
+ self, _name: str, pinned: str | None, expected: str
+ ) -> None:
+ with patch.object(source_module, "validate_clever_credentials", return_value=(True, None)) as mock_validate:
+ self.source.validate_credentials(self.config, team_id=1, api_version=pinned)
+
+ mock_validate.assert_called_once_with("test-token", expected)
+
def test_source_for_pipeline_drops_watermark_on_full_refresh(self) -> None:
# A stale watermark leaking into a full refresh would silently skip earlier rows.
inputs = _inputs(