: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 Census source (#73184)
Tom Owerse4c2e1958536
diff --git a/frontend/public/services/census.png b/frontend/public/services/census.pngindex 22725023944b..d097761f0a72 100644Binary files a/frontend/public/services/census.png and b/frontend/public/services/census.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0b670108a413..1c2b8ffab495 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -117,6 +117,7 @@ the row lists both.| canny | HTTP | requests | ✅ || capsule_crm | HTTP | requests | ✅ || care_quality_commission | HTTP | requests | ✅ |+| census | HTTP | requests + `rest_source.RESTClient` | ✅ || chameleon | HTTP | requests | ✅ || chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ || chargedesk | HTTP | requests | ✅ |@@ -821,7 +822,6 @@ doesn't conflict with concurrent PRs.- castor_edc- catchpoint- cdc_open_data-- census- checkly- chift- chorusdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/census/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/census/canonical_descriptions.pynew file mode 100644index 000000000000..b9039be9e24c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/census/canonical_descriptions.py@@ -0,0 +1,85 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "syncs": {+ "description": "A Census sync: the configuration that moves data from a source model to a destination object, including its schedule, field mappings, and alerting.",+ "docs_url": "https://fivetran.com/docs/activations/rest-api/api-reference/workspace-apis/syncs/get-syncs",+ "columns": {+ "id": "Unique identifier for the sync.",+ "status": "Current status of the sync configuration (e.g. ready, paused, broken).",+ "label": "Human-readable name of the sync.",+ "operation": "The sync operation type (e.g. mirror, append, update, upsert).",+ "paused": "Whether the sync is currently paused and will not run on schedule.",+ "created_at": "Timestamp the sync was created.",+ "updated_at": "Timestamp the sync configuration was last updated.",+ "source_attributes": "The source connection and model/table this sync reads from.",+ "destination_attributes": "The destination connection and object this sync writes to.",+ "mappings": "The field mappings between the source model and destination object.",+ "mode": "The sync's trigger mode (e.g. triggered on a schedule, or continuous).",+ "high_water_mark_attribute": "The source column Census uses to detect changed records between runs.",+ "field_behavior": "Which destination fields are synced (e.g. sync all properties, or only mapped fields).",+ "mirror_strategy": "For mirror syncs, whether deletes are propagated to the destination.",+ "historical_sync_operation": "How the initial (historical) sync run backfills records.",+ "match_rate_details": "The most recently calculated match rate between source and destination records.",+ },+ },+ "sync_runs": {+ "description": "A single execution of a Census sync, including its status, timing, and per-run record counts.",+ "docs_url": "https://fivetran.com/docs/activations/rest-api/api-reference/workspace-apis/sync-runs/list-sync-runs",+ "columns": {+ "id": "Unique identifier for the sync run.",+ "sync_id": "Identifier of the sync this run belongs to.",+ "status": "Final or current status of the run (e.g. completed, failed, working).",+ "created_at": "Timestamp the run was created/queued.",+ "updated_at": "Timestamp the run was last updated.",+ "completed_at": "Timestamp the run finished, if completed.",+ "canceled": "Whether the run was canceled before completion.",+ "current_step": "The processing step the run is currently on or last reported.",+ "full_sync": "Whether this run was a full (historical) sync rather than an incremental one.",+ "error_code": "Machine-readable error code if the run failed.",+ "error_message": "Short human-readable error message if the run failed.",+ "error_detail": "Extended error detail for troubleshooting a failed run.",+ "source_record_count": "Number of records read from the source for this run.",+ "records_processed": "Number of records processed by the sync during this run.",+ "records_updated": "Number of destination records updated during this run.",+ "records_failed": "Number of records that failed to sync during this run.",+ "records_invalid": "Number of records rejected as invalid during this run.",+ "source_record_updates": "Number of source records detected as updates for this run.",+ "source_record_deletes": "Number of source records detected as deletes for this run.",+ "source_record_invalids": "Number of source records flagged invalid for this run.",+ "scheduled_execution_time": "The time the run was scheduled to execute.",+ "sync_trigger_reason": "What triggered the run (e.g. manual, scheduled).",+ },+ },+ "sources": {+ "description": "A Census data source: a connected warehouse or database Census reads records from.",+ "docs_url": "https://fivetran.com/docs/activations/rest-api/api-reference/workspace-apis/sources/list-sources",+ "columns": {+ "id": "Unique identifier for the source connection.",+ "name": "Internal name of the source connection.",+ "label": "Human-readable label of the source connection.",+ "type": "The warehouse/database type (e.g. snowflake, bigquery, postgres).",+ "sync_engine": "The engine Census uses to query this source.",+ "created_at": "Timestamp the source connection was created.",+ "last_tested_at": "Timestamp connectivity to the source was last tested.",+ "last_test_succeeded": "Whether the most recent connectivity test succeeded.",+ "last_test_results": "Detailed results of the most recent connectivity test.",+ "warehouse_writeback_retention_in_days": "How many days of writeback/sync history Census retains for this source.",+ },+ },+ "destinations": {+ "description": "A Census destination: a connected SaaS tool or warehouse Census writes records to.",+ "docs_url": "https://fivetran.com/docs/activations/rest-api/api-reference/workspace-apis/destinations/list-destinations",+ "columns": {+ "id": "Unique identifier for the destination connection.",+ "name": "Name of the destination connection.",+ "created_at": "Timestamp the destination connection was created.",+ "last_tested_at": "Timestamp connectivity to the destination was last tested.",+ "last_test_succeeded": "Whether the most recent connectivity test succeeded.",+ "last_test_results": "Detailed results of the most recent connectivity test.",+ "is_file_system_destination": "Whether this destination writes to a file system rather than an API.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/census/census.py b/products/warehouse_sources/backend/temporal/data_imports/sources/census/census.pynew file mode 100644index 000000000000..f263f98f2c84--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/census/census.py@@ -0,0 +1,195 @@+import dataclasses+from collections.abc import Callable+from typing import Any, Optional, cast++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.census.settings import (+ CENSUS_ENDPOINTS,+ CENSUS_HOSTS,+ CensusEndpointConfig,+)+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.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+++class CensusResumeConfig:+ # Opaque framework checkpoint: `{"page": N}` for top-level endpoints, or the fan-out+ # manager's `{"completed": [...], "current": ..., "child_state": {"page": N}}` for+ # sync_runs — round-tripped into `initial_paginator_state` on resume.+ paginator_state: dict[str, Any]+++def _host(region: str) -> str:+ return CENSUS_HOSTS.get(region, CENSUS_HOSTS["us"])+++def _paginator() -> PageNumberPaginator:+ # Census pages are 1-indexed and the response echoes `pagination.last_page`, so the+ # paginator can stop precisely instead of paying one extra empty-page request.+ return PageNumberPaginator(base_page=1, page_param="page", total_path="pagination.last_page")+++def _client_config(api_key: str, region: str) -> ClientConfig:+ return {+ "base_url": _host(region),+ "headers": {"Accept": "application/json"},+ "auth": {"type": "bearer", "token": api_key},+ # Census responses echo `connection_details` (warehouse account, user, and warehouse+ # identifiers) which `_drop_fields` strips per-row — but HTTP sample capture records the+ # raw body before the mapper runs, so `capture=False` keeps that metadata out of samples.+ "session": make_tracked_session(capture=False, redact_values=(api_key,)),+ }+++def _drop_fields(fields: tuple[str, ...]) -> Callable[[dict[str, Any]], dict[str, Any]]:+ def _mapper(row: dict[str, Any]) -> dict[str, Any]:+ for field_name in fields:+ row.pop(field_name, None)+ return row++ return _mapper+++def validate_credentials(api_key: str, region: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:+ # A missing scope on a workspace token would 403 rather than 401; accept that at source-create+ # (schema_name is None) since the user may only want to sync a subset of resources.+ ok_statuses = (200, 403) if schema_name is None else (200,)+ ok, status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,), capture=False),+ f"{_host(region)}/api/v1/syncs",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ ok_statuses=ok_statuses,+ allow_redirects=False,+ )+ if ok:+ return True, None+ if status == 401:+ return False, "Census rejected the API token. Generate a new workspace access token and reconnect."+ if status == 403:+ return False, "Your Census API token does not have access to this resource."+ if status is None:+ return False, "Could not reach Census. Please check your network and selected region, then retry."+ return False, f"Census API returned an unexpected status: {status}"+++def get_resource(endpoint: str) -> EndpointResource:+ config = CENSUS_ENDPOINTS[endpoint]+ if config.fanout:+ raise ValueError(f"Fan-out endpoint '{endpoint}' must use the fan-out path")++ endpoint_config: Endpoint = {+ "path": config.path,+ # `order=asc` (oldest-created-first) keeps offset-style page-number pagination stable:+ # new rows created mid-sync are appended past the last page instead of shifting rows+ # already fetched (Census's implicit default is newest-first).+ "params": {"per_page": config.page_size, "order": "asc"},+ "data_selector": "data",+ "paginator": _paginator(),+ }++ resource: EndpointResource = {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+ if config.strip_fields:+ resource["data_map"] = _drop_fields(config.strip_fields)+ return resource+++def _make_source_response(endpoint_config: CensusEndpointConfig, items_fn: Any) -> SourceResponse:+ return SourceResponse(+ name=endpoint_config.name,+ items=items_fn,+ primary_keys=endpoint_config.primary_key+ if isinstance(endpoint_config.primary_key, list)+ else [endpoint_config.primary_key],+ sort_mode=endpoint_config.sort_mode,+ partition_count=1,+ partition_size=1,+ 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,+ )+++def census_source(+ api_key: str,+ region: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CensusResumeConfig],+) -> SourceResponse:+ endpoint_config = CENSUS_ENDPOINTS[endpoint]++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = resume_config.paginator_state++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's somewhere to resume to; the Redis TTL handles cleanup.+ if state:+ resumable_source_manager.save_state(CensusResumeConfig(paginator_state=dict(state)))++ if endpoint_config.fanout:+ dependent_resource = build_dependent_resource(+ endpoint_configs=cast(Any, CENSUS_ENDPOINTS),+ child_endpoint=endpoint,+ fanout=endpoint_config.fanout,+ client_config=_client_config(api_key, region),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ page_size_param="per_page",+ parent_endpoint_extra={+ "paginator": _paginator(),+ "data_selector": "data",+ },+ child_endpoint_extra={+ "paginator": _paginator(),+ "data_selector": "data",+ },+ child_params_extra={"order": "asc"},+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ return _make_source_response(endpoint_config, lambda: dependent_resource)++ config: RESTAPIConfig = {+ "client": _client_config(api_key, region),+ "resource_defaults": {"write_disposition": "replace"},+ "resources": [get_resource(endpoint=endpoint)],+ }++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ return _make_source_response(endpoint_config, lambda: resource)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/census/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/census/settings.pynew file mode 100644index 000000000000..8a55a2bae12d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/census/settings.py@@ -0,0 +1,78 @@+from dataclasses import dataclass, field+from typing import Literal++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField++CENSUS_HOSTS = {+ "us": "https://app.getcensus.com",+ "eu": "https://app-eu.getcensus.com",+}++# Census documents `per_page` with a default of 25 and a hard cap of 100.+PAGE_SIZE = 100+++@dataclass+class CensusEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ partition_key: str | None = None+ page_size: int = PAGE_SIZE+ sort_mode: Literal["asc", "desc"] = "asc"+ primary_key: str | list[str] = "id"+ fanout: DependentEndpointConfig | None = None+ # Response fields dropped from every row before it is yielded. Census `connection_details`+ # on sources/destinations carries warehouse account identifiers (account, user, warehouse+ # name) that shouldn't be copied into a table any project member can query.+ strip_fields: tuple[str, ...] = ()+++CENSUS_ENDPOINTS: dict[str, CensusEndpointConfig] = {+ # Census has no server-side `updated_since`/`created_since` filter on any list endpoint+ # (only `page`/`per_page`/`order`), so every table is full refresh only.+ "syncs": CensusEndpointConfig(+ name="syncs",+ path="/api/v1/syncs",+ partition_key="created_at",+ ),+ "sync_runs": CensusEndpointConfig(+ name="sync_runs",+ path="/api/v1/syncs/{sync_id}/sync_runs",+ partition_key="created_at",+ # `id` is only documented per-sync ("List Sync Runs" scopes it under a sync_id path+ # param); this table aggregates runs across every sync, so the parent id is part of+ # the key to keep it unique table-wide.+ primary_key=["sync_id", "id"],+ fanout=DependentEndpointConfig(+ parent_name="syncs",+ resolve_param="sync_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "sync_id"},+ # `order=asc` keeps the parent page walk stable (see `get_resource`'s comment).+ parent_params={"order": "asc"},+ ),+ ),+ "sources": CensusEndpointConfig(+ name="sources",+ path="/api/v1/sources",+ partition_key="created_at",+ strip_fields=("connection_details",),+ ),+ "destinations": CensusEndpointConfig(+ name="destinations",+ path="/api/v1/destinations",+ partition_key="created_at",+ strip_fields=("connection_details",),+ ),+}++ENDPOINTS = tuple(CENSUS_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CENSUS_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/census/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/census/source.pyindex 8a24b6b720f9..2c419264e9c3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/census/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/census/source.py@@ -1,30 +1,140 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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.census.census import (+ CensusResumeConfig,+ census_source,+ validate_credentials as validate_census_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.census.settings import (+ 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.generated_configs.census import CensusSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CensusSource(SimpleSource[CensusSourceConfig]):+class CensusSource(ResumableSource[CensusSourceConfig, CensusResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://fivetran.com/docs/activations/rest-api"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CENSUS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Census rejected the API token. Generate a new workspace access token in Census (workspace settings → API Access) and reconnect.",+ "403 Client Error": "Your Census API token does not have access to this resource. Check the token's permissions in Census and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.census.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CensusSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # Census has no server-side timestamp filter on any list endpoint (only page-based+ # pagination + creation-time ordering), so every table is full refresh only.+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: CensusSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_census_credentials(config.api_key, config.region, schema_name=schema_name)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CensusResumeConfig]:+ return ResumableSourceManager[CensusResumeConfig](inputs, CensusResumeConfig)++ def source_for_pipeline(+ self,+ config: CensusSourceConfig,+ resumable_source_manager: ResumableSourceManager[CensusResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return census_source(+ api_key=config.api_key,+ region=config.region,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CENSUS,category=DataWarehouseSourceCategory.ANALYTICS,label="Census (Fivetran)",+ caption="""Enter a Census workspace API access token to sync your syncs, sync runs, sources, and destinations.++You can find or generate a workspace access token in Census under **Workspace settings → API Access**.+""",+ keywords=["reverse etl", "data activation", "fivetran"],+ docsUrl="https://posthog.com/docs/cdp/sources/census",iconPath="/static/services/census.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Workspace region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (app.getcensus.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (app-eu.getcensus.com)", value="eu"),+ ],+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/census/tests/test_census.py b/products/warehouse_sources/backend/temporal/data_imports/sources/census/tests/test_census.pynew file mode 100644index 000000000000..09133b2ed73a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/census/tests/test_census.py@@ -0,0 +1,293 @@+from typing import Any, cast++import pytest+from unittest.mock import Mock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.census.census import (+ CensusResumeConfig,+ census_source,+ get_resource,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+++class _FakeDltResource:+ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper):+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++def _make_manager(resume_state: CensusResumeConfig | None = None) -> Mock:+ manager = Mock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++class TestCensusTransport:+ @parameterized.expand(+ [+ ("us", "https://app.getcensus.com"),+ ("eu", "https://app-eu.getcensus.com"),+ ("unknown", "https://app.getcensus.com"), # unrecognized region falls back to US+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.make_tracked_session")+ def test_validate_credentials_uses_region_host(self, region, expected_host, mock_session) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=200)++ validate_credentials(api_key="key", region=region)++ call = mock_session.return_value.get.call_args+ assert call.args[0] == f"{expected_host}/api/v1/syncs"+ assert call.kwargs["headers"]["Authorization"] == "Bearer key"++ @parameterized.expand(+ [+ (200, None, True, None),+ (401, None, False, "Census rejected the API token. Generate a new workspace access token and reconnect."),+ (403, None, True, None), # missing scope accepted at source-create+ (403, "syncs", False, "Your Census API token does not have access to this resource."),+ (500, None, False, "Census API returned an unexpected status: 500"),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.make_tracked_session")+ def test_validate_credentials_status_mapping(+ self, status, schema_name, expected_valid, expected_message, mock_session+ ) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=status)++ result = validate_credentials(api_key="key", region="us", schema_name=schema_name)++ assert result == (expected_valid, expected_message)++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.make_tracked_session")+ def test_validate_credentials_network_failure(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")++ result = validate_credentials(api_key="key", region="us")++ assert result == (False, "Could not reach Census. Please check your network and selected region, then retry.")++ def test_get_resource_full_refresh(self) -> None:+ resource = cast(dict[str, Any], get_resource(endpoint="syncs"))+ assert resource["name"] == "syncs"+ assert resource["write_disposition"] == "replace"+ assert resource["endpoint"]["path"] == "/api/v1/syncs"+ assert resource["endpoint"]["data_selector"] == "data"+ assert resource["endpoint"]["params"] == {"per_page": 100, "order": "asc"}+ assert isinstance(resource["endpoint"]["paginator"], PageNumberPaginator)+ assert resource["table_format"] == "delta"++ def test_get_resource_rejects_sync_runs_fanout(self) -> None:+ with pytest.raises(ValueError, match="Fan-out endpoint"):+ get_resource(endpoint="sync_runs")++ @parameterized.expand([("sources",), ("destinations",)])+ def test_get_resource_strips_connection_details(self, endpoint) -> None:+ # `connection_details` carries warehouse account identifiers that must not land in a+ # queryable warehouse table.+ resource = cast(dict[str, Any], get_resource(endpoint=endpoint))+ row = resource["data_map"]({"id": 1, "name": "Snowflake", "connection_details": {"user": "DEV"}})+ assert row == {"id": 1, "name": "Snowflake"}++ def test_get_resource_syncs_keeps_all_fields(self) -> None:+ resource = cast(dict[str, Any], get_resource(endpoint="syncs"))+ assert "data_map" not in resource++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.make_tracked_session")+ def test_probe_disables_sample_capture(self, mock_session) -> None:+ # The `/syncs` probe response echoes `connection_details`; capturing it would persist the+ # warehouse account/user/warehouse identifiers to shared sample storage before any mapper runs.+ mock_session.return_value.get.return_value = Mock(status_code=200)++ validate_credentials(api_key="key", region="us")++ assert mock_session.call_args.kwargs["capture"] is False++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.make_tracked_session")+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.rest_api_resource")+ def test_client_session_disables_sample_capture(self, mock_rest_api_resource, mock_session) -> None:+ # Sync responses echo `connection_details` which `_drop_fields` strips per-row, but HTTP+ # sample capture records the raw body first — the client must run capture=False so that+ # metadata never reaches shared sample storage.+ mock_rest_api_resource.return_value = Mock()++ census_source(+ api_key="key",+ region="us",+ endpoint="syncs",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ assert mock_session.call_args.kwargs["capture"] is False+ assert mock_rest_api_resource.call_args.args[0]["client"]["session"] is mock_session.return_value++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.rest_api_resource")+ def test_census_source_top_level_response(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()+ response = census_source(+ api_key="key",+ region="us",+ endpoint="syncs",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ assert response.name == "syncs"+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.rest_api_resource")+ def test_census_source_resumes_from_saved_state(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()+ manager = _make_manager(CensusResumeConfig(paginator_state={"page": 3}))++ census_source(+ api_key="key",+ region="us",+ endpoint="syncs",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ kwargs = mock_rest_api_resource.call_args.kwargs+ assert kwargs["initial_paginator_state"] == {"page": 3}++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.rest_api_resource")+ def test_census_source_saves_checkpoints_after_batches(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()+ manager = _make_manager()++ census_source(+ api_key="key",+ region="us",+ endpoint="syncs",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]+ resume_hook({"page": 2})+ manager.save_state.assert_called_once_with(CensusResumeConfig(paginator_state={"page": 2}))++ # A terminal (None) checkpoint is not persisted — the Redis TTL handles cleanup.+ manager.save_state.reset_mock()+ resume_hook(None)+ manager.save_state.assert_not_called()++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_sync_runs_fanout_row_format(self, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("syncs", [{"id": 42}]),+ _FakeDltResource("sync_runs", [{"id": 7, "status": "completed", "_syncs_id": 42}]),+ ]++ response = census_source(+ api_key="key",+ region="us",+ endpoint="sync_runs",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ rows = list(cast(Any, response.items()))+ assert rows == [{"id": 7, "status": "completed", "sync_id": 42}]+ # Run ids are only documented per-sync, so the parent sync id is part of the key.+ assert response.primary_keys == ["sync_id", "id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]+ assert response.sort_mode == "asc"++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.build_dependent_resource")+ def test_sync_runs_fanout_wiring(self, mock_build_dependent_resource) -> None:+ mock_build_dependent_resource.return_value = iter([])+ manager = _make_manager(CensusResumeConfig(paginator_state={"completed": [], "current": None}))++ census_source(+ api_key="key",+ region="us",+ endpoint="sync_runs",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert kwargs["page_size_param"] == "per_page"+ assert "params" not in kwargs["parent_endpoint_extra"]+ assert kwargs["parent_endpoint_extra"]["data_selector"] == "data"+ assert kwargs["child_endpoint_extra"]["data_selector"] == "data"+ assert isinstance(kwargs["parent_endpoint_extra"]["paginator"], PageNumberPaginator)+ assert isinstance(kwargs["child_endpoint_extra"]["paginator"], PageNumberPaginator)+ assert kwargs["child_params_extra"] == {"order": "asc"}+ assert kwargs["db_incremental_field_last_value"] is None+ assert kwargs["resume_hook"] is not None+ assert kwargs["initial_paginator_state"] == {"completed": [], "current": None}+++class TestCensusPageNumberPaginator:+ def test_stops_at_last_page(self) -> None:+ paginator = PageNumberPaginator(base_page=1, page_param="page", total_path="pagination.last_page")+ request = Mock()+ request.params = {}+ paginator.init_request(request)+ assert request.params["page"] == 1++ response = Mock()+ response.json.return_value = {"pagination": {"last_page": 1}, "data": [{"id": 1}]}+ paginator.update_state(response, data=[{"id": 1}])++ assert paginator.has_next_page is False++ def test_continues_before_last_page(self) -> None:+ paginator = PageNumberPaginator(base_page=1, page_param="page", total_path="pagination.last_page")++ response = Mock()+ response.json.return_value = {"pagination": {"last_page": 3}, "data": [{"id": 1}]}+ paginator.update_state(response, data=[{"id": 1}])++ assert paginator.has_next_page is True++ request = Mock()+ request.params = {}+ paginator.update_request(request)+ assert request.params["page"] == 2++ def test_resume_state_roundtrip(self) -> None:+ paginator = PageNumberPaginator(base_page=1, page_param="page", total_path="pagination.last_page")+ response = Mock()+ response.json.return_value = {"pagination": {"last_page": 5}, "data": [{"id": 1}]}+ paginator.update_state(response, data=[{"id": 1}])++ state = paginator.get_resume_state()+ assert state == {"page": 2}++ resumed = PageNumberPaginator(base_page=1, page_param="page", total_path="pagination.last_page")+ resumed.set_resume_state(cast(dict[str, Any], state))+ request = Mock()+ request.params = {}+ resumed.init_request(request)+ assert request.params["page"] == 2diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/census/tests/test_census_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/census/tests/test_census_source.pynew file mode 100644index 000000000000..a3c7a6daa660--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/census/tests/test_census_source.py@@ -0,0 +1,123 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.census.census import CensusResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.census.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.census.source import CensusSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.census import CensusSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestCensusSource:+ def setup_method(self) -> None:+ self.source = CensusSource()+ self.team_id = 123+ self.config = CensusSourceConfig(api_key="census-key", region="us")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CENSUS++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Census"+ assert config.label == "Census (Fivetran)"+ assert config.category == DataWarehouseSourceCategory.ANALYTICS+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # The source ships visible: unreleasedSource hides the connector from every user.+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/census.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/census"++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_region_field_defaults_to_us(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig) and f.name == "region")+ assert field.defaultValue == "us"+ assert {option.value for option in field.options} == {"us", "eu"}++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_all_full_refresh(self) -> None:+ # Census has no server-side timestamp filter on any list endpoint, so nothing supports+ # incremental sync.+ schemas = self.source.get_schemas(self.config, self.team_id)+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["sync_runs"])+ assert len(schemas) == 1+ assert schemas[0].name == "sync_runs"++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://app.getcensus.com/api/v1/syncs",+ "403 Client Error: Forbidden for url: https://app.getcensus.com/api/v1/syncs",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ def test_non_retryable_errors_ignore_transient_failures(self) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(+ key in "500 Server Error for url: https://app.getcensus.com/api/v1/syncs" for key in non_retryable+ )++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.census.source.validate_census_credentials"+ )+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="sync_runs")++ assert result == (True, None)+ mock_validate.assert_called_once_with("census-key", "us", schema_name="sync_runs")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is CensusResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.source.census_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_census_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "sync_runs"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_census_source.call_args.kwargs+ assert kwargs["api_key"] == "census-key"+ assert kwargs["region"] == "us"+ assert kwargs["endpoint"] == "sync_runs"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["job_id"] == "job-1"+ assert kwargs["resumable_source_manager"] is manager++ def test_canonical_descriptions_cover_endpoints(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/generated_configs/census.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/census.pyindex ac52c59a5a95..928b2c5a687d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/census.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/census.py@@ -1,9 +1,12 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass CensusSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu"] = config.value(default="us")