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(data-warehouse): add Zero import source (#84477)

Tom Owers39d9939a97f3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zero.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zero.py
index 83ad449f4c1a..12ee47b89616 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zero.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zero.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class ZeroSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zero/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zero/canonical_descriptions.py
new file mode 100644
index 000000000000..ba8079dfb327
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zero/canonical_descriptions.py
@@ -0,0 +1,210 @@
+"""Canonical, documentation-sourced descriptions for Zero endpoints and columns.
+
+Sourced from the official Zero API reference (https://docs.zero.inc/features/api). Keyed by the
+resource names in `settings.py` `ENDPOINT_CONFIGS`, which match the `ExternalDataSchema.name` of a
+synced Zero table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Fields shared by most workspace-scoped Zero objects; merged into each entry so they aren't repeated.
+_COMMON_COLUMNS = {
+ "id": "Unique identifier for the record.",
+ "workspaceId": "Identifier of the workspace the record belongs to.",
+ "createdAt": "Time at which the record was created.",
+ "updatedAt": "Time at which the record was last updated.",
+ "archived": "Whether the record has been archived.",
+ "createdById": "Identifier of the user who created the record.",
+ "externalId": "Identifier of the record in the system it was imported from, if any.",
+ "source": "Where the record originated from (e.g. manual entry, email capture, import).",
+}
+
+
+def _columns(**overrides: str) -> dict[str, str]:
+ return {**_COMMON_COLUMNS, **overrides}
+
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Workspaces": {
+ "description": "The Zero workspace the connected API key belongs to.",
+ "docs_url": "https://docs.zero.inc/features/api/workspaces",
+ "columns": {
+ "id": "Unique identifier for the workspace.",
+ "name": "Name of the workspace.",
+ "key": "URL-safe identifier for the workspace.",
+ "domain": "Primary email domain associated with the workspace.",
+ "domains": "All email domains associated with the workspace.",
+ "trialEndsAt": "Time at which the workspace's trial period ends, if applicable.",
+ "archived": "Whether the workspace has been archived.",
+ "createdAt": "Time at which the workspace was created.",
+ "updatedAt": "Time at which the workspace was last updated.",
+ },
+ },
+ "Companies": {
+ "description": "A company (account) tracked in the CRM, auto-captured from email and calendar activity.",
+ "docs_url": "https://docs.zero.inc/features/api/companies",
+ "columns": _columns(
+ name="Name of the company.",
+ domain="Primary domain of the company.",
+ description="Free-text description of the company.",
+ linkedin="LinkedIn URL for the company.",
+ logo="URL of the company's logo.",
+ listIds="Identifiers of the lists the company belongs to.",
+ ownerIds="Identifiers of the users who own the company.",
+ location="Location of the company (city, state, country, coordinates).",
+ parentCompanyId="Identifier of the company's parent company, if any.",
+ custom="Custom property values defined by the workspace, keyed by property id.",
+ ),
+ },
+ "Contacts": {
+ "description": "A person tracked in the CRM, auto-captured from email, calendar, and call activity.",
+ "docs_url": "https://docs.zero.inc/features/api/contacts",
+ "columns": _columns(
+ companyId="Identifier of the company the contact belongs to.",
+ name="Full name of the contact.",
+ email="Primary email address of the contact.",
+ title="Job title of the contact.",
+ phone="Phone number of the contact.",
+ linkedin="LinkedIn username of the contact.",
+ location="Location of the contact.",
+ type="Type of contact record.",
+ listIds="Identifiers of the lists the contact belongs to.",
+ ownerIds="Identifiers of the users who own the contact.",
+ custom="Custom property values defined by the workspace, keyed by property id.",
+ unsubscribedFromAllMessaging="Whether the contact has unsubscribed from all outbound messaging.",
+ unsubscribedFromAllMessagingAt="Time at which the contact unsubscribed from all outbound messaging.",
+ ),
+ },
+ "Deals": {
+ "description": "An opportunity moving through a sales pipeline.",
+ "docs_url": "https://docs.zero.inc/features/api/deals",
+ "columns": _columns(
+ pipelineId="Identifier of the pipeline the deal belongs to.",
+ companyId="Identifier of the company the deal is associated with.",
+ contactIds="Identifiers of the contacts associated with the deal.",
+ name="Name of the deal.",
+ stage="Identifier of the pipeline stage the deal is currently in.",
+ value="Monetary value of the deal.",
+ confidence="Confidence (0.0-1.0) that the deal will close.",
+ closeDate="Expected or actual close date of the deal.",
+ startDate="Date the deal was opened.",
+ endDate="Date the deal was closed, if closed.",
+ listIds="Identifiers of the lists the deal belongs to.",
+ ownerIds="Identifiers of the users who own the deal.",
+ custom="Custom property values defined by the workspace, keyed by property id.",
+ ),
+ },
+ "Pipelines": {
+ "description": "A sales pipeline used to track deals through a sequence of stages.",
+ "docs_url": "https://docs.zero.inc/features/api/pipelines",
+ "columns": _columns(
+ name="Name of the pipeline.",
+ description="Free-text description of the pipeline.",
+ icon="Icon shown for the pipeline in the UI.",
+ color="Hex color shown for the pipeline in the UI.",
+ confidenceEnabled="Whether deals in this pipeline track a win confidence score.",
+ defaultStage="Identifier of the stage new deals are created in.",
+ order="Sort order of the pipeline relative to other pipelines.",
+ ),
+ },
+ "PipelineStages": {
+ "description": "A stage within a sales pipeline (e.g. lead, in-progress, won, lost).",
+ "docs_url": "https://docs.zero.inc/features/api/pipeline-stages",
+ "columns": _columns(
+ pipelineId="Identifier of the pipeline this stage belongs to.",
+ name="Name of the stage.",
+ description="Free-text description of the stage.",
+ type="Category of the stage: lead, in-progress, won, or lost.",
+ confidence="Default win confidence (0.0-1.0) for deals in this stage.",
+ icon="Icon shown for the stage in the UI.",
+ color="Hex color shown for the stage in the UI.",
+ order="Sort order of the stage within its pipeline.",
+ ),
+ },
+ "Notes": {
+ "description": "A note attached to a company, contact, or deal.",
+ "docs_url": "https://docs.zero.inc/features/api/notes",
+ "columns": _columns(
+ name="Title of the note.",
+ emoji="Emoji icon shown for the note.",
+ content="Body of the note, in Tiptap document format.",
+ companyId="Identifier of the company the note is attached to, if any.",
+ contactId="Identifier of the contact the note is attached to, if any.",
+ dealId="Identifier of the deal the note is attached to, if any.",
+ ),
+ },
+ "Tasks": {
+ "description": "A to-do item, optionally linked to companies, contacts, or deals.",
+ "docs_url": "https://docs.zero.inc/features/api/tasks",
+ "columns": _columns(
+ name="Title of the task.",
+ done="Whether the task has been completed.",
+ priority="Priority of the task.",
+ deadline="Due date of the task.",
+ content="Rich-text body of the task.",
+ description="Free-text description of the task.",
+ companyIds="Identifiers of the companies the task is linked to.",
+ contactIds="Identifiers of the contacts the task is linked to.",
+ dealIds="Identifiers of the deals the task is linked to.",
+ assignedToIds="Identifiers of the users the task is assigned to.",
+ type="Type of task.",
+ message="Message associated with the task, if any.",
+ ),
+ },
+ "Meetings": {
+ "description": "A calendar event, optionally linked to companies, contacts, or deals.",
+ "docs_url": "https://docs.zero.inc/features/api/meetings",
+ "columns": _columns(
+ name="Title of the meeting.",
+ startTime="Start time of the meeting.",
+ endTime="End time of the meeting.",
+ location="Location of the meeting.",
+ description="Free-text description of the meeting.",
+ organizer="Email and display name of the meeting organizer.",
+ attendeeEmails="Email addresses of the meeting's attendees.",
+ meetingLink="Video conferencing URL for the meeting.",
+ summary="AI-generated summary of the meeting, in Tiptap document format.",
+ userIds="Identifiers of the workspace users attending the meeting.",
+ companyIds="Identifiers of the companies linked to the meeting.",
+ contactIds="Identifiers of the contacts linked to the meeting.",
+ dealIds="Identifiers of the deals linked to the meeting.",
+ busy="Whether the meeting marks the attendees as busy.",
+ external="Whether the meeting was synced from an external calendar.",
+ audioUrl="URL of the meeting's audio recording, if any.",
+ videoUrl="URL of the meeting's video recording, if any.",
+ ),
+ },
+ "Memberships": {
+ "description": "A user's membership in the workspace, including their role.",
+ "docs_url": "https://docs.zero.inc/features/api/memberships",
+ "columns": {
+ "id": "Unique identifier for the membership.",
+ "userId": "Identifier of the user who is a member of the workspace.",
+ "workspaceId": "Identifier of the workspace the user is a member of.",
+ "role": "Role the user holds in the workspace.",
+ "invitedById": "Identifier of the user who sent the invite.",
+ "archived": "Whether the membership has been archived (the member removed).",
+ "createdAt": "Time at which the membership was created.",
+ "updatedAt": "Time at which the membership was last updated.",
+ },
+ },
+ "Users": {
+ "description": "A user with access to the workspace.",
+ "docs_url": "https://docs.zero.inc/features/api/users",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "name": "Full name of the user.",
+ "email": "Email address of the user.",
+ "title": "Job title of the user.",
+ "avatar": "URL of the user's profile picture.",
+ "linkedin": "LinkedIn username of the user.",
+ "active": "Whether the user's account is active.",
+ "emailConfirmed": "Whether the user has confirmed their email address.",
+ "lastSeenAt": "Time at which the user was last active.",
+ "createdAt": "Time at which the user account was created.",
+ "updatedAt": "Time at which the user account was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zero/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zero/settings.py
new file mode 100644
index 000000000000..59c6025ec4e3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zero/settings.py
@@ -0,0 +1,119 @@
+from dataclasses import field
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Zero has no documented API version — every endpoint lives under a bare, unversioned /api/ path.
+ZERO_BASE_URL = "https://api.zero.inc"
+
+
+def _datetime_incremental_fields() -> list[IncrementalField]:
+ # Zero timestamps are ISO 8601 strings; both createdAt and updatedAt support the `$gt`/`$gte`
+ # date operators documented for the `where` filter on every list endpoint.
+ return [
+ {
+ "label": "updatedAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updatedAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "createdAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+
+
+@frozen(slots=False)
+class ZeroEndpointConfig:
+ name: str
+ path: str
+ table_name: str
+ # Whether this endpoint's rows carry a `workspaceId` field and must be scoped with
+ # `where={"workspaceId": ...}`. Users has no such field (identities are global, scoped
+ # implicitly to the ones visible via the key's workspace); Workspaces IS the workspace and is
+ # already scoped to the authenticated key's memberships with no filter of its own.
+ scoped_by_workspace: bool = True
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+ENDPOINT_CONFIGS: dict[str, ZeroEndpointConfig] = {
+ "Workspaces": ZeroEndpointConfig(
+ name="Workspaces",
+ path="/api/workspaces",
+ table_name="workspaces",
+ scoped_by_workspace=False,
+ ),
+ "Companies": ZeroEndpointConfig(
+ name="Companies",
+ path="/api/companies",
+ table_name="companies",
+ incremental_fields=_datetime_incremental_fields(),
+ ),
+ "Contacts": ZeroEndpointConfig(
+ name="Contacts",
+ path="/api/contacts",
+ table_name="contacts",
+ incremental_fields=_datetime_incremental_fields(),
+ ),
+ "Deals": ZeroEndpointConfig(
+ name="Deals",
+ path="/api/deals",
+ table_name="deals",
+ incremental_fields=_datetime_incremental_fields(),
+ ),
+ "Pipelines": ZeroEndpointConfig(
+ name="Pipelines",
+ path="/api/pipelines",
+ table_name="pipelines",
+ incremental_fields=_datetime_incremental_fields(),
+ ),
+ "PipelineStages": ZeroEndpointConfig(
+ name="PipelineStages",
+ path="/api/pipelineStages",
+ table_name="pipeline_stages",
+ incremental_fields=_datetime_incremental_fields(),
+ ),
+ "Notes": ZeroEndpointConfig(
+ name="Notes",
+ path="/api/notes",
+ table_name="notes",
+ incremental_fields=_datetime_incremental_fields(),
+ ),
+ "Tasks": ZeroEndpointConfig(
+ name="Tasks",
+ path="/api/tasks",
+ table_name="tasks",
+ incremental_fields=_datetime_incremental_fields(),
+ ),
+ # The vendor's own docs call this resource "Meetings", but the endpoint they document it under
+ # is /api/calendarEvents (its object schema is titled CalendarEvent) — no /api/meetings exists.
+ "Meetings": ZeroEndpointConfig(
+ name="Meetings",
+ path="/api/calendarEvents",
+ table_name="meetings",
+ incremental_fields=_datetime_incremental_fields(),
+ ),
+ "Memberships": ZeroEndpointConfig(
+ name="Memberships",
+ path="/api/memberships",
+ table_name="memberships",
+ incremental_fields=_datetime_incremental_fields(),
+ ),
+ "Users": ZeroEndpointConfig(
+ name="Users",
+ path="/api/users",
+ table_name="users",
+ scoped_by_workspace=False,
+ incremental_fields=_datetime_incremental_fields(),
+ ),
+}
+
+ENDPOINTS: tuple[str, ...] = tuple(ENDPOINT_CONFIGS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in ENDPOINT_CONFIGS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zero/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zero/source.py
index 61ffec0911a2..c8fef680f4ae 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zero/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zero/source.py
@@ -1,30 +1,129 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zero import ZeroSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.zero.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from products.warehouse_sources.backend.temporal.data_imports.sources.zero.zero import (
+ ZeroResumeConfig,
+ validate_credentials as validate_zero_credentials,
+ zero_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ZeroSource(SimpleSource[ZeroSourceConfig]):
+class ZeroSource(ResumableSource[ZeroSourceConfig, ZeroResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://docs.zero.inc/features/api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ZERO
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Zero API key is invalid or has been revoked. Generate a new key in workspace settings and reconnect.",
+ "403 Client Error": "Your Zero API key is invalid or has been revoked. Generate a new key in workspace settings and reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.zero.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: ZeroSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: ZeroSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if validate_zero_credentials(config.api_key):
+ return True, None
+ return False, "Invalid API key. Check that you copied it from Workspace settings > API keys."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZeroResumeConfig]:
+ return ResumableSourceManager[ZeroResumeConfig](inputs, ZeroResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ZeroSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ZeroResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ resource = zero_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ incremental_field=inputs.incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=["id"],
+ column_hints=resource.column_hints,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.ZERO,
category=DataWarehouseSourceCategory.CRM,
+ releaseStatus=ReleaseStatus.ALPHA,
label="Zero",
+ caption="Connect Zero to sync companies, contacts, deals, and activity into your warehouse. "
+ "Create an API key at [Workspace settings > API keys](https://app.zero.inc/settings/workspace/api).",
+ docsUrl="https://posthog.com/docs/cdp/sources/zero",
iconPath="/static/services/zero.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zero/tests/test_zero.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zero/tests/test_zero.py
new file mode 100644
index 000000000000..c96cc561e5df
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zero/tests/test_zero.py
@@ -0,0 +1,358 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, date, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.zero.zero import (
+ ZeroResumeConfig,
+ _build_where,
+ _format_zero_datetime,
+ get_resource,
+ resolve_workspace_id,
+ validate_credentials,
+ zero_source,
+)
+
+WORKSPACE_ID = "11111111-1111-1111-1111-111111111111"
+
+
+def _make_http_response(body: dict[str, Any] | None, status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body if body is not None else {}).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+class TestFormatZeroDatetime:
+ def test_naive_datetime_gets_utc_timezone(self) -> None:
+ value = datetime(2026, 1, 1, 12, 0, 0)
+ assert _format_zero_datetime(value) == "2026-01-01T12:00:00+00:00"
+
+ def test_aware_datetime_is_converted_to_utc(self) -> None:
+ from datetime import timedelta, timezone
+
+ value = datetime(2026, 1, 1, 12, 0, 0, tzinfo=timezone(timedelta(hours=2)))
+ assert _format_zero_datetime(value) == "2026-01-01T10:00:00+00:00"
+
+ def test_date_is_combined_with_midnight_utc(self) -> None:
+ assert _format_zero_datetime(date(2026, 1, 1)) == "2026-01-01T00:00:00+00:00"
+
+ def test_string_value_passes_through(self) -> None:
+ assert _format_zero_datetime("2026-01-01T00:00:00Z") == "2026-01-01T00:00:00Z"
+
+
+class TestBuildWhere:
+ def test_no_workspace_no_last_value_returns_empty_filter(self) -> None:
+ convert = _build_where(None, "updatedAt")
+ assert json.loads(convert(None)) == {}
+
+ def test_workspace_only_when_no_last_value(self) -> None:
+ convert = _build_where(WORKSPACE_ID, "updatedAt")
+ assert json.loads(convert(None)) == {"workspaceId": WORKSPACE_ID}
+
+ def test_workspace_and_date_filter_combined(self) -> None:
+ convert = _build_where(WORKSPACE_ID, "updatedAt")
+ result = json.loads(convert(datetime(2026, 1, 1, tzinfo=UTC)))
+ assert result == {
+ "workspaceId": WORKSPACE_ID,
+ "updatedAt": {"$gt": "2026-01-01T00:00:00+00:00"},
+ }
+
+ def test_date_filter_without_workspace(self) -> None:
+ # Users has no workspaceId field, so the filter must never include one.
+ convert = _build_where(None, "updatedAt")
+ result = json.loads(convert(datetime(2026, 1, 1, tzinfo=UTC)))
+ assert result == {"updatedAt": {"$gt": "2026-01-01T00:00:00+00:00"}}
+
+ def test_no_date_field_never_adds_a_date_filter(self) -> None:
+ convert = _build_where(WORKSPACE_ID, None)
+ result = json.loads(convert(datetime(2026, 1, 1, tzinfo=UTC)))
+ assert result == {"workspaceId": WORKSPACE_ID}
+
+
+class TestGetResource:
+ @parameterized.expand(
+ [
+ ("Companies", "companies", "/api/companies"),
+ ("Contacts", "contacts", "/api/contacts"),
+ ("Deals", "deals", "/api/deals"),
+ ("Pipelines", "pipelines", "/api/pipelines"),
+ ("PipelineStages", "pipeline_stages", "/api/pipelineStages"),
+ ("Notes", "notes", "/api/notes"),
+ ("Tasks", "tasks", "/api/tasks"),
+ ("Meetings", "meetings", "/api/calendarEvents"),
+ ("Memberships", "memberships", "/api/memberships"),
+ ("Workspaces", "workspaces", "/api/workspaces"),
+ ("Users", "users", "/api/users"),
+ ]
+ )
+ def test_endpoint_name_maps_to_table_and_path(self, endpoint: str, table_name: str, path: str) -> None:
+ resource = get_resource(endpoint, WORKSPACE_ID, should_use_incremental_field=False, incremental_field=None)
+ assert resource["table_name"] == table_name
+ endpoint_config = resource["endpoint"]
+ assert isinstance(endpoint_config, dict)
+ assert endpoint_config["path"] == path
+ assert resource["primary_key"] == ["id"]
+
+ def test_full_refresh_scoped_endpoint_filters_by_workspace_only(self) -> None:
+ resource = get_resource("Companies", WORKSPACE_ID, should_use_incremental_field=False, incremental_field=None)
+ endpoint_config = resource["endpoint"]
+ assert isinstance(endpoint_config, dict)
+ params = endpoint_config["params"]
+ assert isinstance(params, dict)
+ where = params["where"]
+ order_by = params["orderBy"]
+ assert isinstance(where, str)
+ assert isinstance(order_by, str)
+ assert json.loads(where) == {"workspaceId": WORKSPACE_ID}
+ assert json.loads(order_by) == {"createdAt": "asc"}
+ assert resource["write_disposition"] == "replace"
+
+ def test_full_refresh_users_endpoint_has_no_workspace_filter(self) -> None:
+ resource = get_resource("Users", WORKSPACE_ID, should_use_incremental_field=False, incremental_field=None)
+ endpoint_config = resource["endpoint"]
+ assert isinstance(endpoint_config, dict)
+ params = endpoint_config["params"]
+ assert isinstance(params, dict)
+ assert "where" not in params
+
+ def test_incremental_uses_chosen_field_for_filter_and_sort(self) -> None:
+ resource = get_resource(
+ "Companies", WORKSPACE_ID, should_use_incremental_field=True, incremental_field="createdAt"
+ )
+ endpoint_config = resource["endpoint"]
+ assert isinstance(endpoint_config, dict)
+ params = endpoint_config["params"]
+ assert isinstance(params, dict)
+ where = params["where"]
+ order_by = params["orderBy"]
+ assert isinstance(where, dict)
+ assert isinstance(order_by, str)
+ assert where["cursor_path"] == "createdAt" # ty: ignore[invalid-key]
+ assert json.loads(order_by) == {"createdAt": "asc"}
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+
+ def test_incremental_field_falls_back_to_first_advertised_option(self) -> None:
+ resource = get_resource(
+ "Companies", WORKSPACE_ID, should_use_incremental_field=True, incremental_field="not_a_real_field"
+ )
+ endpoint_config = resource["endpoint"]
+ assert isinstance(endpoint_config, dict)
+ params = endpoint_config["params"]
+ assert isinstance(params, dict)
+ where = params["where"]
+ assert isinstance(where, dict)
+ assert where["cursor_path"] == "updatedAt" # ty: ignore[invalid-key]
+
+ def test_incremental_convert_omits_workspace_for_users(self) -> None:
+ resource = get_resource("Users", WORKSPACE_ID, should_use_incremental_field=True, incremental_field="updatedAt")
+ endpoint_config = resource["endpoint"]
+ assert isinstance(endpoint_config, dict)
+ params = endpoint_config["params"]
+ assert isinstance(params, dict)
+ where = params["where"]
+ assert isinstance(where, dict)
+ convert = where["convert"] # ty: ignore[invalid-key]
+ assert convert is not None
+ assert json.loads(convert(None)) == {}
+
+ def test_workspaces_endpoint_never_goes_incremental(self) -> None:
+ # Workspaces declares no incremental_fields, so should_use_incremental_field=True must
+ # still fall through to a plain, full-refresh where filter.
+ resource = get_resource("Workspaces", WORKSPACE_ID, should_use_incremental_field=True, incremental_field=None)
+ endpoint_config = resource["endpoint"]
+ assert isinstance(endpoint_config, dict)
+ params = endpoint_config["params"]
+ assert isinstance(params, dict)
+ assert "where" not in params
+ assert resource["write_disposition"] == "replace"
+
+ def test_paginator_uses_the_documented_default_limit(self) -> None:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ OffsetPaginator,
+ )
+
+ resource = get_resource("Companies", WORKSPACE_ID, should_use_incremental_field=False, incremental_field=None)
+ endpoint_config = resource["endpoint"]
+ assert isinstance(endpoint_config, dict)
+ paginator = endpoint_config["paginator"]
+ assert isinstance(paginator, OffsetPaginator)
+ assert paginator.limit == 100
+ assert paginator.total_path == "total"
+
+
+class TestResolveWorkspaceId:
+ def test_returns_the_single_workspace_id(self) -> None:
+ response = _make_http_response({"data": [{"id": WORKSPACE_ID}], "total": 1})
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zero.zero.make_tracked_session"
+ ) as mock_make_session:
+ mock_make_session.return_value.get.return_value = response
+ assert resolve_workspace_id("api-key") == WORKSPACE_ID
+
+ def test_raises_when_key_has_multiple_workspaces(self) -> None:
+ response = _make_http_response(
+ {"data": [{"id": WORKSPACE_ID}, {"id": "22222222-2222-2222-2222-222222222222"}], "total": 2}
+ )
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zero.zero.make_tracked_session"
+ ) as mock_make_session:
+ mock_make_session.return_value.get.return_value = response
+ with pytest.raises(ValueError, match="access to multiple workspaces"):
+ resolve_workspace_id("api-key")
+
+ def test_raises_when_key_has_no_workspace(self) -> None:
+ response = _make_http_response({"data": [], "total": 0})
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zero.zero.make_tracked_session"
+ ) as mock_make_session:
+ mock_make_session.return_value.get.return_value = response
+ with pytest.raises(ValueError, match="isn't a member of any workspace"):
+ resolve_workspace_id("api-key")
+
+ def test_raises_on_http_error(self) -> None:
+ response = _make_http_response(None, status_code=401)
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zero.zero.make_tracked_session"
+ ) as mock_make_session:
+ mock_make_session.return_value.get.return_value = response
+ with pytest.raises(requests.HTTPError):
+ resolve_workspace_id("api-key")
+
+
+class TestValidateCredentials:
+ @parameterized.expand([(200, True), (401, False), (403, False), (500, False)])
+ def test_maps_status_code_to_validity(self, status_code: int, expected: bool) -> None:
+ response = _make_http_response({"data": []}, status_code=status_code)
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zero.zero.make_tracked_session"
+ ) as mock_make_session:
+ mock_make_session.return_value.get.return_value = response
+ assert validate_credentials("api-key") is expected
+
+
+class TestZeroSourceResumeBehavior:
+ """End-to-end resume behaviour of ``zero_source`` via ``rest_api_resource``."""
+
+ def _drive(
+ self, endpoint: str, manager: MagicMock, responses: list[Response], should_use_incremental_field: bool = False
+ ) -> tuple[list[list[dict[str, Any]]], list[int | None]]:
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zero.zero.resolve_workspace_id",
+ return_value=WORKSPACE_ID,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as mock_session,
+ ):
+ mock_session.return_value.headers = {}
+ mock_session.return_value.prepare_request.side_effect = lambda req: req
+ mock_session.return_value.send.side_effect = fake_send
+
+ resource = zero_source(
+ api_key="test-key",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ should_use_incremental_field=should_use_incremental_field,
+ )
+ pages = list(cast(Iterable[list[dict[str, Any]]], resource))
+
+ offsets_sent = [p.get("offset") for p in sent_params]
+ return pages, offsets_sent
+
+ def test_fresh_run_saves_offset_after_each_non_terminal_page(self) -> None:
+ # The offset paginator's default limit is 100, so a non-terminal page must carry a full
+ # 100 rows — anything smaller would (correctly) be read as the last page and stop pagination.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response({"data": [{"id": f"c{i}"} for i in range(100)], "total": 250}),
+ _make_http_response({"data": [{"id": f"c{i}"} for i in range(100, 200)], "total": 250}),
+ _make_http_response({"data": [{"id": f"c{i}"} for i in range(200, 250)], "total": 250}),
+ ]
+ pages, offsets_sent = self._drive("Companies", manager, responses)
+
+ assert offsets_sent == [0, 100, 200]
+ assert [row["id"] for page in pages for row in page] == [f"c{i}" for i in range(250)]
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [ZeroResumeConfig(offset=100), ZeroResumeConfig(offset=200)]
+
+ def test_resume_seeds_paginator_with_saved_offset(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ZeroResumeConfig(offset=200)
+
+ responses = [_make_http_response({"data": [{"id": "c4"}], "total": 201})]
+ _, offsets_sent = self._drive("Companies", manager, responses)
+
+ assert offsets_sent == [200]
+ manager.load_state.assert_called_once()
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"data": [{"id": "only"}], "total": 1})]
+ self._drive("Companies", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_scoped_endpoint_sends_workspace_where_filter(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"data": [{"id": "c1"}], "total": 1})]
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zero.zero.resolve_workspace_id",
+ return_value=WORKSPACE_ID,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as mock_session,
+ ):
+ mock_session.return_value.headers = {}
+ mock_session.return_value.prepare_request.side_effect = lambda req: req
+ mock_session.return_value.send.side_effect = fake_send
+
+ resource = zero_source(
+ api_key="test-key",
+ endpoint="Companies",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ should_use_incremental_field=False,
+ )
+ list(cast(Iterable[Any], resource))
+
+ assert json.loads(sent_params[0]["where"]) == {"workspaceId": WORKSPACE_ID}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zero/tests/test_zero_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zero/tests/test_zero_source.py
new file mode 100644
index 000000000000..e9771e2c293c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zero/tests/test_zero_source.py
@@ -0,0 +1,144 @@
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zero import ZeroSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.zero.settings import ENDPOINT_CONFIGS, ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.zero.source import ZeroSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.zero.zero import ZeroResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = {name for name, config in ENDPOINT_CONFIGS.items() if config.incremental_fields}
+
+
+class TestZeroSource:
+ def setup_method(self) -> None:
+ self.source = ZeroSource()
+ self.team_id = 123
+ self.config = ZeroSourceConfig(api_key="api_test")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.ZERO
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Zero"
+ assert config.label == "Zero"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/zero.png"
+ assert config.category == DataWarehouseSourceCategory.CRM
+ assert len(config.fields) == 1
+
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static endpoint catalog with no I/O, so the public docs can render it.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_lists_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))
+ def test_get_schemas_incremental_flags(self, endpoint: str) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ expected_incremental = endpoint in INCREMENTAL_ENDPOINTS
+ assert schema.supports_incremental is expected_incremental
+ assert schema.supports_append is expected_incremental
+ if expected_incremental:
+ assert len(schema.incremental_fields) >= 1
+ else:
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Companies"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "Companies"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ @pytest.mark.parametrize(
+ ("mock_return", "expected_valid"),
+ [(True, True), (False, False)],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zero.source.validate_zero_credentials"
+ )
+ def test_validate_credentials(self, mock_validate: MagicMock, mock_return: bool, expected_valid: bool) -> None:
+ 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 is None) is expected_valid
+ mock_validate.assert_called_once_with("api_test")
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_resumable_source_manager_binds_data_class(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ZeroResumeConfig
+
+ def test_get_canonical_descriptions_covers_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.zero.source.zero_source")
+ def test_source_for_pipeline_plumbs_inputs(self, mock_zero_source: MagicMock) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ inputs = MagicMock()
+ inputs.schema_name = "Companies"
+ inputs.team_id = 7
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.incremental_field = "updatedAt"
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00+00:00"
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_zero_source.assert_called_once_with(
+ api_key="api_test",
+ endpoint="Companies",
+ team_id=7,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ incremental_field="updatedAt",
+ db_incremental_field_last_value="2026-01-01T00:00:00+00:00",
+ )
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.zero.source.zero_source")
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self, mock_zero_source: MagicMock) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ inputs = MagicMock()
+ inputs.schema_name = "Users"
+ inputs.team_id = 7
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = False
+ inputs.incremental_field = None
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00+00:00"
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ assert mock_zero_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zero/zero.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zero/zero.py
new file mode 100644
index 000000000000..e6b5ba2be55e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zero/zero.py
@@ -0,0 +1,192 @@
+import json
+from collections.abc import Callable
+from datetime import UTC, date, datetime
+from typing import Any, Optional, cast
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ OffsetPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import 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
+from products.warehouse_sources.backend.temporal.data_imports.sources.zero.settings import (
+ ENDPOINT_CONFIGS,
+ ZERO_BASE_URL,
+)
+
+PAGE_LIMIT = 100
+
+
+@frozen
+class ZeroResumeConfig:
+ offset: int
+
+
+def _format_zero_datetime(value: Any) -> str:
+ """Format an incremental cursor as the ISO 8601 string Zero's `$gt` date operator expects."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).isoformat()
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()
+ return str(value)
+
+
+def _build_where(workspace_id: Optional[str], date_field: Optional[str]) -> Callable[[Any], str]:
+ """Build the `convert` callable for the declarative incremental `where` param.
+
+ Zero's `where` filter is a single JSON-encoded object, so the static workspace scope and the
+ dynamic incremental cursor have to be merged into one value here rather than sent as two
+ separate query params.
+ """
+
+ def convert(last_value: Any) -> str:
+ where: dict[str, Any] = {}
+ if workspace_id is not None:
+ where["workspaceId"] = workspace_id
+ if date_field is not None and last_value is not None:
+ where[date_field] = {"$gt": _format_zero_datetime(last_value)}
+ return json.dumps(where)
+
+ return convert
+
+
+def get_resource(
+ endpoint: str,
+ workspace_id: str,
+ should_use_incremental_field: bool,
+ incremental_field: Optional[str],
+) -> EndpointResource:
+ config = ENDPOINT_CONFIGS[endpoint]
+ is_incremental = should_use_incremental_field and bool(config.incremental_fields)
+ scoped_workspace_id = workspace_id if config.scoped_by_workspace else None
+
+ # Stable, ascending sort so offset pagination doesn't skip or duplicate rows as new records
+ # are created mid-sync — createdAt never changes, so new rows always land after the current
+ # offset. Incremental syncs instead sort on the cursor field, matching SourceResponse.sort_mode.
+ sort_field = "createdAt"
+ params: dict[str, Any] = {}
+
+ if is_incremental:
+ advertised = {incremental["field"] for incremental in config.incremental_fields}
+ cursor = (
+ incremental_field
+ if incremental_field is not None and incremental_field in advertised
+ else config.incremental_fields[0]["field"]
+ )
+ sort_field = cursor
+ params["where"] = {
+ "type": "incremental",
+ "cursor_path": cursor,
+ "initial_value": None,
+ "convert": _build_where(scoped_workspace_id, cursor),
+ }
+ elif scoped_workspace_id is not None:
+ params["where"] = json.dumps({"workspaceId": scoped_workspace_id})
+
+ params["orderBy"] = json.dumps({sort_field: "asc"})
+
+ return {
+ "name": config.name,
+ "table_name": config.table_name,
+ "primary_key": ["id"],
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if is_incremental else "replace",
+ "endpoint": {
+ "path": config.path,
+ "data_selector": "data",
+ "data_selector_required": True,
+ "params": params,
+ "paginator": OffsetPaginator(limit=PAGE_LIMIT, total_path="total"),
+ },
+ "table_format": "delta",
+ }
+
+
+def resolve_workspace_id(api_key: str) -> str:
+ """Resolve the workspace this API key belongs to.
+
+ Most Zero resources are workspace-scoped and require an explicit `where={"workspaceId": ...}`
+ filter, so the sync resolves the workspace once up front. `GET /api/workspaces` returns every
+ workspace the key can see, unfiltered — for a key with access to more than one, taking the
+ first result would pick an unintended workspace boundary silently, so this fails loud instead
+ and asks for a key scoped to a single workspace.
+ """
+ session = make_tracked_session(redact_values=(api_key,))
+ response = session.get(
+ f"{ZERO_BASE_URL}/api/workspaces",
+ headers={"Authorization": f"Bearer {api_key}"},
+ params={"fields": "id"},
+ timeout=10,
+ )
+ response.raise_for_status()
+ data = response.json().get("data") or []
+ if not data:
+ raise ValueError("This Zero API key isn't a member of any workspace.")
+ if len(data) > 1:
+ raise ValueError(
+ "This Zero API key has access to multiple workspaces. Use an API key scoped to a "
+ "single workspace so PostHog imports data from the intended workspace only."
+ )
+ return cast(str, data[0]["id"])
+
+
+def validate_credentials(api_key: str) -> bool:
+ ok, _status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,)),
+ f"{ZERO_BASE_URL}/api/workspaces",
+ headers={"Authorization": f"Bearer {api_key}"},
+ )
+ return ok
+
+
+def zero_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ZeroResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ incremental_field: Optional[str] = None,
+ should_use_incremental_field: bool = False,
+) -> Resource:
+ workspace_id = resolve_workspace_id(api_key)
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": ZERO_BASE_URL,
+ "auth": {"type": "bearer", "token": api_key},
+ },
+ "resource_defaults": {
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if should_use_incremental_field
+ else "replace",
+ },
+ "resources": [get_resource(endpoint, workspace_id, should_use_incremental_field, incremental_field)],
+ }
+
+ 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 = {"offset": resume_config.offset}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and "offset" in state:
+ resumable_source_manager.save_state(ZeroResumeConfig(offset=int(state["offset"])))
+
+ return rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )