Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(census): add the datasets and workspaces tables (#102227)

Tom Owersa0c9a8c2e401
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index daf2b003e13b..55a1b39f8765 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1301,15 +1301,15 @@ Today (4): `destinations`, `sources`, `sync_runs`, `syncs`
Diffed against: <https://fivetran.com/docs/activations/rest-api/api-reference/workspace-apis/syncs/get-syncs>
-- [ ] `workspace-apis/datasets/list-datasets` — lookup resolving the dataset/model IDs every sync points at - without it syncs reference opaque IDs (high)
+- [x] `workspace-apis/datasets/list-datasets` — lookup resolving the dataset/model IDs every sync points at - without it syncs reference opaque IDs (high)
- [ ] `workspace-apis/sync-runs/fetch-records` — record-level sync results including rejected rows, the detail needed to diagnose why a sync partially failed (high)
- [ ] `workspace-apis/sync-runs/fetch-records-count` — per-run record counts by status, the cheap aggregate for sync health dashboards (medium)
-- [ ] `organization-apis/workspaces/list-workspaces` — lookup naming the workspaces that scope every source, destination and sync (medium)
+- [x] `organization-apis/workspaces/list-workspaces` — lookup naming the workspaces that scope every source, destination and sync (medium)
- [ ] `workspace-apis/source-types/list-source-types` — lookup expanding the source type codes on the sources table (low)
- [ ] `workspace-apis/destination-types/list-connectors` — lookup expanding the destination connector codes on the destinations table (low)
- [ ] `workspace-apis/destinations/objects/fetch-destination-object` — destination object schemas that sync field mappings target (low)
-Note: Census now lives under the Fivetran Activations docs; the docs are HTML-only (no llms.txt or OpenAPI export found at fivetran.com/docs/llms.txt). The reference sidebar is the authoritative resource list. Webhooks and source/destination connect links were excluded as plumbing.
+Note: Census now lives under the Fivetran Activations docs; the docs are HTML-only (no llms.txt or OpenAPI export found at fivetran.com/docs/llms.txt). The reference sidebar is the authoritative resource list. Webhooks and source/destination connect links were excluded as plumbing. The two sync-run record endpoints are left unticked deliberately: both are grandchildren of `syncs` (sync -> sync run -> records), and a chained fan-out carries no resume state, so on a source with no server-side time filter every sync would re-walk the record detail of every retained run from scratch. `fetch-records-count` also only returns one unfiltered count, which `sync_runs` already carries as `records_processed`/`records_updated`/`records_failed`/`records_invalid`.
## Chameleon — gaps
diff --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.py
index b9039be9e24c..0df0abedc2db 100644
--- 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.py
@@ -82,4 +82,24 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"is_file_system_destination": "Whether this destination writes to a file system rather than an API.",
},
},
+ "datasets": {
+ "description": "A Census dataset: the SQL query against a source connection that defines the records a sync reads.",
+ "docs_url": "https://fivetran.com/docs/activations/rest-api/api-reference/workspace-apis/datasets/list-datasets",
+ "columns": {
+ "id": "Unique identifier for the dataset.",
+ "type": "Type of dataset. Census documents `sql` as the only value on this endpoint.",
+ "query": "The SQL query that defines the dataset.",
+ "source_id": "Identifier of the source connection the query runs against.",
+ },
+ },
+ "workspaces": {
+ "description": "A Census workspace: the container that scopes an organization's sources, destinations, and syncs.",
+ "docs_url": "https://fivetran.com/docs/activations/rest-api/api-reference/organization-apis/workspaces/list-workspaces",
+ "columns": {
+ "id": "Unique identifier for the workspace.",
+ "name": "Name of the workspace, unique within the organization.",
+ "organization_id": "Identifier of the organization that owns the workspace.",
+ "created_at": "Timestamp the workspace was created.",
+ },
+ },
}
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.py
index ddbbc59ab203..cb979bb57b56 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/census/census.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/census/census.py
@@ -67,17 +67,21 @@ def _drop_fields(fields: tuple[str, ...]) -> Callable[[dict[str, Any]], dict[str
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(
+def _probe(api_key: str, region: str, path: str, ok_statuses: tuple[int, ...]) -> tuple[bool, int | None]:
+ return validate_via_probe(
lambda: make_tracked_session(redact_values=(api_key,), capture=False),
- f"{_host(region)}/api/v1/syncs",
+ f"{_host(region)}{path}",
headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
ok_statuses=ok_statuses,
allow_redirects=False,
)
+
+
+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 = _probe(api_key, region, "/api/v1/syncs", ok_statuses)
if ok:
return True, None
if status == 401:
@@ -89,6 +93,20 @@ def validate_credentials(api_key: str, region: str, schema_name: Optional[str] =
return False, f"Census API returned an unexpected status: {status}"
+def get_endpoint_permissions(api_key: str, region: str, endpoints: list[str]) -> dict[str, str | None]:
+ permissions: dict[str, str | None] = dict.fromkeys(endpoints)
+ for name in endpoints:
+ config = CENSUS_ENDPOINTS.get(name)
+ if config is None or config.permission_denied_reason is None:
+ continue
+ # Only a refusal means the token cannot read the table; a throttle, 5xx, or network
+ # failure leaves the endpoint reported as reachable and is handled at sync time.
+ _, status = _probe(api_key, region, config.path, (200,))
+ if status in (401, 403):
+ permissions[name] = config.permission_denied_reason
+ return permissions
+
+
def get_resource(endpoint: str) -> EndpointResource:
config = CENSUS_ENDPOINTS[endpoint]
if config.fanout:
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.py
index 8a55a2bae12d..c3154061d687 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/census/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/census/settings.py
@@ -15,7 +15,7 @@ CENSUS_HOSTS = {
PAGE_SIZE = 100
-@dataclass
+@dataclass(frozen=True)
class CensusEndpointConfig:
name: str
path: str
@@ -29,6 +29,10 @@ class CensusEndpointConfig:
# 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, ...] = ()
+ # Set when an otherwise-valid token can be refused for this endpoint. `get_endpoint_permissions`
+ # probes those endpoints so the schema picker names the token the table needs instead of letting
+ # the user select a table that can only fail at sync time.
+ permission_denied_reason: str | None = None
CENSUS_ENDPOINTS: dict[str, CensusEndpointConfig] = {
@@ -69,6 +73,22 @@ CENSUS_ENDPOINTS: dict[str, CensusEndpointConfig] = {
partition_key="created_at",
strip_fields=("connection_details",),
),
+ "datasets": CensusEndpointConfig(
+ name="datasets",
+ path="/api/v1/datasets",
+ # The published list schema echoes the create-dataset request body (`type`, `query`,
+ # `source_id`) and names no timestamp, so there is nothing stable to partition on.
+ # Datasets are addressable at `/api/v1/datasets/{dataset_id}`, so `id` stays the key.
+ permission_denied_reason="Census refused access to datasets. Check that datasets are enabled for your Census organization, then reconnect.",
+ ),
+ "workspaces": CensusEndpointConfig(
+ name="workspaces",
+ path="/api/v1/workspaces",
+ partition_key="created_at",
+ strip_fields=("notification_emails",),
+ # Workspaces is an organization-level endpoint, so a workspace-scoped token cannot read it.
+ permission_denied_reason="Listing workspaces needs an organization-level Census API token. Reconnect with an organization token, or deselect this table.",
+ ),
}
ENDPOINTS = tuple(CENSUS_ENDPOINTS)
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.py
index cfcf6bd6dbfa..403d28eab1d0 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
@@ -12,6 +12,7 @@ from products.warehouse_sources.backend.facade.source_config import (
from products.warehouse_sources.backend.temporal.data_imports.sources.census.census import (
CensusResumeConfig,
census_source,
+ get_endpoint_permissions as get_census_endpoint_permissions,
validate_credentials as validate_census_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.census.settings import (
@@ -77,6 +78,15 @@ class CensusSource(ResumableSource[CensusSourceConfig, CensusResumeConfig]):
) -> tuple[bool, str | None]:
return validate_census_credentials(config.api_key, config.region, schema_name=schema_name)
+ def get_endpoint_permissions(
+ self,
+ config: CensusSourceConfig,
+ team_id: int,
+ endpoints: list[str],
+ api_version: str | None = None,
+ ) -> dict[str, str | None]:
+ return get_census_endpoint_permissions(config.api_key, config.region, endpoints)
+
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CensusResumeConfig]:
return ResumableSourceManager[CensusResumeConfig](inputs, CensusResumeConfig)
@@ -101,9 +111,9 @@ class CensusSource(ResumableSource[CensusSourceConfig, CensusResumeConfig]):
name=ExternalDataSourceType.CENSUS,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Census (Fivetran)",
- caption="""Enter a Census workspace API access token to sync your syncs, sync runs, sources, and destinations.
+ caption="""Enter a Census API access token to sync your syncs, sync runs, sources, destinations, and datasets.
-You can find or generate a workspace access token in Census under **Workspace settings → API Access**.
+You can find or generate a workspace access token in Census under **Workspace settings → API Access**. The workspaces table lists every workspace in your organization, so it needs an organization-level token instead.
""",
keywords=["reverse etl", "data activation", "fivetran"],
docsUrl="https://posthog.com/docs/cdp/sources/census",
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.py
index 09133b2ed73a..b978f57896a0 100644
--- 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.py
@@ -8,6 +8,7 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.census.census import (
CensusResumeConfig,
census_source,
+ get_endpoint_permissions,
get_resource,
validate_credentials,
)
@@ -81,6 +82,46 @@ class TestCensusTransport:
assert result == (False, "Could not reach Census. Please check your network and selected region, then retry.")
+ @parameterized.expand(
+ [
+ (200, None),
+ (
+ 401,
+ "Listing workspaces needs an organization-level Census API token. Reconnect with an organization token, or deselect this table.",
+ ),
+ (
+ 403,
+ "Listing workspaces needs an organization-level Census API token. Reconnect with an organization token, or deselect this table.",
+ ),
+ (429, None), # a throttle is not a refusal
+ (500, None),
+ ]
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.make_tracked_session")
+ def test_get_endpoint_permissions_reports_refusals(self, status, expected_reason, mock_session) -> None:
+ mock_session.return_value.get.return_value = Mock(status_code=status)
+
+ permissions = get_endpoint_permissions(api_key="key", region="us", endpoints=["workspaces"])
+
+ assert permissions == {"workspaces": expected_reason}
+ assert mock_session.return_value.get.call_args.args[0] == "https://app.getcensus.com/api/v1/workspaces"
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.make_tracked_session")
+ def test_get_endpoint_permissions_network_failure_is_not_a_refusal(self, mock_session) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+
+ assert get_endpoint_permissions(api_key="key", region="us", endpoints=["workspaces"]) == {"workspaces": None}
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.census.census.make_tracked_session")
+ def test_get_endpoint_permissions_skips_workspace_scoped_endpoints(self, mock_session) -> None:
+ # Every workspace token can read these, so probing them would only slow the schema picker.
+ permissions = get_endpoint_permissions(
+ api_key="key", region="us", endpoints=["syncs", "sync_runs", "sources", "destinations"]
+ )
+
+ assert permissions == {"syncs": None, "sync_runs": None, "sources": None, "destinations": None}
+ mock_session.return_value.get.assert_not_called()
+
def test_get_resource_full_refresh(self) -> None:
resource = cast(dict[str, Any], get_resource(endpoint="syncs"))
assert resource["name"] == "syncs"
@@ -95,13 +136,19 @@ class TestCensusTransport:
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.
+ @parameterized.expand(
+ [
+ ("sources", "connection_details", {"user": "DEV"}),
+ ("destinations", "connection_details", {"user": "DEV"}),
+ ("workspaces", "notification_emails", ["[email protected]"]),
+ ]
+ )
+ def test_get_resource_strips_sensitive_fields(self, endpoint, stripped_field, stripped_value) -> None:
+ # `connection_details` carries warehouse account identifiers and `notification_emails`
+ # carries people's addresses; neither belongs in a table any project member can query.
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"}
+ row = resource["data_map"]({"id": 1, "name": "Census", stripped_field: stripped_value})
+ assert row == {"id": 1, "name": "Census"}
def test_get_resource_syncs_keeps_all_fields(self) -> None:
resource = cast(dict[str, Any], get_resource(endpoint="syncs"))