: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): implement uservoice import source (#71186)
Tom Owers7f99aeefec0e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 7a61fb627e36..794864f84dd9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -515,6 +515,7 @@ the row lists both.| unstructured | HTTP | requests | ✅ || upstash | HTTP | requests | ✅ || uptimerobot | HTTP | requests | ✅ |+| uservoice | HTTP | requests | ✅ || vantage | HTTP | requests | ✅ || vapi | HTTP | requests | ✅ || vellum | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 14fbbc629467..3f6b82737a89 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -4556,7 +4556,8 @@ class UsersnapSourceConfig(config.Config):@config.configclass UservoiceSourceConfig(config.Config):- pass+ subdomain: str+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/canonical_descriptions.pynew file mode 100644index 000000000000..39a228865ebc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/canonical_descriptions.py@@ -0,0 +1,119 @@+"""Canonical, documentation-sourced descriptions for UserVoice Admin API v2 endpoints and columns.++Sourced from the official UserVoice Admin API v2 reference (https://developer.uservoice.com/docs/api/v2/reference/).+Keyed by the resource names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name`+of a synced UserVoice table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://developer.uservoice.com/docs/api/v2/reference/"++# Fields shared by most UserVoice objects; merged into each entry so we don't repeat them.+_COMMON_COLUMNS = {+ "id": "Unique identifier for the object.",+ "created_at": "Time at which the object was created (ISO 8601).",+ "updated_at": "Time at which the object was last updated (ISO 8601).",+ "links": "Related-resource identifiers for this object (associations UserVoice exposes for side-loading).",+}+++def _columns(**overrides: str) -> dict[str, str]:+ return {**_COMMON_COLUMNS, **overrides}+++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "suggestions": {+ "description": "A feedback idea submitted to a forum, carrying its vote and supporter counts and current status.",+ "docs_url": _DOCS_URL,+ "columns": _columns(+ title="Title of the suggestion.",+ formatted_text="Body text of the suggestion.",+ state="Lifecycle state of the suggestion (e.g. published, closed).",+ vote_count="Number of votes the suggestion has received.",+ subscriber_count="Number of users subscribed to updates on the suggestion.",+ comments_count="Number of comments on the suggestion.",+ category_name="Name of the category the suggestion belongs to.",+ closed_at="Time at which the suggestion was closed, if any.",+ ),+ },+ "forums": {+ "description": "A feedback forum that groups suggestions, optionally scoped to a product or audience.",+ "docs_url": _DOCS_URL,+ "columns": _columns(+ name="Name of the forum.",+ suggestions_count="Number of suggestions in the forum.",+ private="Whether the forum is private.",+ welcome_message="Welcome message shown on the forum.",+ ),+ },+ "users": {+ "description": "An end user (contact) who submits, votes on, or comments on feedback.",+ "docs_url": _DOCS_URL,+ "columns": _columns(+ name="Display name of the user.",+ email="Email address of the user.",+ karma_score="Contribution/karma score for the user.",+ last_seen_at="Time the user was last active.",+ ),+ },+ "comments": {+ "description": "A comment left by a user on a suggestion.",+ "docs_url": _DOCS_URL,+ "columns": _columns(+ formatted_text="Body text of the comment.",+ votes="Number of votes on the comment.",+ ),+ },+ "notes": {+ "description": "An internal admin note attached to a user or contact record.",+ "docs_url": _DOCS_URL,+ "columns": _columns(+ text="Body text of the note.",+ ),+ },+ "nps_ratings": {+ "description": "A Net Promoter Score rating submitted by a user, with the optional follow-up comment.",+ "docs_url": _DOCS_URL,+ "columns": _columns(+ rating="The 0–10 NPS rating value.",+ comment="Optional free-text comment left with the rating.",+ rated_at="Time at which the rating was submitted.",+ ),+ },+ "tickets": {+ "description": "A helpdesk support ticket. Only present on accounts with the Helpdesk feature enabled.",+ "docs_url": _DOCS_URL,+ "columns": _columns(+ subject="Subject line of the ticket.",+ state="Current state of the ticket (e.g. open, closed).",+ priority="Priority assigned to the ticket.",+ assignee_name="Name of the admin the ticket is assigned to.",+ ),+ },+ "ticket_messages": {+ "description": "An individual message within a helpdesk ticket thread. Requires the Helpdesk feature.",+ "docs_url": _DOCS_URL,+ "columns": _columns(+ body="Body text of the message.",+ direction="Whether the message was inbound (from the user) or outbound (from an admin).",+ ),+ },+ "suggestion_statuses": {+ "description": "A configurable status label that can be applied to suggestions (e.g. planned, started, completed).",+ "docs_url": _DOCS_URL,+ "columns": _columns(+ name="Name of the status.",+ hex_color="Display color for the status.",+ ),+ },+ "labels": {+ "description": "A label used to tag and organize suggestions.",+ "docs_url": _DOCS_URL,+ "columns": _columns(+ name="Name of the label.",+ ),+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/settings.pynew file mode 100644index 000000000000..06e61e1cb15d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/settings.py@@ -0,0 +1,121 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# UserVoice caps `per_page` at 100 on its Admin API v2 list actions (default 20). Always request the+# max to minimise round trips.+PER_PAGE = 100+++def _updated_at_incremental_fields() -> list[IncrementalField]:+ # UserVoice's only server-side time filter is `updated_after`, which keys off `updated_at`.+ # Advertising just `updated_at` keeps the user's chosen cursor aligned with what the API filters on.+ return [+ {+ "label": "updated_at",+ "type": IncrementalFieldType.DateTime,+ "field": "updated_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+++@dataclass+class UservoiceEndpointConfig:+ name: str+ # Path under /api/v2/admin, e.g. "/suggestions".+ path: str+ # Root key of the list in the JSON response. UserVoice wraps each list under its plural resource+ # name (e.g. {"suggestions": [...], "pagination": {...}}), which equals `path` minus the slash.+ response_key: str+ # UserVoice documents `updated_after` (filters by `updated_at`) on every GET list action. We only+ # turn it on for the mutable, high-volume resources; the small config-like tables sync full refresh.+ supports_incremental: bool+ # Stable creation-time field to partition by. Every UserVoice object carries `created_at`.+ partition_key: Optional[str] = "created_at"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+++# Endpoint catalog for the UserVoice Admin API v2. The helpdesk resources (tickets, ticket_messages)+# only return data on accounts with the Helpdesk feature enabled; users who don't have it simply leave+# those tables deselected.+USERVOICE_ENDPOINTS: dict[str, UservoiceEndpointConfig] = {+ "suggestions": UservoiceEndpointConfig(+ name="suggestions",+ path="/suggestions",+ response_key="suggestions",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "forums": UservoiceEndpointConfig(+ name="forums",+ path="/forums",+ response_key="forums",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "users": UservoiceEndpointConfig(+ name="users",+ path="/users",+ response_key="users",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "comments": UservoiceEndpointConfig(+ name="comments",+ path="/comments",+ response_key="comments",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "notes": UservoiceEndpointConfig(+ name="notes",+ path="/notes",+ response_key="notes",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "nps_ratings": UservoiceEndpointConfig(+ name="nps_ratings",+ path="/nps_ratings",+ response_key="nps_ratings",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "tickets": UservoiceEndpointConfig(+ name="tickets",+ path="/tickets",+ response_key="tickets",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "ticket_messages": UservoiceEndpointConfig(+ name="ticket_messages",+ path="/ticket_messages",+ response_key="ticket_messages",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ # Small, config-like reference tables — cheap to pull in full every run, so no incremental filter.+ "suggestion_statuses": UservoiceEndpointConfig(+ name="suggestion_statuses",+ path="/suggestion_statuses",+ response_key="suggestion_statuses",+ supports_incremental=False,+ ),+ "labels": UservoiceEndpointConfig(+ name="labels",+ path="/labels",+ response_key="labels",+ supports_incremental=False,+ ),+}++ENDPOINTS = tuple(USERVOICE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in USERVOICE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/source.pyindex fdc4480c06a1..ece322faa81f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/source.py@@ -1,30 +1,159 @@-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.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import UservoiceSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ USERVOICE_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.uservoice import (+ UservoiceResumeConfig,+ uservoice_source,+ validate_credentials as validate_uservoice_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class UservoiceSource(SimpleSource[UservoiceSourceConfig]):+class UservoiceSource(ResumableSource[UservoiceSourceConfig, UservoiceResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.USERVOICE+ @property+ def connection_host_fields(self) -> list[str]:+ # The token is sent to `<subdomain>.uservoice.com`, so changing the subdomain must re-require it.+ return ["subdomain"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.USERVOICE,- category=DataWarehouseSourceCategory.PRODUCTIVITY,- label="Uservoice",+ category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,+ label="UserVoice",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your UserVoice account subdomain and API access token to pull your UserVoice data into the PostHog Data warehouse.++Create a trusted API client under **Settings → Channels → Add API Client** in your UserVoice Admin Console, then generate an access token to use here. The token has admin-level read access to your account's feedback data.""",iconPath="/static/services/uservoice.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/uservoice",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="subdomain",+ label="Account subdomain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="yourcompany",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # Retrying can never fix a credential/permission problem, so fail the sync. The base host+ # is per-account, so match the stable status text rather than a fixed URL.+ "401 Client Error: Unauthorized": "Your UserVoice API token is invalid or has been revoked. Generate a new token in your UserVoice Admin Console, then reconnect.",+ "403 Client Error: Forbidden": "Your UserVoice API token is missing the permissions needed to sync this data. Check the API client's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: UservoiceSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = USERVOICE_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: UservoiceSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ ok, status_code = validate_uservoice_credentials(config.subdomain, config.api_key)+ except ValueError as e:+ return False, str(e)++ if ok:+ return True, None+ if status_code == 401:+ return False, "Invalid UserVoice API token"+ return False, "Could not connect to UserVoice with the provided subdomain and API token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[UservoiceResumeConfig]:+ return ResumableSourceManager[UservoiceResumeConfig](inputs, UservoiceResumeConfig)++ def source_for_pipeline(+ self,+ config: UservoiceSourceConfig,+ resumable_source_manager: ResumableSourceManager[UservoiceResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return uservoice_source(+ subdomain=config.subdomain,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ 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,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/tests/test_uservoice.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/tests/test_uservoice.pynew file mode 100644index 000000000000..b849ea70dc42--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/tests/test_uservoice.py@@ -0,0 +1,336 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice import uservoice+from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.settings import PER_PAGE+from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.uservoice import (+ UservoiceResumeConfig,+ _build_initial_params,+ _build_url,+ _format_updated_after,+ _next_page,+ get_rows,+ normalize_subdomain,+ uservoice_source,+)+++class TestNormalizeSubdomain:+ @parameterized.expand(+ [+ ("bare", "acme", "acme"),+ ("full_host", "acme.uservoice.com", "acme"),+ ("https_url", "https://acme.uservoice.com", "acme"),+ ("trailing_slash", "acme.uservoice.com/", "acme"),+ ("with_hyphen", "acme-corp", "acme-corp"),+ ("whitespace", " acme ", "acme"),+ ]+ )+ def test_valid_subdomains(self, _name: str, value: str, expected: str) -> None:+ assert normalize_subdomain(value) == expected++ @parameterized.expand(+ [+ ("path_injection", "acme/../evil"),+ ("host_injection", "acme.evil.com"),+ ("userinfo_injection", "[email protected]"),+ ("empty", ""),+ ("space_inside", "ac me"),+ ("trailing_hyphen", "acme-"),+ ]+ )+ def test_invalid_subdomains_raise(self, _name: str, value: str) -> None:+ with pytest.raises(ValueError):+ normalize_subdomain(value)+++class TestFormatUpdatedAfter:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ result = _format_updated_after(value)+ assert result == expected+ assert "+00:00" not in result+++class TestBuildInitialParams:+ def test_incremental_endpoint_with_value_adds_updated_after(self) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.settings import (+ USERVOICE_ENDPOINTS,+ )++ params = _build_initial_params(+ USERVOICE_ENDPOINTS["suggestions"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ assert params == {"per_page": PER_PAGE, "updated_after": "2026-03-04T02:58:14Z"}++ def test_incremental_endpoint_without_value_omits_updated_after(self) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.settings import (+ USERVOICE_ENDPOINTS,+ )++ params = _build_initial_params(+ USERVOICE_ENDPOINTS["suggestions"], should_use_incremental_field=True, db_incremental_field_last_value=None+ )+ assert params == {"per_page": PER_PAGE}++ def test_full_refresh_endpoint_never_filters(self) -> None:+ # labels has no server-side `updated_after`; a cursor value must not leak into the request.+ from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.settings import (+ USERVOICE_ENDPOINTS,+ )++ params = _build_initial_params(+ USERVOICE_ENDPOINTS["labels"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ assert params == {"per_page": PER_PAGE}+++class TestBuildUrl:+ def test_no_params(self) -> None:+ base = "https://acme.uservoice.com/api/v2/admin"+ assert _build_url(base, "/suggestions", {}) == f"{base}/suggestions"++ def test_encodes_params(self) -> None:+ base = "https://acme.uservoice.com/api/v2/admin"+ url = _build_url(base, "/suggestions", {"page": 2, "updated_after": "2026-03-04T02:58:14Z"})+ assert url == f"{base}/suggestions?page=2&updated_after=2026-03-04T02%3A58%3A14Z"+++class TestNextPage:+ def test_cursor_takes_priority(self) -> None:+ # A present cursor is followed even when page metadata would say "last page".+ result = _next_page({"cursor": "abc", "page": 3, "total_pages": 3}, current_page=3, item_count=100)+ assert result is not None+ assert result.cursor == "abc"+ assert result.page is None++ @parameterized.expand(+ [+ ("more_pages", {"page": 1, "total_pages": 3}, 1, 100, 2),+ ("current_page_alias", {"current_page": 1, "total_pages": 2}, 1, 100, 2),+ ]+ )+ def test_page_fallback_advances(+ self, _name: str, pagination: dict, current_page: int, item_count: int, expected_page: int+ ) -> None:+ result = _next_page(pagination, current_page, item_count)+ assert result is not None+ assert result.cursor is None+ assert result.page == expected_page++ @parameterized.expand(+ [+ ("last_page", {"page": 3, "total_pages": 3}, 3, 50),+ ("missing_meta_partial_page", {}, 1, 5),+ ]+ )+ def test_terminates(self, _name: str, pagination: dict, current_page: int, item_count: int) -> None:+ assert _next_page(pagination, current_page, item_count) is None++ def test_missing_meta_full_page_keeps_going(self) -> None:+ result = _next_page({}, current_page=1, item_count=PER_PAGE)+ assert result is not None+ assert result.page == 2+++class _FakeResumableManager:+ def __init__(self, state: UservoiceResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[UservoiceResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> UservoiceResumeConfig | None:+ return self._state++ def save_state(self, data: UservoiceResumeConfig) -> None:+ self.saved.append(data)+++def _patch_fetch(monkeypatch: Any, pages: dict[str, Any]) -> list[str]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ fetched.append(url)+ return pages[url]++ monkeypatch.setattr(uservoice, "_fetch_page", fake_fetch)+ monkeypatch.setattr(uservoice, "make_tracked_session", lambda *a, **k: MagicMock())+ return fetched+++def _collect(monkeypatch: Any, manager: _FakeResumableManager, **kwargs: Any) -> list[dict]:+ rows: list[dict] = []+ for batch in get_rows(+ subdomain="acme",+ api_key="token",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows+++class TestGetRows:+ _BASE = "https://acme.uservoice.com/api/v2/admin"++ def test_paginates_by_page_number(self, monkeypatch: Any) -> None:+ pages = {+ f"{self._BASE}/suggestions?per_page={PER_PAGE}": {+ "suggestions": [{"id": 1}, {"id": 2}],+ "pagination": {"page": 1, "total_pages": 2},+ },+ f"{self._BASE}/suggestions?per_page={PER_PAGE}&page=2": {+ "suggestions": [{"id": 3}],+ "pagination": {"page": 2, "total_pages": 2},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="suggestions")++ assert [r["id"] for r in rows] == [1, 2, 3]+ assert fetched == list(pages)++ def test_paginates_by_cursor(self, monkeypatch: Any) -> None:+ pages = {+ f"{self._BASE}/suggestions?per_page={PER_PAGE}": {+ "suggestions": [{"id": 1}],+ "pagination": {"cursor": "CUR2"},+ },+ f"{self._BASE}/suggestions?per_page={PER_PAGE}&cursor=CUR2": {+ "suggestions": [{"id": 2}],+ "pagination": {},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="suggestions")++ assert [r["id"] for r in rows] == [1, 2]+ assert fetched == list(pages)++ def test_stops_on_non_advancing_cursor(self, monkeypatch: Any) -> None:+ # A cursor that repeats itself must not loop forever.+ pages = {+ f"{self._BASE}/suggestions?per_page={PER_PAGE}": {+ "suggestions": [{"id": 1}],+ "pagination": {"cursor": "SAME"},+ },+ f"{self._BASE}/suggestions?per_page={PER_PAGE}&cursor=SAME": {+ "suggestions": [{"id": 2}],+ "pagination": {"cursor": "SAME"},+ },+ }+ _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="suggestions")++ assert [r["id"] for r in rows] == [1, 2]++ def test_saves_resume_state_after_each_page_only_while_more_remain(self, monkeypatch: Any) -> None:+ pages = {+ f"{self._BASE}/suggestions?per_page={PER_PAGE}": {+ "suggestions": [{"id": 1}],+ "pagination": {"page": 1, "total_pages": 2},+ },+ f"{self._BASE}/suggestions?per_page={PER_PAGE}&page=2": {+ "suggestions": [{"id": 2}],+ "pagination": {"page": 2, "total_pages": 2},+ },+ }+ _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ _collect(monkeypatch, manager, endpoint="suggestions")++ assert manager.saved == [UservoiceResumeConfig(cursor=None, page=2)]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ pages = {+ f"{self._BASE}/suggestions?per_page={PER_PAGE}&page=2": {+ "suggestions": [{"id": 2}],+ "pagination": {"page": 2, "total_pages": 2},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(UservoiceResumeConfig(page=2)), endpoint="suggestions")++ assert [r["id"] for r in rows] == [2]+ assert fetched == [f"{self._BASE}/suggestions?per_page={PER_PAGE}&page=2"]++ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ pages = {+ f"{self._BASE}/suggestions?per_page={PER_PAGE}&cursor=CUR9": {+ "suggestions": [{"id": 9}],+ "pagination": {},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(+ monkeypatch, _FakeResumableManager(UservoiceResumeConfig(cursor="CUR9")), endpoint="suggestions"+ )++ assert [r["id"] for r in rows] == [9]+ assert fetched == [f"{self._BASE}/suggestions?per_page={PER_PAGE}&cursor=CUR9"]++ def test_incremental_filter_added_to_request(self, monkeypatch: Any) -> None:+ url = f"{self._BASE}/suggestions?per_page={PER_PAGE}&updated_after=2026-03-04T02%3A58%3A14Z"+ pages = {url: {"suggestions": [{"id": 1}], "pagination": {"page": 1, "total_pages": 1}}}+ fetched = _patch_fetch(monkeypatch, pages)+ _collect(+ monkeypatch,+ _FakeResumableManager(),+ endpoint="suggestions",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ assert "updated_after=2026-03-04T02%3A58%3A14Z" in fetched[0]++ def test_stops_on_empty_response(self, monkeypatch: Any) -> None:+ pages = {+ f"{self._BASE}/labels?per_page={PER_PAGE}": {"labels": [], "pagination": {"page": 1, "total_pages": 1}},+ }+ _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="labels")++ assert rows == []+++class TestUservoiceSourceResponse:+ @parameterized.expand(+ [+ # Incremental endpoints defer the watermark write to job end via "desc" (order is unverified).+ ("suggestions", "desc", "created_at"),+ ("tickets", "desc", "created_at"),+ # Full-refresh endpoints don't checkpoint a watermark, so they stay on the default "asc".+ ("labels", "asc", "created_at"),+ ]+ )+ def test_sort_mode_and_partitioning(self, endpoint: str, expected_sort: str, partition_key: str) -> None:+ response = uservoice_source(+ subdomain="acme",+ api_key="token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == expected_sort+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/tests/test_uservoice_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/tests/test_uservoice_source.pynew file mode 100644index 000000000000..6b1ec4f0f089--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/tests/test_uservoice_source.py@@ -0,0 +1,180 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import UservoiceSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.settings import (+ ENDPOINTS,+ USERVOICE_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.source import UservoiceSource+from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.uservoice import UservoiceResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++_INCREMENTAL_ENDPOINTS = {+ "suggestions",+ "forums",+ "users",+ "comments",+ "notes",+ "nps_ratings",+ "tickets",+ "ticket_messages",+}+_FULL_REFRESH_ENDPOINTS = {"suggestion_statuses", "labels"}+++class TestUservoiceSource:+ def setup_method(self):+ self.source = UservoiceSource()+ self.team_id = 123+ self.config = UservoiceSourceConfig(subdomain="acme", api_key="token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.USERVOICE++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Uservoice"+ assert config.label == "UserVoice"+ # A finished source ships visible with a soft ALPHA label, never hidden.+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/uservoice"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["subdomain", "api_key"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_subdomain_listed_as_connection_host_field(self):+ # The token is sent to <subdomain>.uservoice.com, so retargeting the subdomain must re-require it.+ assert self.source.connection_host_fields == ["subdomain"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://acme.uservoice.com/api/v2/admin/suggestions?per_page=100",+ "403 Client Error: Forbidden for url: https://acme.uservoice.com/api/v2/admin/tickets?per_page=100",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://acme.uservoice.com/api/v2/admin/suggestions",+ "500 Server Error: Internal Server Error for url: https://acme.uservoice.com/api/v2/admin/suggestions",+ "HTTPSConnectionPool(host='acme.uservoice.com', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name in _INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ assert schemas[name].supports_append is True+ assert [f["field"] for f in schemas[name].incremental_fields] == ["updated_at"]+ for name in _FULL_REFRESH_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["suggestions"])+ assert len(schemas) == 1+ assert schemas[0].name == "suggestions"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self):+ # Static endpoint catalog (no I/O) — the public docs table list should render.+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(USERVOICE_ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, 200), True, None),+ ((False, 401), False, "Invalid UserVoice API token"),+ ((False, 403), False, "Could not connect to UserVoice with the provided subdomain and API token"),+ ((False, None), False, "Could not connect to UserVoice with the provided subdomain and API token"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.source.validate_uservoice_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("acme", "token")++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.source.validate_uservoice_credentials"+ )+ def test_validate_credentials_surfaces_bad_subdomain(self, mock_validate):+ mock_validate.side_effect = ValueError("Invalid UserVoice account subdomain: 'a/b'.")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert "Invalid UserVoice account subdomain" in (error_message or "")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is UservoiceResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.source.uservoice_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_uservoice_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "suggestions"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.incremental_field = "updated_at"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_uservoice_source.assert_called_once()+ kwargs = mock_uservoice_source.call_args.kwargs+ assert kwargs["subdomain"] == "acme"+ assert kwargs["api_key"] == "token"+ assert kwargs["endpoint"] == "suggestions"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.source.uservoice_source")+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_uservoice_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "labels"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_uservoice_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/uservoice.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/uservoice.pynew file mode 100644index 000000000000..f4e28c16dce1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uservoice/uservoice.py@@ -0,0 +1,254 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.uservoice.settings import (+ PER_PAGE,+ USERVOICE_ENDPOINTS,+ UservoiceEndpointConfig,+)++USERVOICE_API_PATH = "/api/v2/admin"++# A single DNS label: letters, digits, hyphens (not leading/trailing). Rejects anything that could+# retarget the host (slashes, `@`, dots) so the stored token is only ever sent to `<subdomain>.uservoice.com`.+_SUBDOMAIN_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")+++class UservoiceRetryableError(Exception):+ pass+++class UservoiceResumeConfig:+ # Opaque cursor token from `pagination.cursor`, when the account uses cursor pagination.+ cursor: str | None = None+ # 1-indexed page for the page-number fallback. Only one of `cursor`/`page` is set at a time.+ page: int | None = None+++class _NextPage:+ cursor: str | None = None+ page: int | None = None+++def normalize_subdomain(subdomain: str) -> str:+ """Reduce user input to a bare, validated UserVoice subdomain label.++ Accepts either the full host (``yourcompany.uservoice.com``) or the bare subdomain+ (``yourcompany``). Raises ``ValueError`` on anything that isn't a single DNS label so the+ token can never be retargeted away from ``<subdomain>.uservoice.com``.+ """+ cleaned = subdomain.strip().removeprefix("https://").removeprefix("http://")+ cleaned = cleaned.strip("/")+ cleaned = cleaned.removesuffix(".uservoice.com")+ if not _SUBDOMAIN_RE.match(cleaned):+ raise ValueError(+ f"Invalid UserVoice account subdomain: {subdomain!r}. Enter just your subdomain, e.g. "+ "'yourcompany' for yourcompany.uservoice.com."+ )+ return cleaned+++def _base_url(subdomain: str) -> str:+ return f"https://{normalize_subdomain(subdomain)}.uservoice.com{USERVOICE_API_PATH}"+++def _headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}+++def _format_updated_after(value: Any) -> str:+ """Format an incremental cursor as the ISO8601 UTC string UserVoice expects for `updated_after`.++ UserVoice documents the ``YYYY-mm-ddThh:mm:ssZ`` shape, so we emit the ``Z`` suffix rather than the+ ``+00:00`` offset that ``isoformat()`` produces.+ """+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{base_url}{path}"+ return f"{base_url}{path}?{urlencode(params)}"+++def _build_initial_params(+ config: UservoiceEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ params: dict[str, Any] = {"per_page": PER_PAGE}+ # Only the `updated_after`-capable endpoints filter server-side; everything else is full refresh.+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value:+ params["updated_after"] = _format_updated_after(db_incremental_field_last_value)+ return params+++@retry(+ retry=retry_if_exception_type(+ (+ UservoiceRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:+ response = session.get(url, headers=headers, timeout=60)++ # UserVoice enforces a per-minute rate limit and returns 429 on exceed (requests taking >1s count+ # as extra requests). Back off and retry rather than failing the sync; transient 5xx are retryable too.+ if response.status_code == 429 or response.status_code >= 500:+ raise UservoiceRetryableError(f"UserVoice API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"UserVoice API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _next_page(pagination: dict[str, Any], current_page: int, item_count: int) -> _NextPage | None:+ """Decide how (and whether) to fetch the next page.++ Prefer UserVoice's cursor (``pagination.cursor``); fall back to page numbers+ (``pagination.page`` / ``pagination.total_pages``), and finally to a full-page heuristic if the+ metadata is ever absent (a full page implies there may be more).+ """+ cursor = pagination.get("cursor")+ if cursor:+ return _NextPage(cursor=str(cursor))++ page = pagination.get("page", pagination.get("current_page"))+ total_pages = pagination.get("total_pages")+ if isinstance(page, int) and isinstance(total_pages, int):+ return _NextPage(page=page + 1) if page < total_pages else None++ return _NextPage(page=current_page + 1) if item_count >= PER_PAGE else None+++def get_rows(+ subdomain: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[UservoiceResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict]]:+ config = USERVOICE_ENDPOINTS[endpoint]+ base_url = _base_url(subdomain)+ headers = _headers(api_key)+ session = make_tracked_session()++ base_params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = resume.cursor if resume is not None else None+ page = resume.page if resume is not None else None+ if cursor or page:+ logger.debug(f"UserVoice: resuming {endpoint} from cursor={cursor}, page={page}")++ while True:+ params = dict(base_params)+ # Keep the `updated_after` filter present on every request: with page numbers it must persist,+ # and appending the opaque cursor alongside it is idempotent if the cursor already encodes it.+ if cursor:+ params["cursor"] = cursor+ elif page:+ params["page"] = page++ data = _fetch_page(session, _build_url(base_url, config.path, params), headers, logger)+ items = data.get(config.response_key, []) or []+ pagination = data.get("pagination", {}) or {}+ next_page = _next_page(pagination, page or 1, len(items))++ if items:+ yield items++ if next_page is None:+ break+ # Guard against a non-advancing cursor to avoid looping forever on the same page.+ if next_page.cursor is not None and next_page.cursor == cursor:+ logger.warning(f"UserVoice: {endpoint} returned a non-advancing cursor, stopping pagination")+ break++ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —+ # merge dedupes on the primary key.+ resumable_source_manager.save_state(UservoiceResumeConfig(cursor=next_page.cursor, page=next_page.page))+ cursor, page = next_page.cursor, next_page.page+++def uservoice_source(+ subdomain: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[UservoiceResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = USERVOICE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ subdomain=subdomain,+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ # UserVoice's list order isn't a documented, verifiable guarantee, and its feedback endpoints+ # tend to return newest-first. "desc" defers the incremental watermark write to successful job+ # end (see finalize_desc_sort_incremental_value), so a crashed mid-sync run can't advance the+ # watermark past rows it never fetched; the next run re-pulls from the old watermark and merge+ # dedupes. Full-refresh endpoints don't checkpoint a watermark, so their sort_mode is moot.+ sort_mode="desc" if config.supports_incremental else "asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def validate_credentials(subdomain: str, api_key: str) -> tuple[bool, int | None]:+ """Probe UserVoice's suggestions list to confirm the token is genuine.++ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error. Raises+ ``ValueError`` if the subdomain is malformed so the caller can surface a precise message.+ """+ url = _build_url(_base_url(subdomain), "/suggestions", {"per_page": 1})+ try:+ response = make_tracked_session().get(url, headers=_headers(api_key), timeout=10)+ except Exception:+ return False, None+ return response.status_code == 200, response.status_code