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 pylon import source (#65649)

Tom Owers07629482e2ee
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index f0320c6a8025..793618312aef 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -160,6 +160,7 @@ the row lists both.
| postgres | DB protocol | psycopg | ➖ |
| postmark | HTTP | requests | ✅ |
| productboard | HTTP | requests | ✅ |
+| pylon | HTTP | requests | ✅ |
| recurly | HTTP | requests + `rest_source.RESTClient` | ✅ |
| ramp | HTTP | requests | ✅ |
| recharge | HTTP | requests | ✅ |
@@ -565,7 +566,6 @@ doesn't conflict with concurrent PRs.
- primetric
- printify
- productive
-- pylon
- pypi
- qonto
- qualaroo
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 69ac69a5333d..a6cbda9c47df 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -2458,7 +2458,7 @@ class PyPISourceConfig(config.Config):
@config.config
class PylonSourceConfig(config.Config):
- pass
+ api_token: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/pylon/canonical_descriptions.py b/posthog/temporal/data_imports/sources/pylon/canonical_descriptions.py
new file mode 100644
index 000000000000..3fe37d0aa01d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/pylon/canonical_descriptions.py
@@ -0,0 +1,201 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Sourced from the official Pylon API reference (https://docs.usepylon.com/pylon-docs/developer/api).
+# Keyed by the schema/endpoint name returned by get_schemas (matches ENDPOINTS in settings.py).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "issues": {
+ "description": "Support issues (conversations and tickets) handled in Pylon across Slack, Teams, email, and the customer portal.",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/issues",
+ "columns": {
+ "id": "The ID of the issue.",
+ "number": "The number of the issue.",
+ "title": "The title of the issue.",
+ "body_html": "The body of the issue in HTML format.",
+ "state": "The state of the issue (e.g. new, waiting_on_you, waiting_on_customer, on_hold, closed, or a custom status slug).",
+ "type": "The type of the issue (conversation or ticket).",
+ "source": "The source of the issue.",
+ "link": "The link to the issue in Pylon.",
+ "account": "The account associated with the issue.",
+ "assignee": "The user assigned to the issue.",
+ "requester": "The contact who requested the issue.",
+ "team": "The team the issue is assigned to.",
+ "tags": "Tags associated with the issue.",
+ "custom_fields": "Custom field values associated with the issue.",
+ "created_at": "The time the issue was created.",
+ "updated_at": "The time the issue was last updated.",
+ "first_response_time": "The time of the first response to the issue, if any.",
+ "resolution_time": "The time of the resolution of the issue, if any.",
+ "latest_message_time": "The time of the latest message in the issue.",
+ "number_of_touches": "The number of times the issue has been touched.",
+ "customer_portal_visible": "Whether the issue is visible in the customer portal.",
+ },
+ },
+ "accounts": {
+ "description": "Customer accounts (companies) tracked in Pylon.",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/accounts",
+ "columns": {
+ "id": "The ID of the account.",
+ "name": "The name of the account.",
+ "type": "The type of the account.",
+ "primary_domain": "The primary domain of the account.",
+ "domains": "The list of domains associated with the account.",
+ "owner": "The user who owns the account.",
+ "tags": "Tags associated with the account.",
+ "custom_fields": "Custom fields associated with the account.",
+ "channels": "Channels associated with the account.",
+ "external_ids": "External IDs associated with the account.",
+ "is_disabled": "Whether the account is disabled.",
+ "created_at": "The creation time of the account.",
+ "updated_at": "The time the account was last updated.",
+ "latest_customer_activity_time": "The time of the latest customer activity.",
+ },
+ },
+ "contacts": {
+ "description": "Individual contacts (people) associated with accounts in Pylon.",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/contacts",
+ "columns": {
+ "id": "The ID of the contact.",
+ "name": "The name of the contact.",
+ "email": "The primary email of the contact, if it exists.",
+ "emails": "The list of all emails of the contact.",
+ "phone_numbers": "The list of all phone numbers of the contact.",
+ "primary_phone_number": "The primary phone number of the contact, if it exists.",
+ "account": "The account the contact belongs to.",
+ "avatar_url": "Avatar URL of the contact.",
+ "custom_fields": "Custom field values associated with the contact.",
+ "external_ids": "External IDs associated with the contact.",
+ "portal_role": "Portal role slug assigned to the contact.",
+ "portal_role_id": "The ID of the custom portal role assigned to the contact.",
+ },
+ },
+ "users": {
+ "description": "Pylon users (agents/team members in your organization).",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/users",
+ "columns": {
+ "id": "The ID of the user.",
+ "name": "The name of the user.",
+ "email": "The primary email of the user.",
+ "emails": "The list of all emails of the user.",
+ "avatar_url": "The avatar URL of the user.",
+ "role_id": "The role_id of the user.",
+ "status": "The status of the user.",
+ },
+ },
+ "teams": {
+ "description": "Teams that issues can be assigned to in Pylon.",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/teams",
+ "columns": {
+ "id": "The ID of the team.",
+ "name": "The name of the team.",
+ "users": "The users in the team.",
+ },
+ },
+ "tags": {
+ "description": "Tags that can be applied to Pylon objects such as issues and accounts.",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/tags",
+ "columns": {
+ "id": "The ID of the tag.",
+ "value": "The value of the tag.",
+ "hex_color": "The hex code of the tag's color.",
+ "object_type": "The object type of the tagged object.",
+ },
+ },
+ "custom_fields": {
+ "description": "Custom field definitions across Pylon object types (account, issue, contact, task, project, meeting, opportunity). The object_type column records which object the definition applies to.",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/custom-fields",
+ "columns": {
+ "id": "The ID of the custom field.",
+ "object_type": "The type of object this custom field is for.",
+ "label": "The label of the custom field.",
+ "slug": "The slug of the custom field.",
+ "type": "The type of the custom field.",
+ "description": "The description of the custom field.",
+ "is_read_only": "Whether the custom field is read only.",
+ "source": "The source of the custom field.",
+ "default_value": "The default value for single-valued custom fields.",
+ "default_values": "The default values for multi-valued custom fields.",
+ "created_at": "When the custom field was created.",
+ "updated_at": "When the custom field was last updated.",
+ },
+ },
+ "ticket_forms": {
+ "description": "Ticket form definitions used to collect support requests in Pylon.",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/ticket-forms",
+ "columns": {
+ "id": "The ID of the ticket form.",
+ "name": "The name of the ticket form.",
+ "slug": "The slug of the ticket form.",
+ "url": "The URL of the ticket form.",
+ "description_html": "The description of the ticket form in HTML.",
+ "fields": "The layout of the ticket form.",
+ "is_public": "Indicates if the ticket form is public.",
+ },
+ },
+ "user_roles": {
+ "description": "User role definitions in Pylon.",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/user-roles",
+ "columns": {
+ "id": "The ID of the role.",
+ "name": "The name of the role.",
+ "slug": "The slug of the role.",
+ },
+ },
+ "macros": {
+ "description": "Saved reply/note/email macros agents can apply to issues in Pylon.",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/macros",
+ "columns": {
+ "id": "The ID of the macro.",
+ "name": "The name of the macro.",
+ "macro_group_id": "The ID of the macro group this macro belongs to.",
+ "text_html": "The HTML content of the macro.",
+ "text_type": "The type of text (reply, note, or email).",
+ "has_actions": "Whether this macro has actions that execute when applied.",
+ "actions": "The actions that execute when this macro is applied.",
+ "created_at": "The time the macro was created.",
+ "updated_at": "The time the macro was last updated.",
+ },
+ },
+ "knowledge_bases": {
+ "description": "Knowledge bases configured in Pylon.",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/knowledge-base",
+ "columns": {
+ "id": "The ID of the knowledge base.",
+ "title": "The name of the knowledge base.",
+ "slug": "The slug of the knowledge base.",
+ "default_language": "The default language of the knowledge base.",
+ "supported_languages": "The list of supported languages for the knowledge base.",
+ },
+ },
+ "tasks": {
+ "description": "Tasks tracked in Pylon, optionally linked to accounts, projects, and milestones.",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/tasks-and-projects",
+ "columns": {
+ "id": "The ID of the task.",
+ "title": "The title of the task.",
+ "body_html": "The body of the task in HTML format.",
+ "status": "The status of the task.",
+ "account": "The account associated with the task.",
+ "assignee": "The user assigned to the task.",
+ "project": "The project the task belongs to.",
+ "milestone": "The milestone the task belongs to.",
+ "parent_task_id": "The ID of the parent task, if this is a subtask.",
+ "subtask_ids": "The IDs of subtasks belonging to this task.",
+ "custom_fields": "Custom field values associated with the task, keyed by custom field slug.",
+ "customer_portal_visible": "Whether the task is visible in the customer portal.",
+ "due_date": "The due date of the task in RFC3339 format.",
+ "created_at": "The created at time of the task.",
+ "updated_at": "The updated at time of the task.",
+ },
+ },
+ "issue_statuses": {
+ "description": "The set of issue statuses (base and custom) configured in Pylon.",
+ "docs_url": "https://docs.usepylon.com/pylon-docs/developer/api/api-reference/issues",
+ "columns": {
+ "slug": "The slug of the issue status.",
+ "label": "The label of the issue status.",
+ "category": "The category of the issue status.",
+ "is_default_status": "Indicates if the issue status is a default status.",
+ "is_archived": "Indicates if the issue status is archived.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/pylon/pylon.py b/posthog/temporal/data_imports/sources/pylon/pylon.py
new file mode 100644
index 000000000000..59ae01e8a3a5
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/pylon/pylon.py
@@ -0,0 +1,327 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from 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.pylon.settings import (
+ ISSUES_MAX_WINDOW_DAYS,
+ PYLON_ENDPOINTS,
+ PylonEndpointConfig,
+)
+
+PYLON_BASE_URL = "https://api.usepylon.com"
+
+
+class PylonRetryableError(Exception):
+ pass
+
+
+class PylonResumeConfig:
+ # Next-page cursor within the current page scroll.
+ cursor: str | None = None
+ # RFC3339 start of the issues window currently being processed (windowed endpoints only).
+ window_start: str | None = None
+ # The custom-fields object_type currently being fanned out (fan-out endpoints only).
+ object_type: str | None = None
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _format_rfc3339(dt: datetime) -> str:
+ """Pylon's time-window params expect RFC3339. Use the Z suffix rather than +00:00."""
+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _parse_rfc3339(value: str) -> datetime:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+
+
+def _to_datetime(value: Any) -> datetime:
+ """Coerce an incremental cursor value (datetime / date / RFC3339 string) to an aware datetime."""
+ if isinstance(value, datetime):
+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ return _parse_rfc3339(str(value))
+
+
+def _build_url(base_url: str, params: dict[str, Any]) -> str:
+ if not params:
+ return base_url
+ return f"{base_url}?{urlencode(params)}"
+
+
+@retry(
+ retry=retry_if_exception_type((PylonRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=2, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ response = session.get(url, headers=headers, timeout=60)
+
+ # Pylon enforces tight per-endpoint rate limits (e.g. 10 req/min on /issues); back off and retry on
+ # 429 and transient 5xx. Everything else (notably 401/403) raises immediately so the sync surfaces a
+ # non-retryable credential error rather than spinning.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise PylonRetryableError(f"Pylon API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Pylon API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(api_token: str) -> bool:
+ try:
+ # redact_values masks the bearer token in logs/sample capture; allow_redirects=False keeps the
+ # credentialed request from following an off-origin redirect that could leak the token.
+ session = make_tracked_session(redact_values=(api_token,), allow_redirects=False)
+ response = session.get(f"{PYLON_BASE_URL}/me", headers=_get_headers(api_token), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _iter_pages(
+ session: requests.Session,
+ headers: dict[str, str],
+ path: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+ start_cursor: str | None = None,
+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:
+ """Page through a Pylon list endpoint, yielding (items, next_cursor) per page.
+
+ `next_cursor` is the cursor to fetch the page *after* the one just yielded, or None when the API
+ signals no further pages. Endpoints that return no `pagination` object (e.g. macros) yield exactly
+ one page with `next_cursor=None`.
+ """
+ cursor = start_cursor
+ seen_cursors: set[str] = set()
+ while True:
+ page_params = dict(params)
+ if cursor:
+ page_params["cursor"] = cursor
+
+ data = _fetch_page(session, _build_url(f"{PYLON_BASE_URL}{path}", page_params), headers, logger)
+ items = data.get("data") or []
+ pagination = data.get("pagination") or {}
+ next_cursor = pagination.get("cursor") if pagination.get("has_next_page") else None
+
+ yield items, next_cursor
+
+ if not next_cursor:
+ break
+ # A few list endpoints don't document the cursor param; guard against an endpoint that keeps
+ # reporting has_next_page with a cursor it then ignores, which would otherwise loop forever on
+ # the same page.
+ if next_cursor in seen_cursors:
+ logger.warning(f"Pylon: cursor did not advance for {path}, stopping pagination")
+ break
+ seen_cursors.add(next_cursor)
+ cursor = next_cursor
+
+
+def _get_simple_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: PylonEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[PylonResumeConfig],
+ resume: PylonResumeConfig | None,
+) -> Iterator[list[dict[str, Any]]]:
+ params: dict[str, Any] = {}
+ if config.limit:
+ params["limit"] = config.limit
+
+ start_cursor = resume.cursor if resume else None
+ for items, next_cursor in _iter_pages(session, headers, config.path, params, logger, start_cursor):
+ if items:
+ yield items
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it; merge dedupes
+ # on the primary key.
+ if next_cursor:
+ manager.save_state(PylonResumeConfig(cursor=next_cursor))
+
+
+def _get_fan_out_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: PylonEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[PylonResumeConfig],
+ resume: PylonResumeConfig | None,
+) -> Iterator[list[dict[str, Any]]]:
+ object_types = config.fan_out_object_types or []
+
+ remaining = object_types
+ resume_cursor: str | None = None
+ if resume is not None and resume.object_type is not None and resume.object_type in object_types:
+ remaining = object_types[object_types.index(resume.object_type) :]
+ resume_cursor = resume.cursor
+
+ for index, object_type in enumerate(remaining):
+ params: dict[str, Any] = {"object_type": object_type}
+ if config.limit:
+ params["limit"] = config.limit
+
+ start_cursor = resume_cursor if index == 0 else None
+ resume_cursor = None
+
+ for items, next_cursor in _iter_pages(session, headers, config.path, params, logger, start_cursor):
+ # Stamp the queried object_type so a single table covers every type and the composite
+ # [object_type, id] primary key stays unique even if two types reuse an id.
+ stamped = [{**item, "object_type": item.get("object_type") or object_type} for item in items]
+ if stamped:
+ yield stamped
+ if next_cursor:
+ manager.save_state(PylonResumeConfig(cursor=next_cursor, object_type=object_type))
+
+ # Advance the bookmark to the next object_type so a crash between types resumes correctly.
+ if index + 1 < len(remaining):
+ manager.save_state(PylonResumeConfig(cursor=None, object_type=remaining[index + 1]))
+
+
+def _get_windowed_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: PylonEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[PylonResumeConfig],
+ resume: PylonResumeConfig | None,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk `/issues` forward one <=30-day window at a time.
+
+ The endpoint requires a start_time/end_time window no longer than 30 days, so a backfill is a
+ sequence of ascending windows ending at "now". On an incremental run we start from the saved
+ watermark; on a first sync we look back `default_lookback_days`. Windows are processed strictly
+ ascending and always extended up to "now", so the resumable state (exact window + cursor) and the
+ incremental watermark both pick back up without gaps regardless of intra-window ordering.
+ """
+ now = datetime.now(UTC)
+
+ if should_use_incremental_field and db_incremental_field_last_value:
+ overall_start = _to_datetime(db_incremental_field_last_value)
+ else:
+ lookback_days = config.default_lookback_days or ISSUES_MAX_WINDOW_DAYS
+ overall_start = now - timedelta(days=lookback_days)
+
+ # A future-dated watermark would make every window empty; cap it so the sync stays a no-op rather
+ # than building an invalid window.
+ overall_start = min(overall_start, now)
+
+ if resume is not None and resume.window_start:
+ window_start = _parse_rfc3339(resume.window_start)
+ resume_cursor = resume.cursor
+ else:
+ window_start = overall_start
+ resume_cursor = None
+
+ while window_start < now:
+ window_end = min(window_start + timedelta(days=ISSUES_MAX_WINDOW_DAYS), now)
+ params: dict[str, Any] = {
+ "start_time": _format_rfc3339(window_start),
+ "end_time": _format_rfc3339(window_end),
+ }
+ if config.limit:
+ params["limit"] = config.limit
+
+ start_cursor = resume_cursor
+ resume_cursor = None
+
+ for items, next_cursor in _iter_pages(session, headers, config.path, params, logger, start_cursor):
+ if items:
+ yield items
+ if next_cursor:
+ manager.save_state(PylonResumeConfig(cursor=next_cursor, window_start=params["start_time"]))
+
+ window_start = window_end
+ if window_start < now:
+ manager.save_state(PylonResumeConfig(cursor=None, window_start=_format_rfc3339(window_start)))
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PylonResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = PYLON_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+ # redact_values masks the bearer token in logs/sample capture; allow_redirects=False keeps the
+ # credentialed request from following an off-origin redirect that could leak the token.
+ session = make_tracked_session(redact_values=(api_token,), allow_redirects=False)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.windowed:
+ yield from _get_windowed_rows(
+ session,
+ headers,
+ config,
+ logger,
+ resumable_source_manager,
+ resume,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ elif config.fan_out_object_types:
+ yield from _get_fan_out_rows(session, headers, config, logger, resumable_source_manager, resume)
+ else:
+ yield from _get_simple_rows(session, headers, config, logger, resumable_source_manager, resume)
+
+
+def pylon_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PylonResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = PYLON_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ 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,
+ # Issues windows are processed strictly ascending; the other endpoints are full-refresh cursor
+ # scrolls where sort_mode is not used to checkpoint a watermark.
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/pylon/settings.py b/posthog/temporal/data_imports/sources/pylon/settings.py
new file mode 100644
index 000000000000..d71e64312eda
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/pylon/settings.py
@@ -0,0 +1,136 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class PylonEndpointConfig:
+ name: str
+ path: str
+ # Most list endpoints return the records under `data` with a `pagination` object; macros and a
+ # handful of reference endpoints return a single un-paginated `data` array. We follow the
+ # `pagination.has_next_page`/`cursor` contract whenever the API returns one, so this is purely a
+ # documentation hint and never gates the loop.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable creation-style field used for datetime partitioning. None for endpoints whose objects
+ # expose no stable timestamp (contacts, users, teams, tags, ...).
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Only issues exposes a genuine server-side time filter (start_time/end_time), so it is the only
+ # endpoint that can sync incrementally. Everything else is cursor-only and ships full refresh.
+ supports_incremental: bool = False
+ # `GET /issues` requires an RFC3339 start_time/end_time window capped at 30 days, so its backfill
+ # is walked forward one <=30-day window at a time rather than as a single cursor scroll.
+ windowed: bool = False
+ # First-sync lookback for windowed endpoints (issues). Issues older than this aren't pulled on the
+ # initial load, matching how other high-volume event-style endpoints bound their first sync.
+ default_lookback_days: Optional[int] = None
+ # Page size to request. `GET /accounts` *requires* `limit`; issues accepts up to 20000. We send a
+ # conservative value everywhere to bound peak memory while keeping request counts low under the
+ # per-endpoint rate limits.
+ limit: Optional[int] = None
+ # custom-fields requires an `object_type` query param and has no single "all" value, so we fan out
+ # over each object type and stamp it onto every row. The id is only unique within an object type,
+ # hence the composite primary key.
+ fan_out_object_types: Optional[list[str]] = None
+ should_sync_default: bool = True
+
+
+# Pylon caps `/issues` time windows at 30 days.
+ISSUES_MAX_WINDOW_DAYS = 30
+
+# object_type values accepted by `GET /custom-fields` (per the API reference). We fan out over all of
+# them so a single `custom_fields` table covers every custom field definition in the workspace.
+CUSTOM_FIELD_OBJECT_TYPES = ["account", "issue", "contact", "task", "project", "meeting", "opportunity"]
+
+
+def _datetime_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+PYLON_ENDPOINTS: dict[str, PylonEndpointConfig] = {
+ "issues": PylonEndpointConfig(
+ name="issues",
+ path="/issues",
+ partition_key="created_at",
+ supports_incremental=True,
+ windowed=True,
+ default_lookback_days=365,
+ limit=2000,
+ # The /issues time window is required but the docs don't state which timestamp it filters on.
+ # We assume `created_at` (stable, also our partition key) and always extend the window up to
+ # "now", so even if the server actually filters on activity time the windowed backfill still
+ # covers the full history and merge dedupes on `id`. See pylon.py for the windowing logic.
+ incremental_fields=[_datetime_field("created_at")],
+ ),
+ "accounts": PylonEndpointConfig(
+ name="accounts",
+ path="/accounts",
+ partition_key="created_at",
+ limit=999, # accounts requires limit and rejects values >= 1000
+ ),
+ "contacts": PylonEndpointConfig(
+ name="contacts",
+ path="/contacts",
+ limit=999,
+ ),
+ "users": PylonEndpointConfig(
+ name="users",
+ path="/users",
+ ),
+ "teams": PylonEndpointConfig(
+ name="teams",
+ path="/teams",
+ ),
+ "tags": PylonEndpointConfig(
+ name="tags",
+ path="/tags",
+ ),
+ "custom_fields": PylonEndpointConfig(
+ name="custom_fields",
+ path="/custom-fields",
+ primary_keys=["object_type", "id"],
+ fan_out_object_types=CUSTOM_FIELD_OBJECT_TYPES,
+ ),
+ "ticket_forms": PylonEndpointConfig(
+ name="ticket_forms",
+ path="/ticket-forms",
+ ),
+ "user_roles": PylonEndpointConfig(
+ name="user_roles",
+ path="/user-roles",
+ ),
+ "macros": PylonEndpointConfig(
+ name="macros",
+ path="/macros",
+ partition_key="created_at",
+ ),
+ "knowledge_bases": PylonEndpointConfig(
+ name="knowledge_bases",
+ path="/knowledge-bases",
+ ),
+ "tasks": PylonEndpointConfig(
+ name="tasks",
+ path="/tasks",
+ partition_key="created_at",
+ limit=999,
+ ),
+ "issue_statuses": PylonEndpointConfig(
+ name="issue_statuses",
+ path="/issue-statuses",
+ # IssueStatus objects have no `id`; `slug` is the stable unique key.
+ primary_keys=["slug"],
+ ),
+}
+
+ENDPOINTS = tuple(PYLON_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in PYLON_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/pylon/source.py b/posthog/temporal/data_imports/sources/pylon/source.py
index 9b3b99912f38..b22fc4d1eb7d 100644
--- a/posthog/temporal/data_imports/sources/pylon/source.py
+++ b/posthog/temporal/data_imports/sources/pylon/source.py
@@ -1,20 +1,33 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-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 PylonSourceConfig
+from posthog.temporal.data_imports.sources.pylon.pylon import (
+ PylonResumeConfig,
+ pylon_source,
+ validate_credentials as validate_pylon_credentials,
+)
+from posthog.temporal.data_imports.sources.pylon.settings import ENDPOINTS, INCREMENTAL_FIELDS, PYLON_ENDPOINTS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PylonSource(SimpleSource[PylonSourceConfig]):
+class PylonSource(ResumableSource[PylonSourceConfig, PylonResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PYLON
@@ -25,7 +38,89 @@ class PylonSource(SimpleSource[PylonSourceConfig]):
name=SchemaExternalDataSourceType.PYLON,
category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
label="Pylon",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Pylon API token to pull your Pylon support data into the PostHog Data warehouse.
+
+You can create an API token from your Pylon dashboard under **Settings > API tokens** (admin only).""",
iconPath="/static/services/pylon.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/pylon",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A bad/revoked token surfaces as an HTTPError from `raise_for_status()`; retrying can never
+ # fix a credential problem. Match the stable status text and base host, not the per-request
+ # path/query.
+ "401 Client Error: Unauthorized for url: https://api.usepylon.com": "Your Pylon API token is invalid or has been revoked. Create a new token in Settings > API tokens and reconnect.",
+ "403 Client Error: Forbidden for url: https://api.usepylon.com": "Your Pylon API token is missing the permissions needed to sync this data. Recreate the token with the required access and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: PylonSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = PYLON_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: PylonSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_pylon_credentials(config.api_token):
+ return True, None
+
+ return False, "Invalid Pylon API token"
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.pylon.canonical_descriptions import CANONICAL_DESCRIPTIONS
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PylonResumeConfig]:
+ return ResumableSourceManager[PylonResumeConfig](inputs, PylonResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PylonSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PylonResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return pylon_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/posthog/temporal/data_imports/sources/pylon/tests/test_pylon.py b/posthog/temporal/data_imports/sources/pylon/tests/test_pylon.py
new file mode 100644
index 000000000000..a4936d69ddf8
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/pylon/tests/test_pylon.py
@@ -0,0 +1,345 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.pylon import pylon
+from posthog.temporal.data_imports.sources.pylon.pylon import (
+ PylonResumeConfig,
+ _build_url,
+ _format_rfc3339,
+ _parse_rfc3339,
+ _to_datetime,
+ get_rows,
+ pylon_source,
+)
+from posthog.temporal.data_imports.sources.pylon.settings import PYLON_ENDPOINTS
+
+
+def _page(items: list[dict[str, Any]], cursor: str | None = None) -> dict[str, Any]:
+ body: dict[str, Any] = {"data": items, "request_id": "req"}
+ if cursor is not None:
+ body["pagination"] = {"cursor": cursor, "has_next_page": True}
+ else:
+ body["pagination"] = {"cursor": "", "has_next_page": False}
+ return body
+
+
+def _no_resume_manager() -> MagicMock:
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+ manager.load_state.return_value = None
+ return manager
+
+
+class TestFormatRfc3339:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ ]
+ )
+ def test_format(self, _name: str, value: datetime, expected: str) -> None:
+ assert _format_rfc3339(value) == expected
+
+ def test_no_plus_offset(self) -> None:
+ assert "+00:00" not in _format_rfc3339(datetime(2026, 3, 4, tzinfo=UTC))
+
+ def test_roundtrip(self) -> None:
+ dt = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)
+ assert _parse_rfc3339(_format_rfc3339(dt)) == dt
+
+
+class TestToDatetime:
+ @parameterized.expand(
+ [
+ ("aware_datetime", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)),
+ ("naive_datetime", datetime(2026, 1, 2, 3, 4, 5), datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)),
+ ("date", date(2026, 1, 2), datetime(2026, 1, 2, 0, 0, 0, tzinfo=UTC)),
+ ("rfc3339_string", "2026-01-02T03:04:05Z", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)),
+ ]
+ )
+ def test_to_datetime(self, _name: str, value: Any, expected: datetime) -> None:
+ assert _to_datetime(value) == expected
+
+
+class TestBuildUrl:
+ def test_no_params(self) -> None:
+ assert _build_url("https://api.usepylon.com/teams", {}) == "https://api.usepylon.com/teams"
+
+ def test_encodes_params(self) -> None:
+ url = _build_url("https://api.usepylon.com/issues", {"limit": 100, "cursor": "a b"})
+ query = parse_qs(urlparse(url).query)
+ assert query["limit"] == ["100"]
+ assert query["cursor"] == ["a b"]
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_validate_credentials(self, _name: str, status_code: int, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status_code)
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: session)
+ assert pylon.validate_credentials("token") is expected
+
+ def test_validate_credentials_handles_exception(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: session)
+ assert pylon.validate_credentials("token") is False
+
+ def test_validate_credentials_hits_me_endpoint(self) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=200)
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: session)
+ pylon.validate_credentials("token")
+ called_url = session.get.call_args.args[0]
+ assert called_url == "https://api.usepylon.com/me"
+
+
+class TestSimpleEndpointPagination:
+ def test_follows_cursor_until_exhausted(self) -> None:
+ pages = [_page([{"id": "1"}], cursor="c1"), _page([{"id": "2"}], cursor="c2"), _page([{"id": "3"}])]
+ manager = _no_resume_manager()
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: MagicMock())
+ mp.setattr(pylon, "_fetch_page", MagicMock(side_effect=pages))
+ batches = list(
+ get_rows(api_token="t", endpoint="teams", logger=MagicMock(), resumable_source_manager=manager)
+ )
+
+ assert [row["id"] for batch in batches for row in batch] == ["1", "2", "3"]
+
+ def test_saves_state_after_each_page_with_next_cursor(self) -> None:
+ pages = [_page([{"id": "1"}], cursor="c1"), _page([{"id": "2"}])]
+ manager = _no_resume_manager()
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: MagicMock())
+ mp.setattr(pylon, "_fetch_page", MagicMock(side_effect=pages))
+ list(get_rows(api_token="t", endpoint="teams", logger=MagicMock(), resumable_source_manager=manager))
+
+ # Only the page that has a next cursor saves state (the last page must not).
+ assert manager.save_state.call_count == 1
+ assert manager.save_state.call_args.args[0] == PylonResumeConfig(cursor="c1")
+
+ def test_resumes_from_saved_cursor(self) -> None:
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = PylonResumeConfig(cursor="resume-cursor")
+ fetch = MagicMock(side_effect=[_page([{"id": "9"}])])
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: MagicMock())
+ mp.setattr(pylon, "_fetch_page", fetch)
+ list(get_rows(api_token="t", endpoint="teams", logger=MagicMock(), resumable_source_manager=manager))
+
+ first_url = fetch.call_args_list[0].args[1]
+ assert parse_qs(urlparse(first_url).query)["cursor"] == ["resume-cursor"]
+
+ def test_stops_when_cursor_does_not_advance(self) -> None:
+ # An endpoint that keeps returning the same cursor with has_next_page=true must not loop forever.
+ stuck = _page([{"id": "1"}], cursor="same")
+ manager = _no_resume_manager()
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: MagicMock())
+ mp.setattr(pylon, "_fetch_page", MagicMock(return_value=stuck))
+ batches = list(
+ get_rows(api_token="t", endpoint="teams", logger=MagicMock(), resumable_source_manager=manager)
+ )
+
+ # First page yielded, second fetch returns the same cursor -> stop. So at most two pages.
+ assert len(batches) <= 2
+
+ def test_accounts_sends_required_limit(self) -> None:
+ manager = _no_resume_manager()
+ fetch = MagicMock(side_effect=[_page([{"id": "1"}])])
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: MagicMock())
+ mp.setattr(pylon, "_fetch_page", fetch)
+ list(get_rows(api_token="t", endpoint="accounts", logger=MagicMock(), resumable_source_manager=manager))
+
+ url = fetch.call_args_list[0].args[1]
+ assert parse_qs(urlparse(url).query)["limit"] == ["999"]
+
+
+class TestFanOutEndpoint:
+ def test_fans_out_over_all_object_types_and_stamps_object_type(self) -> None:
+ object_types = PYLON_ENDPOINTS["custom_fields"].fan_out_object_types or []
+ # One single-page response per object type; the field omits object_type so the stamp must fill it.
+ pages = [_page([{"id": f"f-{ot}"}]) for ot in object_types]
+ manager = _no_resume_manager()
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: MagicMock())
+ mp.setattr(pylon, "_fetch_page", MagicMock(side_effect=pages))
+ batches = list(
+ get_rows(api_token="t", endpoint="custom_fields", logger=MagicMock(), resumable_source_manager=manager)
+ )
+
+ rows = [row for batch in batches for row in batch]
+ assert {row["object_type"] for row in rows} == set(object_types)
+ assert len(rows) == len(object_types)
+
+ def test_resumes_from_saved_object_type(self) -> None:
+ object_types = PYLON_ENDPOINTS["custom_fields"].fan_out_object_types or []
+ resume_type = object_types[2]
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = PylonResumeConfig(object_type=resume_type)
+ # Remaining object types after (and including) the resume position.
+ remaining = object_types[object_types.index(resume_type) :]
+ fetch = MagicMock(side_effect=[_page([{"id": "x", "object_type": ot}]) for ot in remaining])
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: MagicMock())
+ mp.setattr(pylon, "_fetch_page", fetch)
+ batches = list(
+ get_rows(api_token="t", endpoint="custom_fields", logger=MagicMock(), resumable_source_manager=manager)
+ )
+
+ seen = [row["object_type"] for batch in batches for row in batch]
+ assert seen == remaining
+
+
+class TestWindowedIssues:
+ @freeze_time("2026-06-23T00:00:00Z")
+ def test_first_sync_walks_lookback_in_30_day_windows(self) -> None:
+ manager = _no_resume_manager()
+ fetch = MagicMock(return_value=_page([{"id": "i", "created_at": "2026-01-01T00:00:00Z"}]))
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: MagicMock())
+ mp.setattr(pylon, "_fetch_page", fetch)
+ list(
+ get_rows(
+ api_token="t",
+ endpoint="issues",
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+ )
+
+ windows = [parse_qs(urlparse(c.args[1]).query) for c in fetch.call_args_list]
+ # 365-day lookback in <=30-day windows => 13 windows.
+ assert len(windows) == 13
+ # First window starts a year before frozen now and the last window ends exactly at now.
+ assert windows[0]["start_time"] == ["2025-06-23T00:00:00Z"]
+ assert windows[-1]["end_time"] == ["2026-06-23T00:00:00Z"]
+ # Each window is contiguous: a window's end is the next window's start.
+ for earlier, later in zip(windows, windows[1:]):
+ assert earlier["end_time"] == later["start_time"]
+
+ @freeze_time("2026-06-23T00:00:00Z")
+ def test_incremental_starts_from_watermark(self) -> None:
+ manager = _no_resume_manager()
+ fetch = MagicMock(return_value=_page([{"id": "i", "created_at": "2026-06-10T00:00:00Z"}]))
+ watermark = datetime(2026, 6, 1, tzinfo=UTC)
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: MagicMock())
+ mp.setattr(pylon, "_fetch_page", fetch)
+ list(
+ get_rows(
+ api_token="t",
+ endpoint="issues",
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+ )
+
+ windows = [parse_qs(urlparse(c.args[1]).query) for c in fetch.call_args_list]
+ # Watermark is 22 days before now, so a single <=30-day window covers it.
+ assert len(windows) == 1
+ assert windows[0]["start_time"] == ["2026-06-01T00:00:00Z"]
+ assert windows[0]["end_time"] == ["2026-06-23T00:00:00Z"]
+
+ @freeze_time("2026-06-23T00:00:00Z")
+ def test_future_watermark_is_a_no_op(self) -> None:
+ manager = _no_resume_manager()
+ fetch = MagicMock(return_value=_page([]))
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: MagicMock())
+ mp.setattr(pylon, "_fetch_page", fetch)
+ list(
+ get_rows(
+ api_token="t",
+ endpoint="issues",
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2027, 1, 1, tzinfo=UTC),
+ )
+ )
+
+ assert fetch.call_count == 0
+
+ @freeze_time("2026-06-23T00:00:00Z")
+ def test_resumes_from_saved_window(self) -> None:
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = PylonResumeConfig(cursor="page2", window_start="2026-06-10T00:00:00Z")
+ fetch = MagicMock(return_value=_page([{"id": "i", "created_at": "2026-06-11T00:00:00Z"}]))
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon, "make_tracked_session", lambda *a, **k: MagicMock())
+ mp.setattr(pylon, "_fetch_page", fetch)
+ list(
+ get_rows(
+ api_token="t",
+ endpoint="issues",
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2020, 1, 1, tzinfo=UTC),
+ )
+ )
+
+ first = parse_qs(urlparse(fetch.call_args_list[0].args[1]).query)
+ # Resume picks up at the saved window start and saved cursor, not the stale watermark.
+ assert first["start_time"] == ["2026-06-10T00:00:00Z"]
+ assert first["cursor"] == ["page2"]
+
+
+class TestPylonSourceResponse:
+ @parameterized.expand(
+ [
+ ("issues", ["id"], "created_at"),
+ ("accounts", ["id"], "created_at"),
+ ("contacts", ["id"], None),
+ ("custom_fields", ["object_type", "id"], None),
+ ("issue_statuses", ["slug"], None),
+ ("tasks", ["id"], "created_at"),
+ ]
+ )
+ def test_source_response_shape(self, endpoint: str, primary_keys: list[str], partition_key: str | None) -> None:
+ response = pylon_source(
+ api_token="t", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=_no_resume_manager()
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.sort_mode == "asc"
+ if partition_key is None:
+ assert response.partition_keys is None
+ assert response.partition_mode is None
+ else:
+ assert response.partition_keys == [partition_key]
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "month"
diff --git a/posthog/temporal/data_imports/sources/pylon/tests/test_pylon_source.py b/posthog/temporal/data_imports/sources/pylon/tests/test_pylon_source.py
new file mode 100644
index 000000000000..cafce1eaad24
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/pylon/tests/test_pylon_source.py
@@ -0,0 +1,143 @@
+from typing import cast
+
+import pytest
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ ExternalDataSourceType as SchemaExternalDataSourceType,
+ SourceFieldInputConfig,
+)
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import PylonSourceConfig
+from posthog.temporal.data_imports.sources.pylon import source as pylon_source_module
+from posthog.temporal.data_imports.sources.pylon.pylon import PylonResumeConfig
+from posthog.temporal.data_imports.sources.pylon.settings import ENDPOINTS, PYLON_ENDPOINTS
+from posthog.temporal.data_imports.sources.pylon.source import PylonSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _config(api_token: str = "token") -> PylonSourceConfig:
+ return PylonSourceConfig.from_dict({"api_token": api_token})
+
+
+class TestPylonSourceConfig:
+ def test_source_type(self) -> None:
+ assert PylonSource().source_type == ExternalDataSourceType.PYLON
+
+ def test_get_source_config_basics(self) -> None:
+ config = PylonSource().get_source_config
+ assert config.name == SchemaExternalDataSourceType.PYLON
+ assert config.label == "Pylon"
+ # A finished-but-new source ships visible (no unreleasedSource) and labelled alpha.
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == "alpha"
+
+ def test_get_source_config_has_single_password_token_field(self) -> None:
+ fields = PylonSource().get_source_config.fields
+ assert len(fields) == 1
+ field = cast(SourceFieldInputConfig, fields[0])
+ assert field.name == "api_token"
+ assert field.type == "password"
+ assert field.required is True
+
+
+class TestPylonGetSchemas:
+ def test_returns_all_endpoints(self) -> None:
+ schemas = PylonSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_only_issues_supports_incremental(self) -> None:
+ schemas = PylonSource().get_schemas(_config(), team_id=1)
+ incremental = {s.name for s in schemas if s.supports_incremental}
+ assert incremental == {"issues"}
+
+ def test_filters_by_names(self) -> None:
+ schemas = PylonSource().get_schemas(_config(), team_id=1, names=["issues", "accounts"])
+ assert {s.name for s in schemas} == {"issues", "accounts"}
+
+ def test_issues_advertises_created_at_incremental_field(self) -> None:
+ schemas = PylonSource().get_schemas(_config(), team_id=1, names=["issues"])
+ fields = schemas[0].incremental_fields
+ assert [f["field"] for f in fields] == ["created_at"]
+
+
+class TestPylonValidateCredentials:
+ @parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid Pylon API token"))])
+ def test_validate_credentials(self, _name: str, api_returns: bool, expected: tuple[bool, str | None]) -> None:
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon_source_module, "validate_pylon_credentials", lambda token: api_returns)
+ result = PylonSource().validate_credentials(_config(), team_id=1)
+ assert result == expected
+
+
+class TestPylonNonRetryableErrors:
+ def test_maps_auth_errors(self) -> None:
+ errors = PylonSource().get_non_retryable_errors()
+ keys = list(errors.keys())
+ assert any(k.startswith("401 Client Error") and "api.usepylon.com" in k for k in keys)
+ assert any(k.startswith("403 Client Error") and "api.usepylon.com" in k for k in keys)
+
+
+class TestPylonResumableManager:
+ def test_returns_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = PylonSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is PylonResumeConfig
+
+
+class TestPylonSourceForPipeline:
+ def test_plumbs_args_into_pylon_source(self) -> None:
+ captured: dict = {}
+
+ def _fake_pylon_source(**kwargs: object):
+ captured.update(kwargs)
+ return MagicMock()
+
+ inputs = MagicMock()
+ inputs.schema_name = "issues"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-06-01T00:00:00Z"
+ inputs.incremental_field = "created_at"
+ manager = MagicMock()
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon_source_module, "pylon_source", _fake_pylon_source)
+ PylonSource().source_for_pipeline(_config("secret"), manager, inputs)
+
+ assert captured["api_token"] == "secret"
+ assert captured["endpoint"] == "issues"
+ assert captured["should_use_incremental_field"] is True
+ assert captured["db_incremental_field_last_value"] == "2026-06-01T00:00:00Z"
+ assert captured["resumable_source_manager"] is manager
+
+ def test_passes_none_last_value_when_not_incremental(self) -> None:
+ captured: dict = {}
+
+ def _fake_pylon_source(**kwargs: object):
+ captured.update(kwargs)
+ return MagicMock()
+
+ inputs = MagicMock()
+ inputs.schema_name = "accounts"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "ignored"
+ inputs.incremental_field = None
+
+ with pytest.MonkeyPatch().context() as mp:
+ mp.setattr(pylon_source_module, "pylon_source", _fake_pylon_source)
+ PylonSource().source_for_pipeline(_config(), MagicMock(), inputs)
+
+ assert captured["db_incremental_field_last_value"] is None
+
+
+class TestPylonCanonicalDescriptions:
+ def test_descriptions_keyed_by_known_endpoints(self) -> None:
+ descriptions = PylonSource().get_canonical_descriptions()
+ assert descriptions
+ assert set(descriptions.keys()).issubset(set(PYLON_ENDPOINTS.keys()))