: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Clever import source (#84348)
Tom Owers449423507dfc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clever/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/canonical_descriptions.pynew file mode 100644index 000000000000..8e3b9b061fec--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/canonical_descriptions.py@@ -0,0 +1,137 @@+"""Canonical, documentation-sourced descriptions for Clever endpoints and columns.++Sourced from the official Clever Data API v3 reference (https://dev.clever.com/docs). Keyed by+the resource names in `settings.py` `CLEVER_ENDPOINTS`, which match the `ExternalDataSchema.name`+of a synced Clever table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_LINKS_COLUMN = "Related resource links Clever attaches to every object."++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Districts": {+ "description": "A school district that has authorized your Clever application.",+ "docs_url": "https://dev.clever.com/docs/districts",+ "columns": {+ "id": "Globally unique and stable id for the district, assigned by Clever.",+ "name": "District or CMO name.",+ "sis_type": "Student information system this district's data originates from.",+ "nces_id": "Federal NCES identifier for the district, when available.",+ "mdr_number": "MDR number used for external record matching, when available.",+ "launch_date": "Date the district launched with Clever (YYYY-MM-DD).",+ "portal_url": "URL of the district's Clever portal.",+ "state": "Current sync status of the district (running, pending, error, paused, success).",+ "last_sync": "Time of the district's most recent data sync, when available.",+ "links": _LINKS_COLUMN,+ },+ },+ "Schools": {+ "description": "A school within a district.",+ "docs_url": "https://dev.clever.com/docs/schools",+ "columns": {+ "id": "Globally unique and stable id for the school, assigned by Clever.",+ "district": "Id of the district the school belongs to.",+ "name": "School name.",+ "nces_id": "Federal NCES identifier for the school, when available.",+ "school_number": "School identifier assigned by the district or county, when available.",+ "high_grade": "Highest grade level served by the school, when available.",+ "low_grade": "Lowest grade level served by the school, when available.",+ "location": "Street address, city, state, and zip code of the school.",+ "created": "Time the school record was created in Clever.",+ "last_modified": "Time the school record was last modified in Clever.",+ "links": _LINKS_COLUMN,+ },+ },+ "Users": {+ "description": "A student, teacher, staff member, district admin, or contact in the district roster.",+ "docs_url": "https://dev.clever.com/docs/users",+ "columns": {+ "id": "Globally unique and stable id for the user, assigned by Clever.",+ "district": "Id of the user's district.",+ "name": "First, middle, and last name of the user.",+ "email": "Email address on file for the user, when available (not verified by Clever).",+ "roles": "Role-specific data for the user (student, teacher, staff, district_admin, contact).",+ "school": "Id of the user's primary school, for students and teachers.",+ "schools": "Ids of every school the user is associated with.",+ "sis_id": "Identifier for the user in the district's source system of record.",+ "created": "Time the user record was created in Clever.",+ "last_modified": "Time the user record was last modified in Clever.",+ "links": _LINKS_COLUMN,+ },+ },+ "Sections": {+ "description": "A class section: a group of students taught by a teacher for a course.",+ "docs_url": "https://dev.clever.com/docs/sections",+ "columns": {+ "id": "Globally unique and stable id for the section, assigned by Clever.",+ "district": "Id of the section's district.",+ "school": "Id of the section's school.",+ "name": "Section name, usually the course name, teacher's last name, and period.",+ "teacher": "Id of the section's primary teacher.",+ "students": "Ids of every student enrolled in the section.",+ "course": "Id of the course the section belongs to, when available.",+ "term_id": "Id of the term the section runs in, when available.",+ "subject": "Normalized subject of the section (e.g. math, science), when available.",+ "grade": "Grade level of the section, when available.",+ "period": "Bell schedule period the section meets in, when available.",+ "sis_id": "Identifier for the section in the district's source system of record.",+ "created": "Time the section record was created in Clever.",+ "last_modified": "Time the section record was last modified in Clever.",+ "links": _LINKS_COLUMN,+ },+ },+ "Courses": {+ "description": "A course offered by the district, made up of one or more sections.",+ "docs_url": "https://dev.clever.com/docs/courses",+ "columns": {+ "id": "Globally unique and stable id for the course, assigned by Clever.",+ "district": "Id of the course's district.",+ "name": "Course name provided by the district, when available.",+ "number": "Course number provided by the district, when available.",+ "links": _LINKS_COLUMN,+ },+ },+ "Terms": {+ "description": "An academic term (semester, quarter, or school year) defined by the district.",+ "docs_url": "https://dev.clever.com/docs/terms",+ "columns": {+ "id": "Globally unique and stable id for the term, assigned by Clever.",+ "district": "Id of the term's district.",+ "name": "Term name provided by the district, when available.",+ "start_date": "Start date of the term (YYYY-MM-DD), when available.",+ "end_date": "End date of the term (YYYY-MM-DD), when available.",+ "links": _LINKS_COLUMN,+ },+ },+ "Contacts": {+ "description": "A guardian or emergency contact, listed as a user with the `contact` role.",+ "docs_url": "https://dev.clever.com/docs/contacts-guardians",+ "columns": {+ "id": "Globally unique and stable id for the contact, assigned by Clever.",+ "district": "Id of the contact's district.",+ "name": "First, middle, and last name of the contact.",+ "email": "Email address on file for the contact, when available.",+ "phone": "Phone number on file for the contact, when available.",+ "phone_type": "Type of the contact's phone number (e.g. mobile, home), when available.",+ "student_relationships": "Students the contact is related to, with the relationship type.",+ "sis_id": "Identifier for the contact in the district's source system of record.",+ "created": "Time the contact record was created in Clever.",+ "last_modified": "Time the contact record was last modified in Clever.",+ "links": _LINKS_COLUMN,+ },+ },+ "Events": {+ "description": "A created, updated, or deleted change event for a record in the district, from Clever's delta feed. Retained for 30 days.",+ "docs_url": "https://dev.clever.com/docs/events-api",+ "columns": {+ "id": "Unique id of the event itself (distinct from the id of the affected record).",+ "type": "Event type, e.g. users.created, sections.updated, schools.deleted.",+ "created": "Time the event occurred.",+ "data": "The affected record's full object, plus `previous_attributes` for update events.",+ "uri": "Link to this event.",+ },+ },+}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.pynew file mode 100644index 000000000000..d53912595205--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/clever.py@@ -0,0 +1,173 @@+from typing import Any, Optional+from urllib.parse import parse_qs, urlsplit++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,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+++@frozen+class CleverResumeConfig:+ starting_after: str+++class CleverPaginator(BasePaginator):+ """Cursor pagination via Clever's `links` envelope.++ Every Clever list response carries a root-level `links` array; a `rel: "next"` entry's+ `uri` is a relative path whose query string carries the `starting_after` value for the+ next page. There is no absolute URL to follow, so the cursor value is extracted and+ re-injected as a param on the existing request rather than following the URI directly.+ """++ def __init__(self) -> None:+ super().__init__()+ self._starting_after: Optional[str] = None++ def init_request(self, request: Request) -> None:+ if self._starting_after is not None:+ if request.params is None:+ request.params = {}+ request.params["starting_after"] = self._starting_after++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ body = response.json()+ links = body.get("links") if isinstance(body, dict) else None+ next_uri = next((link.get("uri") for link in links if link.get("rel") == "next"), None) if links else None++ if not next_uri:+ self._has_next_page = False+ self._starting_after = None+ return++ starting_after = parse_qs(urlsplit(next_uri).query).get("starting_after", [None])[0]+ if not starting_after:+ # A `next` link without a `starting_after` value is not a shape we can resume+ # from, so stop rather than re-fetch the same page forever.+ self._has_next_page = False+ self._starting_after = None+ return++ self._starting_after = starting_after+ self._has_next_page = True++ def update_request(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ request.params["starting_after"] = self._starting_after++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if self._starting_after is not None and self._has_next_page:+ return {"starting_after": self._starting_after}+ return None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ starting_after = state.get("starting_after")+ if starting_after is not None:+ self._starting_after = str(starting_after)+ self._has_next_page = True+++def clever_source(+ bearer_token: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CleverResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> Resource:+ config = CLEVER_ENDPOINTS[endpoint]++ params: dict[str, Any] = {"limit": CLEVER_PAGE_SIZE}+ params.update(config.extra_params)++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": CLEVER_BASE_URL,+ "auth": {"type": "bearer", "token": bearer_token},+ "paginator": CleverPaginator(),+ # Clever responses carry student, guardian, and staff PII (names, DOBs, contact+ # info, addresses) that the name-based sample scrubbers aren't guaranteed to catch,+ # so keep raw bodies out of HTTP sample capture even where an operator enables it.+ "capture": False,+ },+ "resource_defaults": {+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ },+ "resources": [+ {+ "name": endpoint,+ "table_format": "delta",+ "endpoint": {+ "path": config.path,+ "params": params,+ # Every Clever object is double-wrapped: the list envelope's `data` array+ # holds one `{"data": {...fields...}, "links": [...]}` entry per row.+ "data_selector": "data[*].data",+ },+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"starting_after": resume.starting_after}+ elif should_use_incremental_field and db_incremental_field_last_value:+ # `starting_after` is both the pagination cursor and the cross-sync incremental+ # watermark for the /events delta feed: resuming from the last synced event id+ # picks the feed up where the previous sync left off.+ initial_paginator_state = {"starting_after": str(db_incremental_field_last_value)}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Save AFTER a page is yielded, so a crash mid-sync re-yields the last page (merge+ # dedupes on `id`) instead of skipping it.+ if state and state.get("starting_after"):+ resumable_source_manager.save_state(CleverResumeConfig(starting_after=str(state["starting_after"])))++ return rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def validate_credentials(bearer_token: str) -> tuple[bool, str | None]:+ try:+ response = make_tracked_session(redact_values=(bearer_token,)).get(+ f"{CLEVER_BASE_URL}/districts",+ headers={"Authorization": f"Bearer {bearer_token}"},+ params={"limit": 1},+ )+ except Exception:+ return False, "Could not reach Clever. Check your network connection and try again."++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid or expired bearer token. Check the district bearer token and try again."+ return False, f"Clever returned an unexpected error (status {response.status_code}). Please try again."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.pynew file mode 100644index 000000000000..e87a4d3400df--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/settings.py@@ -0,0 +1,65 @@+from dataclasses import field+from typing import Optional++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++CLEVER_BASE_URL = "https://api.clever.com/v3.0"++# 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.+CLEVER_PAGE_SIZE = 10000++# Clever's event ids are ObjectIDs returned oldest-to-newest by /events, so the id itself+# doubles as a stable incremental cursor for that endpoint (see clever.py).+_EVENTS_INCREMENTAL_FIELD = "id"+++@frozen+class CleverEndpointConfig:+ name: str+ path: str+ extra_params: dict[str, str] = field(default_factory=dict)+ incremental: bool = False+ # Stable creation timestamp to partition on. Left unset for endpoints whose object has no+ # `created`/`last_modified` field (Districts, Courses, Terms), per Clever's data model docs.+ partition_key: Optional[str] = None++ @property+ def incremental_fields(self) -> list[IncrementalField]:+ if not self.incremental:+ return []+ return [+ {+ "label": _EVENTS_INCREMENTAL_FIELD,+ "type": IncrementalFieldType.ObjectID,+ "field": _EVENTS_INCREMENTAL_FIELD,+ "field_type": IncrementalFieldType.ObjectID,+ }+ ]+++CLEVER_ENDPOINTS: dict[str, CleverEndpointConfig] = {+ "Districts": CleverEndpointConfig(name="Districts", path="/districts"),+ "Schools": CleverEndpointConfig(name="Schools", path="/schools", partition_key="created"),+ "Users": CleverEndpointConfig(name="Users", path="/users", partition_key="created"),+ "Sections": CleverEndpointConfig(name="Sections", path="/sections", partition_key="created"),+ "Courses": CleverEndpointConfig(name="Courses", path="/courses"),+ "Terms": CleverEndpointConfig(name="Terms", path="/terms"),+ # Clever has no dedicated contacts/guardians endpoint - they're users with the `contact`+ # role, listed via the documented `role` filter on /users.+ "Contacts": CleverEndpointConfig(+ name="Contacts", path="/users", extra_params={"role": "contact"}, partition_key="created"+ ),+ # Delta feed of created/updated/deleted events across every record type. Clever retains+ # only 30 days of events, so a sync gap longer than that needs a full re-sync of the+ # entity endpoints above to catch up.+ "Events": CleverEndpointConfig(name="Events", path="/events", incremental=True, partition_key="created"),+}++ENDPOINTS = tuple(CLEVER_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CLEVER_ENDPOINTS.items()+}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.pyindex ed45ebddf135..7e2be9a13d46 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@@ -1,30 +1,141 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.clever.clever import (+ CleverResumeConfig,+ clever_source,+ validate_credentials as validate_clever_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.clever.settings import (+ CLEVER_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+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,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.clever import CleverSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CleverSource(SimpleSource[CleverSourceConfig]):+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"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CLEVER+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.clever.com": "Clever authentication failed. Check the district bearer token and try again.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.clever.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CLEVER,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Clever",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["rostering", "k-12", "education", "sis"],+ caption="""Enter the bearer token Clever issued to your app for a district. Find it in your Clever+app dashboard, under that district's **Data Sources** tab in the **API Token** section. See the+[Clever API overview](https://dev.clever.com/docs/api-overview) for details.++Each token is scoped to a single district — connect a separate source per district you want to sync.+Rostering data beyond districts requires the district's Clever Secure Sync (Clever Complete) subscription.""",iconPath="/static/services/clever.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/clever",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="bearer_token",+ label="District bearer token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: CleverSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: CleverSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_clever_credentials(config.bearer_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CleverResumeConfig]:+ return ResumableSourceManager[CleverResumeConfig](inputs, CleverResumeConfig)++ def source_for_pipeline(+ self,+ config: CleverSourceConfig,+ resumable_source_manager: ResumableSourceManager[CleverResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ endpoint_config = CLEVER_ENDPOINTS[inputs.schema_name]+ resource = clever_source(+ bearer_token=config.bearer_token,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )+ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=["id"],+ column_hints=resource.column_hints,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ sort_mode="asc",)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.pynew file mode 100644index 000000000000..902c86fcc2cf--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/tests/test_clever.py@@ -0,0 +1,287 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Request, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.clever.clever import (+ CleverPaginator,+ CleverResumeConfig,+ clever_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++CLEVER_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.clever.clever.make_tracked_session"+)+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+++def _next_link(starting_after: str) -> dict[str, Any]:+ return {"rel": "next", "uri": f"/v3.0/districts?starting_after={starting_after}&limit=10000"}+++class TestCleverPaginator:+ def test_initial_state(self) -> None:+ paginator = CleverPaginator()+ assert paginator._starting_after is None+ assert paginator.has_next_page is True++ def test_update_state_extracts_starting_after_from_next_link(self) -> None:+ paginator = CleverPaginator()+ response = MagicMock()+ response.json.return_value = {+ "data": [{"data": {"id": "d1"}}],+ "links": [{"rel": "self", "uri": "/v3.0/districts"}, _next_link("d1")],+ }+ paginator.update_state(response)+ assert paginator._starting_after == "d1"+ assert paginator.has_next_page is True++ @pytest.mark.parametrize(+ "links",+ [+ [{"rel": "self", "uri": "/v3.0/districts"}], # no `next` link at all+ [], # empty links array+ [{"rel": "next", "uri": "/v3.0/districts?limit=10000"}], # `next` link with no cursor value+ ],+ )+ def test_update_state_stops_when_no_resumable_next_link(self, links: list[dict[str, Any]]) -> None:+ paginator = CleverPaginator()+ response = MagicMock()+ response.json.return_value = {"data": [{"data": {"id": "d1"}}], "links": links}+ paginator.update_state(response)+ assert paginator._starting_after is None+ assert paginator.has_next_page is False++ def test_update_state_missing_links_key(self) -> None:+ paginator = CleverPaginator()+ response = MagicMock()+ response.json.return_value = {"data": [{"data": {"id": "d1"}}]}+ paginator.update_state(response)+ assert paginator.has_next_page is False++ @pytest.mark.parametrize(+ ("label", "seeded_starting_after"),+ [+ ("fresh", None),+ ("resumed", "cursor-2000"),+ ],+ )+ def test_init_request_honours_seeded_starting_after(self, label: str, seeded_starting_after: str | None) -> None:+ paginator = CleverPaginator()+ if seeded_starting_after is not None:+ paginator.set_resume_state({"starting_after": seeded_starting_after})++ request = Request(method="GET", url="https://api.clever.com/v3.0/districts")+ paginator.init_request(request)++ if seeded_starting_after is None:+ assert request.params is None or "starting_after" not in request.params+ else:+ assert request.params["starting_after"] == seeded_starting_after++ def test_get_resume_state_returns_state_when_next_page(self) -> None:+ paginator = CleverPaginator()+ response = MagicMock()+ response.json.return_value = {"data": [], "links": [_next_link("cursor-42")]}+ paginator.update_state(response)++ assert paginator.get_resume_state() == {"starting_after": "cursor-42"}++ def test_get_resume_state_returns_none_on_terminal_page(self) -> None:+ paginator = CleverPaginator()+ response = MagicMock()+ response.json.return_value = {"data": [], "links": []}+ paginator.update_state(response)++ assert paginator.get_resume_state() is None++ def test_set_resume_state_round_trip(self) -> None:+ paginator = CleverPaginator()+ paginator.set_resume_state({"starting_after": "cursor-99"})++ assert paginator._starting_after == "cursor-99"+ assert paginator.has_next_page is True+ assert paginator.get_resume_state() == {"starting_after": "cursor-99"}++ def test_set_resume_state_ignores_missing_key(self) -> None:+ paginator = CleverPaginator()+ paginator.set_resume_state({})++ assert paginator._starting_after is None+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++class TestCleverSourceResumeBehavior:+ """End-to-end resume/incremental behaviour of ``clever_source`` via ``rest_api_resource``."""++ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = 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 {}))+ return next(response_iter)++ with patch(CLIENT_SESSION_PATCH) 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++ resource = clever_source(+ bearer_token="test-token",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ list(cast(Iterable[Any], resource))+ return mock_session, sent_params++ @pytest.mark.parametrize("endpoint", ["Districts", "Schools", "Users", "Sections", "Courses", "Terms"])+ def test_fresh_full_refresh_run_saves_cursor_after_each_non_terminal_page(self, endpoint: str) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"data": [{"data": {"id": "r1"}}], "links": [_next_link("r1")]}),+ _make_http_response({"data": [{"data": {"id": "r2"}}], "links": [_next_link("r2")]}),+ _make_http_response({"data": [{"data": {"id": "r3"}}], "links": []}),+ ]+ _, sent_params = self._drive(endpoint, manager, responses)++ starting_afters = [p.get("starting_after") for p in sent_params]+ assert starting_afters == [None, "r1", "r2"]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [+ CleverResumeConfig(starting_after="r1"),+ CleverResumeConfig(starting_after="r2"),+ ]++ def test_contacts_endpoint_sends_role_filter(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"data": [{"data": {"id": "c1"}}], "links": []})]+ _, sent_params = self._drive("Contacts", manager, responses)++ assert sent_params[0]["role"] == "contact"++ def test_resume_seeds_paginator_with_saved_cursor(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = CleverResumeConfig(starting_after="cursor-resumed")++ responses = [_make_http_response({"data": [{"data": {"id": "r4"}}], "links": []})]+ _, sent_params = self._drive("Districts", manager, responses)++ assert sent_params[0]["starting_after"] == "cursor-resumed"+ manager.load_state.assert_called_once()++ def test_incremental_seeds_from_db_last_value_when_no_saved_state(self) -> None:+ """Events has no mid-run resume state (fresh run), but a prior sync's watermark+ should seed `starting_after` so the delta feed continues from where it left off."""+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"data": [{"data": {"id": "evt-9"}}], "links": []})]+ _, sent_params = self._drive(+ "Events",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value="evt-5",+ )++ assert sent_params[0]["starting_after"] == "evt-5"++ def test_full_refresh_endpoint_ignores_db_last_value(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"data": [{"data": {"id": "d1"}}], "links": []})]+ _, sent_params = self._drive(+ "Districts",+ manager,+ responses,+ should_use_incremental_field=False,+ db_incremental_field_last_value="should-be-unused",+ )++ assert "starting_after" not in sent_params[0]++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"data": [{"data": {"id": "only"}}], "links": []})]+ self._drive("Districts", manager, responses)++ manager.save_state.assert_not_called()++ def test_does_not_load_state_when_cannot_resume(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"data": [{"data": {"id": "a"}}], "links": []})]+ self._drive("Districts", manager, responses)++ manager.load_state.assert_not_called()+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected_valid"),+ [+ (200, True),+ (401, False),+ (500, False),+ ],+ )+ @patch(CLEVER_SESSION_PATCH)+ def test_validate_credentials_status_mapping(+ 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")+ assert is_valid is expected_valid+ if expected_valid:+ assert message is None+ else:+ assert message is not None++ @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")+ 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")+ mock_session.assert_called_once_with(redact_values=("super-secret-token",))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.pynew file mode 100644index 000000000000..cbddc221019f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clever/tests/test_clever_source.py@@ -0,0 +1,169 @@+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++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.clever import CleverResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.clever.settings import ENDPOINTS+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+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _inputs(+ schema_name: str = "Districts",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: object = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-id",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestCleverSource:+ def setup_method(self) -> None:+ self.source = CleverSource()+ self.config = CleverSourceConfig(bearer_token="test-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CLEVER++ def test_no_unreleased_source_flag(self) -> None:+ # A finished source ships visible; `unreleasedSource` hides it from every user.+ assert self.source.get_source_config.unreleasedSource is not True++ def test_source_config_fields(self) -> None:+ fields = self.source.get_source_config.fields+ by_name = {field.name: field for field in fields}++ bearer_token = by_name["bearer_token"]+ assert isinstance(bearer_token, SourceFieldInputConfig)+ assert bearer_token.required is True+ assert bearer_token.secret is True++ def test_get_schemas_covers_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @parameterized.expand(+ [+ # Clever's entity endpoints have no server-side timestamp filter: full refresh only.+ ("Districts", False, False),+ ("Schools", False, False),+ ("Users", False, False),+ ("Sections", False, False),+ ("Courses", False, False),+ ("Terms", False, False),+ ("Contacts", False, False),+ # /events is a real delta feed with a stable id cursor.+ ("Events", True, True),+ ]+ )+ def test_get_schemas_sync_modes(self, endpoint: str, supports_incremental: bool, supports_append: bool) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, team_id=1) if s.name == endpoint)+ assert schema.supports_incremental == supports_incremental+ assert schema.supports_append == supports_append++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["Districts", "Schools"])+ assert {schema.name for schema in schemas} == {"Districts", "Schools"}++ @parameterized.expand([("valid", True, None, True), ("invalid", False, "bad token", False)])+ def test_validate_credentials(+ self, _name: str, probe_valid: bool, probe_message: str | None, expected_valid: bool+ ) -> None:+ with patch.object(source_module, "validate_clever_credentials", return_value=(probe_valid, probe_message)):+ valid, error = self.source.validate_credentials(self.config, team_id=1)++ assert valid == expected_valid+ assert error == probe_message++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_inputs())+ assert manager._data_class is CleverResumeConfig++ def test_source_for_pipeline_passes_config_and_incremental_state(self) -> None:+ inputs = _inputs(+ schema_name="Events",+ should_use_incremental_field=True,+ db_incremental_field_last_value="evt-123",+ )+ manager = MagicMock()+ with patch.object(source_module, "clever_source") as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["bearer_token"] == "test-token"+ assert kwargs["endpoint"] == "Events"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "evt-123"++ 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(+ schema_name="Events",+ should_use_incremental_field=False,+ db_incremental_field_last_value="evt-123",+ )+ with patch.object(source_module, "clever_source") as mock_source:+ self.source.source_for_pipeline(self.config, MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ @parameterized.expand(+ [+ ("Districts", None),+ ("Schools", "created"),+ ("Users", "created"),+ ("Sections", "created"),+ ("Courses", None),+ ("Terms", None),+ ("Contacts", "created"),+ ("Events", "created"),+ ]+ )+ def test_source_for_pipeline_partitions_on_the_stable_created_field(+ self, endpoint: str, expected_partition_key: str | None+ ) -> None:+ with patch.object(source_module, "clever_source") as mock_source:+ mock_source.return_value.name = endpoint+ mock_source.return_value.column_hints = None+ response = self.source.source_for_pipeline(self.config, MagicMock(), _inputs(schema_name=endpoint))++ if expected_partition_key is None:+ assert response.partition_keys is None+ assert response.partition_mode is None+ else:+ assert response.partition_keys == [expected_partition_key]+ assert response.partition_mode == "datetime"++ def test_non_retryable_errors_match_requests_error_format(self) -> None:+ # The pipeline disables a source by substring-matching these keys against the raised+ # error; they must match the message `requests.raise_for_status` actually produces.+ response = MagicMock(spec=requests.Response)+ response.status_code = 401+ response.reason = "Unauthorized"+ response.url = "https://api.clever.com/v3.0/districts?limit=10000"+ error = requests.HTTPError(f"401 Client Error: Unauthorized for url: {response.url}", response=response)++ assert any(key in str(error) for key in self.source.get_non_retryable_errors())++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.pyindex bb0bccb54e04..9c3e1a833622 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py@@ -298,6 +298,7 @@ def create_resources(allowed_hosts=client_config.get("allowed_hosts"),allow_redirects=client_config.get("allow_redirects", True),request_timeout=client_config.get("request_timeout"),+ capture=client_config.get("capture", True),)hooks = create_response_hooks(endpoint_config.get("response_actions"), resource_name=resource_name)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.pyindex 12eefdc3bb51..31e214f9dec9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py@@ -310,6 +310,7 @@ class RESTClient:allowed_hosts: Optional[list[str]] = None,allow_redirects: bool = True,request_timeout: Optional[float | tuple[float, float]] = None,+ capture: bool = True,) -> None:self.base_url = base_url or ""self.headers = headers or {}@@ -355,7 +356,14 @@ class RESTClient:# `RESTClient` participates in HTTP logging, metrics, and sample# capture. Callers can pass a pre-built `Session` for tests or# specialized auth (it should still be a tracked one in prod).- self.session = session or make_tracked_session(redact_values=self._redact_values)+ #+ # `capture` is only forwarded when it opts out of the default, so the call keeps+ # matching the exact `assert_called_once_with(redact_values=...)` many sources'+ # existing tests already make against `make_tracked_session`.+ session_kwargs: dict[str, Any] = {"redact_values": self._redact_values}+ if not capture:+ session_kwargs["capture"] = capture+ self.session = session or make_tracked_session(**session_kwargs)if self.headers:self.session.headers.update(self.headers)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.pyindex 0f534bc4014d..a1d7513388ba 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py@@ -224,6 +224,12 @@ class ClientConfig(TypedDict, total=False):# source pointed at a customer-controlled host that stalls holds an import worker forever.# A single float applies to both connect and read; a tuple sets them separately.request_timeout: Optional[float | tuple[float, float]]+ # When False, this client's default tracked session is built with HTTP sample capture+ # disabled — for endpoints whose bodies carry sensitive PII the name-based sample scrubbers+ # aren't guaranteed to catch (e.g. student/HR records). Requests are still metered and+ # logged. Left unset, capture follows the operator-configured sample rules as normal. No+ # effect when a pre-built `session` is supplied instead.+ capture: boolclass IncrementalArgs(TypedDict, total=False):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clever.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clever.pyindex ae00bc72f995..149522c20dab 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clever.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clever.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass CleverSourceConfig(config.Config):- pass+ bearer_token: str