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): implement segment import source (#65645)

Tom Owers0547568ba4fa
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 22ed017d70c8..1137bb152ae4 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -186,6 +186,7 @@ the row lists both.
| rollbar | HTTP | requests | ✅ |
| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |
| salesloft | HTTP | requests | ✅ |
+| segment | HTTP | requests | ✅ |
| sendgrid | HTTP | requests | ✅ |
| sentry | HTTP | requests + `rest_source.RESTClient` | ✅ |
| servicenow | HTTP | requests | ✅ |
@@ -613,7 +614,6 @@ doesn't conflict with concurrent PRs.
- savvycal
- search_ads_360
- secoda
-- segment
- sendowl
- sendpulse
- senseforce
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 62dd788309f7..8400fb4a73c8 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -2753,7 +2753,8 @@ class SecodaSourceConfig(config.Config):
@config.config
class SegmentSourceConfig(config.Config):
- pass
+ api_token: str
+ region: Literal["api", "eu1"] = config.value(default="api")
@config.config
diff --git a/posthog/temporal/data_imports/sources/segment/canonical_descriptions.py b/posthog/temporal/data_imports/sources/segment/canonical_descriptions.py
new file mode 100644
index 000000000000..790810a4e04d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/segment/canonical_descriptions.py
@@ -0,0 +1,122 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Descriptions are taken from the Twilio Segment Public API docs (https://docs.segmentapis.com). The
+# Public API is the workspace configuration/admin/metadata API, not the event or Profile data plane.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "workspace": {
+ "description": "The Segment workspace associated with the Public API token used to connect.",
+ "docs_url": "https://docs.segmentapis.com/tag/Workspaces",
+ "columns": {
+ "id": "Unique identifier for the workspace.",
+ "name": "Human-readable name of the workspace.",
+ "slug": "URL-friendly slug for the workspace.",
+ },
+ },
+ "sources": {
+ "description": "Sources configured in the workspace — the integrations that send data into Segment.",
+ "docs_url": "https://docs.segmentapis.com/tag/Sources",
+ "columns": {
+ "id": "Unique identifier for the source.",
+ "slug": "URL-friendly slug for the source.",
+ "name": "Human-readable name of the source.",
+ "workspaceId": "Identifier of the workspace the source belongs to.",
+ "enabled": "Whether the source is currently enabled.",
+ "metadata": "Catalog metadata describing the source type (id, slug, name, categories, logos).",
+ "settings": "Source-specific configuration settings.",
+ "labels": "Labels applied to the source.",
+ },
+ },
+ "destinations": {
+ "description": "Destinations configured in the workspace — where Segment forwards collected data.",
+ "docs_url": "https://docs.segmentapis.com/tag/Destinations",
+ "columns": {
+ "id": "Unique identifier for the destination.",
+ "name": "Human-readable name of the destination.",
+ "sourceId": "Identifier of the source feeding this destination.",
+ "enabled": "Whether the destination is currently enabled.",
+ "metadata": "Catalog metadata describing the destination type.",
+ },
+ },
+ "warehouses": {
+ "description": "Warehouse connections configured in the workspace (e.g. Redshift, BigQuery, Snowflake).",
+ "docs_url": "https://docs.segmentapis.com/tag/Warehouses",
+ "columns": {
+ "id": "Unique identifier for the warehouse connection.",
+ "workspaceId": "Identifier of the workspace the warehouse belongs to.",
+ "enabled": "Whether the warehouse connection is currently enabled.",
+ "metadata": "Catalog metadata describing the warehouse type.",
+ },
+ },
+ "tracking_plans": {
+ "description": "Tracking plans that define the expected events and properties for the workspace.",
+ "docs_url": "https://docs.segmentapis.com/tag/Tracking-Plans",
+ "columns": {
+ "id": "Unique identifier for the tracking plan.",
+ "name": "Human-readable name of the tracking plan.",
+ "type": "The type of tracking plan.",
+ "updatedAt": "When the tracking plan was last updated.",
+ "createdAt": "When the tracking plan was created.",
+ },
+ },
+ "transformations": {
+ "description": "Transformations that modify events in-flight before they reach destinations.",
+ "docs_url": "https://docs.segmentapis.com/tag/Transformations",
+ "columns": {
+ "id": "Unique identifier for the transformation.",
+ "name": "Human-readable name of the transformation.",
+ "sourceId": "Identifier of the source the transformation applies to.",
+ "enabled": "Whether the transformation is currently enabled.",
+ },
+ },
+ "reverse_etl_models": {
+ "description": "Reverse ETL models — the queries that extract data from a warehouse to send to destinations.",
+ "docs_url": "https://docs.segmentapis.com/tag/Reverse-ETL",
+ "columns": {
+ "id": "Unique identifier for the Reverse ETL model.",
+ "sourceId": "Identifier of the Reverse ETL source the model belongs to.",
+ "name": "Human-readable name of the model.",
+ "enabled": "Whether the model is currently enabled.",
+ "query": "The SQL query defining the model.",
+ },
+ },
+ "iam_users": {
+ "description": "IAM users with access to the workspace.",
+ "docs_url": "https://docs.segmentapis.com/tag/IAM-Users",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "name": "The user's name.",
+ "email": "The user's email address.",
+ },
+ },
+ "iam_groups": {
+ "description": "IAM user groups defined in the workspace.",
+ "docs_url": "https://docs.segmentapis.com/tag/IAM-Groups",
+ "columns": {
+ "id": "Unique identifier for the user group.",
+ "name": "Human-readable name of the group.",
+ "memberCount": "Number of members in the group.",
+ },
+ },
+ "labels": {
+ "description": "Labels defined in the workspace, used to tag and organize sources and other resources.",
+ "docs_url": "https://docs.segmentapis.com/tag/Labels",
+ "columns": {
+ "key": "The label key (e.g. `environment`).",
+ "value": "The label value (e.g. `dev`).",
+ "description": "Optional description of the label.",
+ },
+ },
+ "audit_events": {
+ "description": "Workspace audit trail — a log of configuration and access events.",
+ "docs_url": "https://docs.segmentapis.com/tag/Audit-Trail",
+ "columns": {
+ "id": "Unique identifier for the audit event.",
+ "timestamp": "When the event occurred (ISO 8601).",
+ "type": "The type of audit event.",
+ "actor": "The user or token that performed the action.",
+ "resourceId": "Identifier of the resource the event acted on.",
+ "resourceType": "The type of resource the event acted on.",
+ "resourceName": "Name of the resource the event acted on.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/segment/segment.py b/posthog/temporal/data_imports/sources/segment/segment.py
new file mode 100644
index 000000000000..b1a63532b7ce
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/segment/segment.py
@@ -0,0 +1,195 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import quote
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.segment.settings import (
+ REGION_BASE_URLS,
+ SEGMENT_ENDPOINTS,
+ SegmentEndpointConfig,
+)
+
+# Segment's Public API caps a page at 1000 items (default 200). We request the max to minimize the
+# number of round-trips while staying within documented limits and well clear of the lower per-endpoint
+# rate caps (some endpoints are throttled to 250 req/min).
+PAGE_SIZE = 200
+
+
+class SegmentRetryableError(Exception):
+ pass
+
+
+class SegmentResumeConfig:
+ # Opaque base64 cursor (`data.pagination.next`) for the next page of the endpoint being synced.
+ cursor: str
+
+
+def _base_url(region: str) -> str:
+ return REGION_BASE_URLS.get(region, REGION_BASE_URLS["api"])
+
+
+def _headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _build_url(base_url: str, path: str, cursor: str | None) -> str:
+ """Build a list URL with Segment's pagination query params.
+
+ Segment uses bracketed keys (`pagination[count]`, `pagination[cursor]`). The keys are constructed
+ internally so they're left literal; only the opaque cursor value (base64, contains `=`) is encoded.
+ """
+ params = [f"pagination[count]={PAGE_SIZE}"]
+ if cursor:
+ params.append(f"pagination[cursor]={quote(cursor, safe='')}")
+ return f"{base_url}{path}?{'&'.join(params)}"
+
+
+@retry(
+ retry=retry_if_exception_type((SegmentRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, headers=headers, timeout=60)
+
+ # 429 (rate limit) and 5xx are transient; back off and retry.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SegmentRetryableError(f"Segment API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Segment API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _extract_rows(data: dict[str, Any]) -> list[dict[str, Any]]:
+ """Pull the resource array out of a Segment list response.
+
+ The body is `{"data": {"<resource>": [...], "pagination": {...}}}`. The resource key varies and
+ doesn't always match the endpoint name (e.g. `/audit-events` returns `events`, `/labels` returns
+ `labels`), so we take the single list-valued entry under `data` rather than hardcoding the key.
+ """
+ payload = data.get("data", {})
+ if not isinstance(payload, dict):
+ return []
+ for key, value in payload.items():
+ if key == "pagination":
+ continue
+ if isinstance(value, list):
+ return value
+ return []
+
+
+def _redact_rows(rows: list[dict[str, Any]], redacted_fields: frozenset[str]) -> list[dict[str, Any]]:
+ """Drop credential-like top-level fields (e.g. destination `settings`, source `writeKeys`) so
+ they never land in a queryable warehouse table. See `SegmentEndpointConfig.redacted_fields`.
+ """
+ if not redacted_fields:
+ return rows
+ return [
+ {key: value for key, value in row.items() if key not in redacted_fields} if isinstance(row, dict) else row
+ for row in rows
+ ]
+
+
+def _next_cursor(data: dict[str, Any]) -> str | None:
+ payload = data.get("data", {})
+ pagination = payload.get("pagination", {}) if isinstance(payload, dict) else {}
+ next_cursor = pagination.get("next") if isinstance(pagination, dict) else None
+ return next_cursor or None
+
+
+def get_rows(
+ api_token: str,
+ region: str,
+ config: SegmentEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SegmentResumeConfig],
+) -> Iterator[Any]:
+ base_url = _base_url(region)
+ headers = _headers(api_token)
+ # One session reused across pages so urllib3 keeps the connection alive instead of re-handshaking.
+ # `redact_values` masks the bearer token in tracked request logs and captured HTTP samples.
+ session = make_tracked_session(redact_values=(api_token,))
+
+ # `GET /` (Get Workspace) returns a single object, not a paginated list.
+ if config.single_object_key is not None:
+ data = _fetch(session, f"{base_url}{config.path}", headers, logger)
+ obj = data.get("data", {}).get(config.single_object_key)
+ if obj:
+ yield _redact_rows([obj], config.redacted_fields)
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = resume.cursor if resume else None
+ if cursor:
+ logger.debug(f"Segment: resuming {config.name} from cursor={cursor}")
+
+ while True:
+ url = _build_url(base_url, config.path, cursor)
+ data = _fetch(session, url, headers, logger)
+
+ rows = _extract_rows(data)
+ if rows:
+ yield _redact_rows(rows, config.redacted_fields)
+
+ cursor = _next_cursor(data)
+ if not cursor:
+ break
+
+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on the primary key)
+ # rather than skipping it.
+ resumable_source_manager.save_state(SegmentResumeConfig(cursor=cursor))
+
+
+def segment_source(
+ api_token: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SegmentResumeConfig],
+) -> SourceResponse:
+ config = SEGMENT_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ region=region,
+ config=config,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def validate_credentials(api_token: str, region: str) -> bool:
+ """Cheapest probe that a token is genuine: Get Workspace (`GET /`) for the token's region."""
+ try:
+ response = make_tracked_session(redact_values=(api_token,)).get(
+ f"{_base_url(region)}/",
+ headers=_headers(api_token),
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
diff --git a/posthog/temporal/data_imports/sources/segment/settings.py b/posthog/temporal/data_imports/sources/segment/settings.py
new file mode 100644
index 000000000000..4925404c7d88
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/segment/settings.py
@@ -0,0 +1,69 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField
+
+# Twilio Segment exposes two regional hosts for the same workspace-scoped Public API. The token is
+# bound to one region, so the user picks it at connect time (Airbyte models this as `region: api|eu1`).
+REGION_BASE_URLS: dict[str, str] = {
+ "api": "https://api.segmentapis.com",
+ "eu1": "https://eu1.api.segmentapis.com",
+}
+DEFAULT_REGION = "api"
+
+
+@dataclass
+class SegmentEndpointConfig:
+ name: str
+ path: str
+ # Keys must be unique table-wide. Most resources expose a global `id`; labels have none, so they
+ # use the natural (key, value) composite.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # `GET /` (Get Workspace) returns a single object under `data.<object_key>` with no pagination,
+ # rather than a paginated list. Such endpoints yield exactly one row.
+ single_object_key: Optional[str] = None
+ # A stable, immutable datetime field to partition on. Segment's config/admin objects carry no
+ # timestamps, so only audit events (immutable `timestamp`) set this.
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ should_sync_default: bool = True
+ # Top-level fields stripped from every row before it's persisted. Segment's config endpoints
+ # embed credential-like blobs — destination/warehouse connection `settings` (third-party API
+ # keys, DB passwords) and source `writeKeys`. These are free-form per integration, so there's
+ # no reliable allowlist of safe sub-keys; we drop the whole field rather than risk leaking
+ # secrets into a queryable warehouse table.
+ redacted_fields: frozenset[str] = field(default_factory=frozenset)
+
+
+# The Segment Public API is a workspace configuration/admin/usage API (not the event/Profile data
+# plane). Every listing endpoint uses cursor pagination (`pagination[count]` / `pagination[cursor]`)
+# and wraps its rows in `{"data": {"<resource>": [...], "pagination": {...}}}`.
+#
+# These resources expose no server-side timestamp filter, so they are full refresh only. Audit events
+# document `startTime`/`endTime` filters and so are a future incremental candidate, but that needs a
+# live-token smoke test (future-date cutoff) to confirm the filter is honored before we enable it.
+SEGMENT_ENDPOINTS: dict[str, SegmentEndpointConfig] = {
+ "workspace": SegmentEndpointConfig(
+ name="workspace",
+ path="/",
+ single_object_key="workspace",
+ ),
+ "sources": SegmentEndpointConfig(name="sources", path="/sources", redacted_fields=frozenset({"writeKeys"})),
+ "destinations": SegmentEndpointConfig(
+ name="destinations", path="/destinations", redacted_fields=frozenset({"settings"})
+ ),
+ "warehouses": SegmentEndpointConfig(name="warehouses", path="/warehouses", redacted_fields=frozenset({"settings"})),
+ "tracking_plans": SegmentEndpointConfig(name="tracking_plans", path="/tracking-plans"),
+ "transformations": SegmentEndpointConfig(name="transformations", path="/transformations"),
+ "reverse_etl_models": SegmentEndpointConfig(name="reverse_etl_models", path="/reverse-etl-models"),
+ "iam_users": SegmentEndpointConfig(name="iam_users", path="/users"),
+ "iam_groups": SegmentEndpointConfig(name="iam_groups", path="/groups"),
+ "labels": SegmentEndpointConfig(name="labels", path="/labels", primary_keys=["key", "value"]),
+ "audit_events": SegmentEndpointConfig(name="audit_events", path="/audit-events", partition_key="timestamp"),
+}
+
+ENDPOINTS = tuple(SEGMENT_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in SEGMENT_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/segment/source.py b/posthog/temporal/data_imports/sources/segment/source.py
index c39f019cf514..0c77c2d346d4 100644
--- a/posthog/temporal/data_imports/sources/segment/source.py
+++ b/posthog/temporal/data_imports/sources/segment/source.py
@@ -1,20 +1,41 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import SegmentSourceConfig
+from posthog.temporal.data_imports.sources.segment.canonical_descriptions import CANONICAL_DESCRIPTIONS
+from posthog.temporal.data_imports.sources.segment.segment import (
+ SegmentResumeConfig,
+ segment_source,
+ validate_credentials as validate_segment_credentials,
+)
+from posthog.temporal.data_imports.sources.segment.settings import (
+ DEFAULT_REGION,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ SEGMENT_ENDPOINTS,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SegmentSource(SimpleSource[SegmentSourceConfig]):
+class SegmentSource(ResumableSource[SegmentSourceConfig, SegmentResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SEGMENT
@@ -25,7 +46,101 @@ class SegmentSource(SimpleSource[SegmentSourceConfig]):
name=SchemaExternalDataSourceType.SEGMENT,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Segment",
- iconPath="/static/services/segment.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter a Twilio Segment workspace-scoped Public API token to pull your Segment workspace configuration into the PostHog Data warehouse.
+
+Create a **Public API token** in your Segment workspace under **Settings → Access Management → Tokens**, and pick the region your workspace lives in.
+
+This connects to the Segment **Public API** (workspace configuration, admin, and metadata) — not the event or Profile data plane.""",
+ iconPath="/static/services/segment.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/segment",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue=DEFAULT_REGION,
+ options=[
+ SourceFieldSelectConfigOption(label="US (api.segmentapis.com)", value="api"),
+ SourceFieldSelectConfigOption(label="EU (eu1.api.segmentapis.com)", value="eu1"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="Public API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid, revoked, or insufficiently-scoped Public API token surfaces as a requests
+ # HTTPError when `_fetch` calls `raise_for_status()`. Retrying can never fix a credential
+ # problem, so stop the sync. Segment returns 401 when the header is missing and 403 for a
+ # token that's present but not authorized; match the stable status text only.
+ "401 Client Error: Unauthorized for url": "Your Segment Public API token is missing or invalid. Create a new Public API token in your Segment workspace settings, then reconnect.",
+ "403 Client Error: Forbidden for url": "Your Segment Public API token is invalid, revoked, or missing the permissions needed to sync this data. Create a new token with the required access in your Segment workspace settings, then reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SegmentSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # The Segment Public API exposes no server-side timestamp filter on these resources, so every
+ # endpoint is full refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=SEGMENT_ENDPOINTS[endpoint].should_sync_default,
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: SegmentSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_segment_credentials(config.api_token, config.region):
+ return True, None
+
+ return False, "Invalid Segment Public API token, or wrong region selected for this token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SegmentResumeConfig]:
+ return ResumableSourceManager[SegmentResumeConfig](inputs, SegmentResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SegmentSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SegmentResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return segment_source(
+ api_token=config.api_token,
+ region=config.region,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/posthog/temporal/data_imports/sources/segment/tests/test_segment.py b/posthog/temporal/data_imports/sources/segment/tests/test_segment.py
new file mode 100644
index 000000000000..b72b003530e6
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/segment/tests/test_segment.py
@@ -0,0 +1,276 @@
+from typing import Any
+
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.segment import segment
+from posthog.temporal.data_imports.sources.segment.segment import (
+ PAGE_SIZE,
+ SegmentResumeConfig,
+ _base_url,
+ _build_url,
+ _extract_rows,
+ _next_cursor,
+ _redact_rows,
+ get_rows,
+ segment_source,
+)
+from posthog.temporal.data_imports.sources.segment.settings import REGION_BASE_URLS, SEGMENT_ENDPOINTS
+
+
+class _FakeResumableManager:
+ """In-memory stand-in for ResumableSourceManager that records saved state."""
+
+ def __init__(self, state: SegmentResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[SegmentResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> SegmentResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: SegmentResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestBaseUrl:
+ @parameterized.expand(
+ [
+ ("us", "api", "https://api.segmentapis.com"),
+ ("eu", "eu1", "https://eu1.api.segmentapis.com"),
+ # An unknown region falls back to the US host rather than building a broken URL.
+ ("unknown", "mars", "https://api.segmentapis.com"),
+ ]
+ )
+ def test_base_url(self, _name: str, region: str, expected: str) -> None:
+ assert _base_url(region) == expected
+
+ def test_both_documented_regions_are_covered(self) -> None:
+ assert set(REGION_BASE_URLS) == {"api", "eu1"}
+
+
+class TestBuildUrl:
+ def test_first_page_has_count_and_no_cursor(self) -> None:
+ url = _build_url("https://api.segmentapis.com", "/sources", None)
+ assert url == f"https://api.segmentapis.com/sources?pagination[count]={PAGE_SIZE}"
+
+ def test_cursor_is_url_encoded(self) -> None:
+ # Segment cursors are base64 and contain `=` padding, which must be percent-encoded in a query value.
+ url = _build_url("https://api.segmentapis.com", "/sources", "Mw==")
+ assert url == f"https://api.segmentapis.com/sources?pagination[count]={PAGE_SIZE}&pagination[cursor]=Mw%3D%3D"
+
+ def test_bracket_keys_stay_literal(self) -> None:
+ # Segment expects literal brackets in the pagination keys, not percent-encoded ones.
+ url = _build_url("https://api.segmentapis.com", "/labels", "abc")
+ assert "pagination[count]" in url
+ assert "%5B" not in url
+
+
+class TestExtractRows:
+ @parameterized.expand(
+ [
+ ("sources_key", {"data": {"sources": [{"id": "s1"}], "pagination": {}}}, [{"id": "s1"}]),
+ # The array key isn't always the endpoint name: audit-events returns it under "events".
+ ("events_key", {"data": {"events": [{"id": "e1"}], "pagination": {}}}, [{"id": "e1"}]),
+ ("labels_key", {"data": {"labels": [{"key": "env", "value": "dev"}]}}, [{"key": "env", "value": "dev"}]),
+ ("empty_list", {"data": {"sources": [], "pagination": {}}}, []),
+ ("no_data", {}, []),
+ ("data_not_dict", {"data": []}, []),
+ ]
+ )
+ def test_extract_rows(self, _name: str, body: dict[str, Any], expected: list[dict[str, Any]]) -> None:
+ assert _extract_rows(body) == expected
+
+ def test_pagination_object_is_never_returned_as_rows(self) -> None:
+ # `pagination` is a dict, not a list, so it must not be mistaken for the resource array.
+ body = {"data": {"pagination": {"next": "x"}, "sources": [{"id": "s1"}]}}
+ assert _extract_rows(body) == [{"id": "s1"}]
+
+
+class TestRedactRows:
+ def test_no_redacted_fields_returns_rows_unchanged(self) -> None:
+ rows = [{"id": "1", "settings": {"k": "v"}}]
+ assert _redact_rows(rows, frozenset()) == rows
+
+ def test_drops_only_the_named_fields(self) -> None:
+ rows = [{"id": "1", "settings": {"apiKey": "secret"}, "name": "keep"}]
+ assert _redact_rows(rows, frozenset({"settings"})) == [{"id": "1", "name": "keep"}]
+
+ def test_non_dict_rows_pass_through(self) -> None:
+ # Defensive: a malformed row that isn't a dict should not raise.
+ malformed: list[Any] = ["not-a-dict"]
+ assert _redact_rows(malformed, frozenset({"settings"})) == malformed
+
+
+class TestNextCursor:
+ @parameterized.expand(
+ [
+ ("has_next", {"data": {"pagination": {"next": "Mw=="}}}, "Mw=="),
+ ("next_null", {"data": {"pagination": {"next": None}}}, None),
+ ("next_empty", {"data": {"pagination": {"next": ""}}}, None),
+ ("no_pagination", {"data": {"sources": []}}, None),
+ ("no_data", {}, None),
+ ]
+ )
+ def test_next_cursor(self, _name: str, body: dict[str, Any], expected: str | None) -> None:
+ assert _next_cursor(body) == expected
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(endpoint: str, manager: _FakeResumableManager, monkeypatch: Any, pages: list[dict]) -> list[dict]:
+ """Drive get_rows with a queue of fake page bodies, returning the flattened rows."""
+ page_iter = iter(pages)
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ return next(page_iter)
+
+ monkeypatch.setattr(segment, "_fetch", fake_fetch)
+ monkeypatch.setattr(segment, "make_tracked_session", lambda *a, **k: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_token="tok",
+ region="api",
+ config=SEGMENT_ENDPOINTS[endpoint],
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_paginates_until_next_is_absent(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = [
+ {"data": {"sources": [{"id": "s1"}], "pagination": {"next": "c1"}}},
+ {"data": {"sources": [{"id": "s2"}], "pagination": {"next": "c2"}}},
+ {"data": {"sources": [{"id": "s3"}], "pagination": {"next": None}}},
+ ]
+ rows = self._collect("sources", manager, monkeypatch, pages)
+ assert rows == [{"id": "s1"}, {"id": "s2"}, {"id": "s3"}]
+
+ def test_saves_cursor_after_each_non_terminal_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = [
+ {"data": {"sources": [{"id": "s1"}], "pagination": {"next": "c1"}}},
+ {"data": {"sources": [{"id": "s2"}], "pagination": {"next": "c2"}}},
+ {"data": {"sources": [{"id": "s3"}], "pagination": {"next": None}}},
+ ]
+ self._collect("sources", manager, monkeypatch, pages)
+ # State is saved only for the pages that have a next cursor — never on the terminal page.
+ assert manager.saved == [SegmentResumeConfig(cursor="c1"), SegmentResumeConfig(cursor="c2")]
+
+ def test_terminal_single_page_saves_no_state(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = [{"data": {"sources": [{"id": "only"}], "pagination": {"next": None}}}]
+ self._collect("sources", manager, monkeypatch, pages)
+ assert manager.saved == []
+
+ def test_resume_starts_from_saved_cursor(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(state=SegmentResumeConfig(cursor="resumed"))
+ captured_urls: list[str] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ captured_urls.append(url)
+ return {"data": {"sources": [{"id": "s9"}], "pagination": {"next": None}}}
+
+ monkeypatch.setattr(segment, "_fetch", fake_fetch)
+ monkeypatch.setattr(segment, "make_tracked_session", lambda *a, **k: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_token="tok",
+ region="api",
+ config=SEGMENT_ENDPOINTS["sources"],
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+
+ assert rows == [{"id": "s9"}]
+ assert "pagination[cursor]=resumed" in captured_urls[0]
+
+ def test_credential_fields_are_redacted(self, monkeypatch: Any) -> None:
+ # Credential-like config must never reach the queryable warehouse table.
+ cases = [
+ ("destinations", {"id": "d1", "settings": {"apiKey": "secret"}}, {"id": "d1"}),
+ ("warehouses", {"id": "w1", "settings": {"password": "secret"}}, {"id": "w1"}),
+ ("sources", {"id": "s1", "writeKeys": ["wk_secret"]}, {"id": "s1"}),
+ ]
+ for endpoint, raw_row, expected_row in cases:
+ manager = _FakeResumableManager()
+ pages = [{"data": {endpoint: [raw_row], "pagination": {"next": None}}}]
+ rows = self._collect(endpoint, manager, monkeypatch, pages)
+ assert rows == [expected_row], endpoint
+
+ def test_single_object_endpoint_yields_one_row_and_no_pagination(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ captured_urls: list[str] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ captured_urls.append(url)
+ return {"data": {"workspace": {"id": "w1", "name": "Acme", "slug": "acme"}}}
+
+ monkeypatch.setattr(segment, "_fetch", fake_fetch)
+ monkeypatch.setattr(segment, "make_tracked_session", lambda *a, **k: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_token="tok",
+ region="api",
+ config=SEGMENT_ENDPOINTS["workspace"],
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+
+ assert rows == [{"id": "w1", "name": "Acme", "slug": "acme"}]
+ # The workspace endpoint hits its bare path once, with no pagination params.
+ assert captured_urls == ["https://api.segmentapis.com/"]
+ assert manager.saved == []
+
+
+class TestSegmentSource:
+ @parameterized.expand([(name,) for name in SEGMENT_ENDPOINTS])
+ def test_source_response_carries_endpoint_primary_keys(self, endpoint: str) -> None:
+ response = segment_source(
+ api_token="tok",
+ region="api",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == SEGMENT_ENDPOINTS[endpoint].primary_keys
+
+ def test_labels_use_composite_primary_key(self) -> None:
+ response = segment_source(
+ api_token="tok",
+ region="api",
+ endpoint="labels",
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.primary_keys == ["key", "value"]
+
+ @parameterized.expand(
+ [
+ ("audit_events_partitions_on_timestamp", "audit_events", "datetime", ["timestamp"]),
+ ("sources_unpartitioned", "sources", None, None),
+ ]
+ )
+ def test_partitioning(
+ self, _name: str, endpoint: str, expected_mode: str | None, expected_keys: list[str] | None
+ ) -> None:
+ response = segment_source(
+ api_token="tok",
+ region="api",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.partition_mode == expected_mode
+ assert response.partition_keys == expected_keys
diff --git a/posthog/temporal/data_imports/sources/segment/tests/test_segment_source.py b/posthog/temporal/data_imports/sources/segment/tests/test_segment_source.py
new file mode 100644
index 000000000000..6de0e6cbd727
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/segment/tests/test_segment_source.py
@@ -0,0 +1,166 @@
+from typing import Any, Literal, cast
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import SegmentSourceConfig
+from posthog.temporal.data_imports.sources.segment.segment import SegmentResumeConfig
+from posthog.temporal.data_imports.sources.segment.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.segment.source import SegmentSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _config(region: str = "api", api_token: str = "tok") -> SegmentSourceConfig:
+ return SegmentSourceConfig(api_token=api_token, region=cast(Literal["api", "eu1"], region))
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert SegmentSource().source_type == ExternalDataSourceType.SEGMENT
+
+ def test_config_category_and_release_status(self) -> None:
+ config = SegmentSource().get_source_config
+ assert config.category == DataWarehouseSourceCategory.ANALYTICS
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Intentionally unreleased: the source is shipped behind the flag while it stabilizes.
+ assert config.unreleasedSource is True
+
+ def test_config_fields(self) -> None:
+ config = SegmentSource().get_source_config
+ field_names = {f.name for f in config.fields}
+ assert field_names == {"region", "api_token"}
+
+ token_field = next(f for f in config.fields if f.name == "api_token")
+ assert isinstance(token_field, SourceFieldInputConfig)
+ # The token is a secret and must render as a password input.
+ assert token_field.type == "password"
+ assert token_field.secret is True
+
+ region_field = next(f for f in config.fields if f.name == "region")
+ assert isinstance(region_field, SourceFieldSelectConfig)
+ assert {o.value for o in region_field.options} == {"api", "eu1"}
+ assert region_field.defaultValue == "api"
+
+
+class TestGetSchemas:
+ def test_returns_all_endpoints(self) -> None:
+ schemas = SegmentSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_all_full_refresh(self) -> None:
+ # The Public API exposes no server-side timestamp filter on these resources, so nothing is incremental.
+ schemas = SegmentSource().get_schemas(_config(), team_id=1)
+ assert all(not s.supports_incremental for s in schemas)
+ assert all(not s.supports_append for s in schemas)
+
+ def test_names_filter(self) -> None:
+ schemas = SegmentSource().get_schemas(_config(), team_id=1, names=["sources", "labels"])
+ assert {s.name for s in schemas} == {"sources", "labels"}
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ ("missing_header", 401, False),
+ ("forbidden", 403, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_validate_credentials_status_mapping(self, _name: str, status_code: int, expected_ok: bool) -> None:
+ with patch("posthog.temporal.data_imports.sources.segment.segment.make_tracked_session") as mock_session:
+ response = MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ ok, error = SegmentSource().validate_credentials(_config(), team_id=1)
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ def test_validate_credentials_network_error_is_invalid(self) -> None:
+ with patch("posthog.temporal.data_imports.sources.segment.segment.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ ok, error = SegmentSource().validate_credentials(_config(), team_id=1)
+ assert ok is False
+ assert error is not None
+
+ @parameterized.expand([("us", "api"), ("eu", "eu1")])
+ def test_validate_credentials_targets_region_host(self, _name: str, region: str) -> None:
+ with patch("posthog.temporal.data_imports.sources.segment.segment.make_tracked_session") as mock_session:
+ response = MagicMock()
+ response.status_code = 200
+ mock_session.return_value.get.return_value = response
+
+ SegmentSource().validate_credentials(_config(region=region), team_id=1)
+ called_url = mock_session.return_value.get.call_args.args[0]
+ assert region in called_url
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.segmentapis.com/sources"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://eu1.api.segmentapis.com/labels"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable_errors = SegmentSource().get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @parameterized.expand(
+ [
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.segmentapis.com/sources"),
+ ("rate_limit", "429 Client Error: Too Many Requests for url: https://api.segmentapis.com/sources"),
+ ("read_timeout", "HTTPSConnectionPool(host='api.segmentapis.com', port=443): Read timed out."),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
+ non_retryable_errors = SegmentSource().get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+
+class TestResumableManager:
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ source = SegmentSource()
+ inputs = MagicMock()
+ manager = source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SegmentResumeConfig
+
+
+class TestSourceForPipeline:
+ def test_plumbs_config_into_transport(self) -> None:
+ source = SegmentSource()
+ inputs = MagicMock()
+ inputs.schema_name = "sources"
+ manager = MagicMock()
+
+ with patch("posthog.temporal.data_imports.sources.segment.source.segment_source") as mock_source:
+ source.source_for_pipeline(_config(region="eu1", api_token="secret"), manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_token"] == "secret"
+ assert kwargs["region"] == "eu1"
+ assert kwargs["endpoint"] == "sources"
+ assert kwargs["resumable_source_manager"] is manager
+
+
+class TestCanonicalDescriptions:
+ def test_descriptions_cover_known_endpoints(self) -> None:
+ descriptions = SegmentSource().get_canonical_descriptions()
+ # Every documented endpoint with a curated description must be a real schema.
+ assert set(descriptions).issubset(set(ENDPOINTS))
+ assert "sources" in descriptions
+
+ @parameterized.expand([(name,) for name in ENDPOINTS])
+ def test_described_columns_are_nonempty(self, endpoint: str) -> None:
+ descriptions: dict[str, Any] = SegmentSource().get_canonical_descriptions()
+ if endpoint not in descriptions:
+ return
+ assert descriptions[endpoint].get("description")