Skip to content

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

feat(data-warehouse): add Zylo source (#73207)

Tom Owersd8ac576a0a4c
diff --git a/frontend/public/services/zylo.png b/frontend/public/services/zylo.png
index c5736e43b50d..33d01f46c768 100644
Binary files a/frontend/public/services/zylo.png and b/frontend/public/services/zylo.png differ
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 108cc7040af2..c01f9182b957 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -1554,20 +1554,29 @@ class BaseTestMigrations(QueryMatchingTest):
apps: Optional[Any] = None
assert_snapshots = False
- @classmethod
- def setUpClass(cls) -> None:
+ @staticmethod
+ def _reset_dead_connections() -> None:
# An earlier test in the same process can leave a connection's underlying psycopg
# connection closed (e.g. dropped server-side) without Django noticing. Every
- # migration test in the class then fails with "the connection is closed", and
- # in-process reruns reuse the same dead wrapper, so they can never recover.
- # Reset unusable connections before the class transaction machinery starts.
+ # migration test then fails with "the connection is closed"; closing the dead
+ # wrapper lets the next use reconnect cleanly. Only unusable connections are
+ # touched, so healthy ones (and any open transaction) are left untouched.
for conn in connections.all():
if conn.connection is not None and not conn.is_usable():
conn.close()
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ # Reset unusable connections before the class transaction machinery starts.
+ cls._reset_dead_connections()
# Mixin: setUpClass resolves via the TestCase mixed in by concrete subclasses.
super().setUpClass() # type: ignore[misc]
def setUp(self):
+ # In-process reruns (pytest --reruns) re-enter setUp without setUpClass, and a
+ # connection can also drop after class setup, so reset again here — otherwise the
+ # dead wrapper is reused and the test can never recover.
+ self._reset_dead_connections()
assert hasattr(self, "migrate_from") and hasattr(self, "migrate_to"), (
"TestCase '{}' must define migrate_from and migrate_to properties".format(type(self).__name__)
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 53fd2c251164..042b062fd81e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -629,6 +629,7 @@ the row lists both.
| zonka_feedback | HTTP | requests | ✅ |
| zoom | HTTP | requests | ✅ |
| zuora | HTTP | requests | ✅ |
+| zylo | HTTP | requests + `rest_source.RESTClient` | ✅ |
### Notes on partially-tracked sources
@@ -1409,4 +1410,3 @@ doesn't conflict with concurrent PRs.
- zoho_inventory
- zoho_invoice
- zoominfo
-- zylo
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zylo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zylo.py
index 41be085d1644..bedc5252e813 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zylo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zylo.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class ZyloSourceConfig(config.Config):
- pass
+ token_id: str
+ token_secret: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/canonical_descriptions.py
new file mode 100644
index 000000000000..cbbba0b521b5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/canonical_descriptions.py
@@ -0,0 +1,233 @@
+"""Canonical, documentation-sourced descriptions for Zylo endpoints and columns.
+
+Sourced from the official Zylo Enterprise API reference (https://developer.zylo.com/reference).
+Keyed by the endpoint names in `settings.py` `ZYLO_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced Zylo table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Timestamps present on nearly every Zylo object; merged into each entry so we don't repeat them.
+_SYSTEM_COLUMNS = {
+ "zylo_created_at": "Date and time the record was created in Zylo.",
+ "zylo_modified_at": "Date and time the record was last modified in Zylo.",
+}
+
+
+def _columns(**overrides: str) -> dict[str, str]:
+ return {**_SYSTEM_COLUMNS, **overrides}
+
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Applications": {
+ "description": "A SaaS application discovered or added in Zylo's software catalog.",
+ "docs_url": "https://developer.zylo.com/reference/applicationscontroller_getapplications",
+ "columns": _columns(
+ id="Unique identifier for the application.",
+ app_name="The application's name.",
+ app_label="Zylo's canonical label for the application.",
+ status="Lifecycle status of the application (e.g. active).",
+ category="High-level category the application belongs to.",
+ subcategory="Sub-category within the application's category.",
+ is_cloud="Whether the application is a cloud-hosted SaaS product.",
+ holds_pii="Whether the application is flagged as holding personally identifiable information.",
+ business_owner_user_email="Email of the business owner assigned to the application.",
+ application_owner_user_email="Email of the application owner.",
+ it_owner_user_email="Email of the IT owner assigned to the application.",
+ next_action="Recommended next action for managing the application (e.g. cancel).",
+ tags="Free-form tags applied to the application.",
+ ),
+ },
+ "ApplicationLicenses": {
+ "description": "A license seat for an application, typically assigned to a user.",
+ "docs_url": "https://developer.zylo.com/reference/applicationlicensescontroller_getapplicationlicenses",
+ "columns": _columns(
+ id="Unique identifier for the license.",
+ active="Whether the license is currently active.",
+ application_id="ID of the application the license belongs to.",
+ external_user_id="Identifier of the user the license is assigned to, from the source system.",
+ is_paid_license="Whether the license is a paid seat.",
+ last_activity_date="Date of the license holder's last recorded activity.",
+ license_type="The license tier or plan name.",
+ name="Display name of the license.",
+ ),
+ },
+ "ApplicationUsers": {
+ "description": "A user of an application, with usage and license activity.",
+ "docs_url": "https://developer.zylo.com/reference/applicationuserscontroller_getapplicationusers",
+ "columns": _columns(
+ id="Unique identifier for the application user record.",
+ application_id="ID of the application the user record belongs to.",
+ email="Email address of the user.",
+ full_name="Full name of the user.",
+ first_name="First name of the user.",
+ last_name="Last name of the user.",
+ external_user_id="Identifier of the user from the source system.",
+ active="Whether the user is currently active on the application.",
+ is_paid_user="Whether the user occupies a paid license seat.",
+ days_active="Number of days the user has been active on the application.",
+ integration_type="Data source integration type this record was collected from.",
+ license_names="Names of the licenses held by the user.",
+ last_activity_date="Date of the user's last recorded activity on the application.",
+ ),
+ },
+ "Contracts": {
+ "description": "A software contract with a supplier, covering one or more applications.",
+ "docs_url": "https://developer.zylo.com/reference/contractscontroller_getcontracts",
+ "columns": _columns(
+ id="Unique identifier for the contract.",
+ name="Name of the contract.",
+ number="Contract number.",
+ status="Lifecycle status of the contract (e.g. Active, Expired, Inactive).",
+ start_date="Date the contract begins.",
+ end_date="Date the contract ends.",
+ supplier_id="ID of the supplier the contract is with.",
+ supplier_name="Name of the supplier the contract is with.",
+ total_contract_value="Total value of the contract.",
+ current_year_contract_value="Value of the contract attributable to the current year.",
+ native_currency="Currency the contract's native monetary values are denominated in.",
+ billing_frequency="How often the contract is billed.",
+ renewal_state="Renewal status of the contract.",
+ month_to_month="Whether the contract has moved to a month-to-month term.",
+ can_have_contract_lines="Whether this contract has associated Contract Line Items.",
+ total_licenses="Total number of licenses covered by the contract.",
+ owner="Owner of the contract record.",
+ ),
+ },
+ "ContractLineItems": {
+ "description": "A single priced line item within a contract, e.g. a license tier or add-on.",
+ "docs_url": "https://developer.zylo.com/reference/contractlineitemscontroller_getcontractlineitems",
+ "columns": _columns(
+ id="Unique identifier for the contract line item.",
+ contract_id="ID of the parent contract.",
+ application_id="ID of the application this line item relates to, if any.",
+ line_description="Description of the line item.",
+ license_type="License tier or plan name for the line item.",
+ license_name="Name of the license the line item covers.",
+ quantity="Quantity of licenses or units covered.",
+ unit_of_measure="Unit the quantity is measured in.",
+ unit_price="Price per unit.",
+ native_unit_price="Price per unit in the contract's native currency.",
+ total_price="Total price for the line item.",
+ native_currency="Currency the line item's native monetary values are denominated in.",
+ start_date="Date the line item's coverage begins.",
+ end_date="Date the line item's coverage ends; null if ongoing.",
+ ),
+ },
+ "Payments": {
+ "description": "A payment made for an application, sourced from AP or expense data.",
+ "docs_url": "https://developer.zylo.com/reference/paymentscontroller_getpayments",
+ "columns": _columns(
+ id="Unique identifier for the payment.",
+ amount="Payment amount.",
+ application_id="ID of the application the payment is for.",
+ payment_date="Date the payment was made.",
+ payment_type="Source of the payment record (AP or Expense).",
+ payment_name="Name of the payment.",
+ payment_description="Description of the payment.",
+ supplier_name="Name of the supplier paid.",
+ purchase_order_id="ID of the associated purchase order, if any.",
+ transaction_id="Identifier of the underlying transaction.",
+ cost_center="Cost center the payment is attributed to.",
+ expense_type="Type of expense the payment represents.",
+ ),
+ },
+ "PurchaseOrders": {
+ "description": "A purchase order raised against a supplier for software spend. Premium feature — "
+ "requires `applications:read` and `spend:read` API key scopes.",
+ "docs_url": "https://developer.zylo.com/reference/purchaseorderscontroller_getpurchaseorders",
+ "columns": _columns(
+ id="Unique identifier for the purchase order.",
+ number="Purchase order number.",
+ status="Lifecycle status of the purchase order.",
+ supplier_id="ID of the supplier the purchase order was raised against.",
+ vendor_name="Name of the vendor on the purchase order.",
+ account_number="Account number associated with the purchase order.",
+ total_spend_against="Total amount spent against the purchase order.",
+ remaining_spend_against="Remaining unspent amount on the purchase order.",
+ percent_spend_against="Percentage of the purchase order value spent so far.",
+ external_created_at="Date the source system reported as the purchase order's creation date.",
+ external_closed_at="Date the source system reported the purchase order as closed.",
+ requisition_number="Requisition number linked to the purchase order.",
+ ),
+ },
+ "POLineItems": {
+ "description": "A single line item within a purchase order.",
+ "docs_url": "https://developer.zylo.com/reference/polineitemscontroller_getpolineitems",
+ "columns": _columns(
+ id="Unique identifier for the purchase order line item.",
+ purchase_order_id="ID of the parent purchase order.",
+ application_id="ID of the application this line item relates to, if any.",
+ description="Description of the line item.",
+ amount="Amount for the line item.",
+ total_spend_against="Total amount spent against this line item.",
+ remaining_spend_against="Remaining unspent amount on this line item.",
+ percent_spend_against="Percentage of the line item's value spent so far.",
+ is_saas="Whether the line item is classified as SaaS spend.",
+ commodity_category="Commodity category the line item is classified under.",
+ commodity_name="Commodity name for the line item.",
+ department_name="Department the line item is attributed to.",
+ expense_type="Type of expense the line item represents.",
+ order_line_number="Line number within the purchase order.",
+ requestor_name="Name of the requestor for the line item.",
+ supplier_account_number="Supplier's account number for the line item.",
+ supplier_name="Name of the supplier.",
+ supplier_number="Zylo supplier number.",
+ supplier_order_number="Supplier's order number for the line item.",
+ external_created_at="Date the source system reported as the line item's creation date.",
+ ),
+ },
+ "Suppliers": {
+ "description": "A supplier (vendor) that PostHog customers buy software or services from.",
+ "docs_url": "https://developer.zylo.com/reference/supplierscontroller_getsuppliers",
+ "columns": _columns(
+ id="Unique identifier for the supplier.",
+ name="Name of the supplier.",
+ domain="Primary domain of the supplier.",
+ description="Description of the supplier.",
+ ),
+ },
+ "SavingsEvents": {
+ "description": "A recorded cost-savings event, e.g. a license reduction or contract renegotiation.",
+ "docs_url": "https://developer.zylo.com/reference/savingseventscontroller_getsavingsevents",
+ "columns": _columns(
+ id="Unique identifier for the savings event.",
+ application_id="ID of the application the savings event relates to.",
+ name="Name of the savings event.",
+ description="Description of the savings event.",
+ event_type="Type of savings event.",
+ value_type="Whether the recorded value is monetary or numerical.",
+ monetary_value="Monetary value of the savings, when `value_type` is monetary.",
+ numerical_value="Numerical value of the savings, when `value_type` is numerical.",
+ unit_of_measure="Unit the numerical value is measured in.",
+ transaction_date="Date of the transaction the savings event relates to.",
+ is_custom="Whether the savings event was manually created rather than system-detected.",
+ exclude_from_event_total="Whether the event is excluded from aggregate savings totals.",
+ notes="Free-form notes on the savings event.",
+ ),
+ },
+ "ApplicationBudgets": {
+ "description": "A yearly budget allocation for an application.",
+ "docs_url": "https://developer.zylo.com/reference/applicationbudgetscontroller_getapplicationbudgets",
+ "columns": _columns(
+ application_id="ID of the application the budget applies to.",
+ year="Fiscal year the budget applies to.",
+ budget_amount="Budgeted amount for the application in the given year.",
+ ),
+ },
+ "ActivityHistory": {
+ "description": "An audit log entry recording a change to a Zylo record.",
+ "docs_url": "https://developer.zylo.com/reference/activityhistorycontroller_getactivityhistory",
+ "columns": _columns(
+ id="Unique identifier for the activity history entry.",
+ resource_id="ID of the resource the activity relates to.",
+ event_name="Name of the event that occurred.",
+ event_by="Identifier of the user or system that performed the event.",
+ event_at="Date and time the event occurred.",
+ before="Value of the changed property before the event.",
+ after="Value of the changed property after the event.",
+ ),
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/settings.py
new file mode 100644
index 000000000000..0ced1b1a557e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/settings.py
@@ -0,0 +1,113 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Zylo Enterprise (v2) API base URL. Every endpoint path below is relative to this.
+ZYLO_BASE_URL = "https://api.zylo.com"
+
+# Zylo list endpoints cap `limit` at 1000 (default 50 if unset); we always pass the max.
+PAGE_LIMIT = 1000
+
+# Every Zylo resource carries these two system timestamps and both accept the same
+# `field=value,operator` filter syntax (see https://developer.zylo.com/reference/filtering),
+# so both are safe, genuine server-side incremental cursors.
+_SYSTEM_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "zylo_created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "zylo_created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "zylo_modified_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "zylo_modified_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+@dataclass
+class ZyloEndpointConfig:
+ name: str
+ path: str
+ table_name: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Advertised incremental cursor options. Empty => full refresh only.
+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_SYSTEM_INCREMENTAL_FIELDS))
+ # Stable, never-updated datetime field used for partitioning. `zylo_created_at` is set once at
+ # record creation and never changes, unlike `zylo_modified_at`.
+ partition_key: Optional[str] = "zylo_created_at"
+
+
+# All resources are top-level list endpoints (no fan-out): every id in this catalog is a genuine
+# top-level list, so no parent identifier needs to ride in the primary key.
+ZYLO_ENDPOINTS: dict[str, ZyloEndpointConfig] = {
+ "Applications": ZyloEndpointConfig(
+ name="Applications",
+ path="/v2/applications",
+ table_name="applications",
+ ),
+ "ApplicationLicenses": ZyloEndpointConfig(
+ name="ApplicationLicenses",
+ path="/v2/applicationLicenses",
+ table_name="application_licenses",
+ ),
+ "ApplicationUsers": ZyloEndpointConfig(
+ name="ApplicationUsers",
+ path="/v2/applicationUsers",
+ table_name="application_users",
+ ),
+ "Contracts": ZyloEndpointConfig(
+ name="Contracts",
+ path="/v2/contracts",
+ table_name="contracts",
+ ),
+ "ContractLineItems": ZyloEndpointConfig(
+ name="ContractLineItems",
+ path="/v2/contractLineItems",
+ table_name="contract_line_items",
+ ),
+ "Payments": ZyloEndpointConfig(
+ name="Payments",
+ path="/v2/payments",
+ table_name="payments",
+ ),
+ # Premium feature — requires `applications:read` and `spend:read` scopes; a key without them
+ # gets a 403 for this endpoint only (see ZyloSource.get_endpoint_permissions).
+ "PurchaseOrders": ZyloEndpointConfig(
+ name="PurchaseOrders",
+ path="/v2/purchaseOrders",
+ table_name="purchase_orders",
+ ),
+ "POLineItems": ZyloEndpointConfig(
+ name="POLineItems",
+ path="/v2/poLineItems",
+ table_name="po_line_items",
+ ),
+ "Suppliers": ZyloEndpointConfig(
+ name="Suppliers",
+ path="/v2/suppliers",
+ table_name="suppliers",
+ ),
+ "SavingsEvents": ZyloEndpointConfig(
+ name="SavingsEvents",
+ path="/v2/savingsEvents",
+ table_name="savings_events",
+ ),
+ # No `id` field — one row per application per fiscal year, so the pair is the natural key.
+ "ApplicationBudgets": ZyloEndpointConfig(
+ name="ApplicationBudgets",
+ path="/v2/applicationBudgets",
+ table_name="application_budgets",
+ primary_keys=["application_id", "year"],
+ ),
+ "ActivityHistory": ZyloEndpointConfig(
+ name="ActivityHistory",
+ path="/v2/activityHistory",
+ table_name="activity_history",
+ ),
+}
+
+ENDPOINTS = tuple(ZYLO_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/source.py
index 41c48e5b5d3f..90787e28a93b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/source.py
@@ -1,30 +1,195 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zylo import ZyloSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.zylo.settings import ZYLO_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.zylo.zylo import (
+ ZyloResumeConfig,
+ probe_endpoint_status,
+ validate_credentials as validate_zylo_credentials,
+ zylo_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+# Scopes required per endpoint, surfaced in `get_endpoint_permissions` when a probe returns 403.
+# https://developer.zylo.com/reference/permissions
+_ENDPOINT_SCOPES: dict[str, str] = {
+ "Applications": "applications:read",
+ "ApplicationLicenses": "applications:read",
+ "ApplicationUsers": "team:read",
+ "Contracts": "contracts:read",
+ "ContractLineItems": "contracts:read",
+ "Payments": "spend:read",
+ # Premium feature — needs both scopes.
+ "PurchaseOrders": "applications:read and spend:read",
+ "POLineItems": "applications:read and spend:read",
+ "Suppliers": "contracts:read",
+ "SavingsEvents": "applications:read",
+ "ApplicationBudgets": "applications:read",
+ "ActivityHistory": "team:read",
+}
+
@SourceRegistry.register
-class ZyloSource(SimpleSource[ZyloSourceConfig]):
+class ZyloSource(ResumableSource[ZyloSourceConfig, ZyloResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://developer.zylo.com/reference"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ZYLO
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Zylo authentication failed. Please check your API token ID and secret.",
+ "403 Client Error: Forbidden for url": "Your Zylo API key does not have the required permission scope for this resource.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.zylo.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: ZyloSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint_config.name,
+ supports_incremental=len(endpoint_config.incremental_fields) > 0,
+ supports_append=len(endpoint_config.incremental_fields) > 0,
+ incremental_fields=endpoint_config.incremental_fields,
+ )
+ for endpoint_config in ZYLO_ENDPOINTS.values()
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def get_endpoint_permissions(
+ self, config: ZyloSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None
+ ) -> dict[str, str | None]:
+ permissions: dict[str, str | None] = {}
+ for endpoint in endpoints:
+ endpoint_config = ZYLO_ENDPOINTS.get(endpoint)
+ if endpoint_config is None:
+ permissions[endpoint] = None
+ continue
+ status = probe_endpoint_status(config.token_id, config.token_secret, endpoint_config.path)
+ # Only a real denial counts as missing scope — throttles, 5xx, and network blips
+ # must not mark a table unreachable.
+ if status == 403:
+ scope = _ENDPOINT_SCOPES.get(endpoint, "the required")
+ permissions[endpoint] = f"API key is missing the `{scope}` permission scope"
+ elif status == 401:
+ permissions[endpoint] = "API key is invalid"
+ else:
+ permissions[endpoint] = None
+ return permissions
+
+ def validate_credentials(
+ self, config: ZyloSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
+ ) -> tuple[bool, str | None]:
+ if not config.token_id or not config.token_secret:
+ return False, "Zylo token ID and token secret are required"
+
+ if validate_zylo_credentials(config.token_id, config.token_secret):
+ return True, None
+
+ return False, "Invalid Zylo credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZyloResumeConfig]:
+ return ResumableSourceManager[ZyloResumeConfig](inputs, ZyloResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ZyloSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ZyloResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return zylo_source(
+ token_id=config.token_id,
+ token_secret=config.token_secret,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ incremental_field=inputs.incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.ZYLO,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
- label="Zylo, Inc.",
+ label="Zylo",
+ keywords=["saas spend", "license management", "subscriptions", "it finance"],
+ caption=(
+ "Import your SaaS spend and license data from Zylo. Create an Enterprise API key under "
+ "**Integrations → API Integration → Connect** in Zylo and paste the token ID and secret "
+ "below. The key needs read scopes (e.g. `applications:read`, `contracts:read`, "
+ "`spend:read`, `team:read`) for the resources you want to sync — Purchase Orders and PO "
+ "Line Items are a premium feature and additionally require `spend:read`."
+ ),
iconPath="/static/services/zylo.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/zylo",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="token_id",
+ label="Token ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="token_secret",
+ label="Token secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/tests/test_zylo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/tests/test_zylo.py
new file mode 100644
index 000000000000..f9c3f0e6f727
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/tests/test_zylo.py
@@ -0,0 +1,291 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, date, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.zylo.zylo import (
+ INITIAL_INCREMENTAL_VALUE,
+ ZyloResumeConfig,
+ _format_zylo_filter_date,
+ get_resource,
+ probe_endpoint_status,
+ validate_credentials,
+ zylo_source,
+)
+
+
+def _endpoint(resource: Any) -> dict[str, Any]:
+ return cast(dict[str, Any], resource["endpoint"])
+
+
+def _params(resource: Any) -> dict[str, Any]:
+ return cast(dict[str, Any], _endpoint(resource)["params"])
+
+
+class TestFormatZyloFilterDate:
+ @pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02,gte"),
+ (date(2024, 1, 2), "2024-01-02,gte"),
+ ("2024-01-02 03:04:05", "2024-01-02,gte"),
+ ("2024-01-02", "2024-01-02,gte"),
+ ],
+ )
+ def test_formats_to_date_with_gte_suffix(self, value: Any, expected: str) -> None:
+ assert _format_zylo_filter_date(value) == expected
+
+ def test_unparseable_value_falls_back_to_raw_with_suffix(self) -> None:
+ assert _format_zylo_filter_date("not-a-date") == "not-a-date,gte"
+
+
+class TestGetResource:
+ @pytest.mark.parametrize(
+ ("endpoint", "table_name", "primary_key"),
+ [
+ ("Applications", "applications", ["id"]),
+ ("ApplicationLicenses", "application_licenses", ["id"]),
+ ("ApplicationUsers", "application_users", ["id"]),
+ ("Contracts", "contracts", ["id"]),
+ ("ContractLineItems", "contract_line_items", ["id"]),
+ ("Payments", "payments", ["id"]),
+ ("PurchaseOrders", "purchase_orders", ["id"]),
+ ("POLineItems", "po_line_items", ["id"]),
+ ("Suppliers", "suppliers", ["id"]),
+ ("SavingsEvents", "savings_events", ["id"]),
+ ("ApplicationBudgets", "application_budgets", ["application_id", "year"]),
+ ("ActivityHistory", "activity_history", ["id"]),
+ ],
+ )
+ def test_table_name_and_primary_key(self, endpoint: str, table_name: str, primary_key: list[str]) -> None:
+ resource = get_resource(endpoint, should_use_incremental_field=False, incremental_field=None)
+ assert resource["table_name"] == table_name
+ assert resource["primary_key"] == primary_key
+
+ def test_full_refresh_sorts_by_default_created_field(self) -> None:
+ resource = get_resource("Applications", should_use_incremental_field=False, incremental_field=None)
+ params = _params(resource)
+ assert params["sort"] == "+zylo_created_at"
+ assert resource["write_disposition"] == "replace"
+ assert set(params.keys()) == {"sort"}
+
+ def test_incremental_endpoint_uses_selected_cursor(self) -> None:
+ resource = get_resource("Contracts", should_use_incremental_field=True, incremental_field="zylo_modified_at")
+ params = _params(resource)
+ assert params["sort"] == "+zylo_modified_at"
+ gte = cast(dict[str, Any], params["zylo_modified_at"])
+ assert gte["type"] == "incremental"
+ assert gte["cursor_path"] == "zylo_modified_at"
+ assert gte["initial_value"] == INITIAL_INCREMENTAL_VALUE
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+
+ @pytest.mark.parametrize("incremental_field", [None, "bogus_field"])
+ def test_incremental_falls_back_to_first_advertised_cursor(self, incremental_field: str | None) -> None:
+ resource = get_resource("Applications", should_use_incremental_field=True, incremental_field=incremental_field)
+ params = _params(resource)
+ assert params["sort"] == "+zylo_created_at"
+ assert "zylo_created_at" in params
+
+ def test_incremental_disabled_when_not_requested(self) -> None:
+ resource = get_resource("Applications", should_use_incremental_field=False, incremental_field="zylo_created_at")
+ assert resource["write_disposition"] == "replace"
+ params = _params(resource)
+ assert "zylo_created_at" not in params
+
+
+class TestZyloSourcePartitioning:
+ def test_partition_config(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ response = zylo_source(
+ token_id="tok_id",
+ token_secret="tok_secret",
+ endpoint="Applications",
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ should_use_incremental_field=False,
+ )
+
+ assert response.name == "Applications"
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["zylo_created_at"]
+ assert response.partition_format == "month"
+
+
+def _make_http_response(body: list[dict[str, Any]], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+class TestZyloSourceResumeBehavior:
+ """End-to-end resume behaviour of ``zylo_source`` via ``rest_api_resource``."""
+
+ def _drive(
+ self,
+ endpoint: str,
+ manager: MagicMock,
+ responses: list[Response],
+ should_use_incremental_field: bool = False,
+ incremental_field: str | None = None,
+ db_incremental_field_last_value: Any = None,
+ ) -> list[dict[str, Any]]:
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ resource = zylo_source(
+ token_id="tok_id",
+ token_secret="tok_secret",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ )
+ list(cast(Iterable[Any], resource.items()))
+ return sent_params
+
+ def test_fresh_run_saves_skip_after_each_non_terminal_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response([{"id": f"app_{i}"} for i in range(1000)]),
+ _make_http_response([{"id": f"app_{i}"} for i in range(1000, 2000)]),
+ _make_http_response([{"id": "app_last"}]),
+ ]
+ sent_params = self._drive("Applications", manager, responses)
+
+ assert [p.get("skip") for p in sent_params] == [0, 1000, 2000]
+ assert all(p.get("limit") == 1000 for p in sent_params)
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [ZyloResumeConfig(next_skip=1000), ZyloResumeConfig(next_skip=2000)]
+
+ def test_resume_seeds_paginator_with_saved_skip(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ZyloResumeConfig(next_skip=2000)
+
+ responses = [_make_http_response([{"id": "app_last"}])]
+ sent_params = self._drive("Applications", manager, responses)
+
+ assert [p.get("skip") for p in sent_params] == [2000]
+ manager.load_state.assert_called_once()
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response([{"id": "only"}])]
+ self._drive("Applications", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response([{"id": "a"}])]
+ self._drive("Applications", manager, responses)
+
+ manager.load_state.assert_not_called()
+
+ def test_incremental_request_carries_gte_filter_and_sort(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response([{"id": "contract_1"}])]
+ sent_params = self._drive(
+ "Contracts",
+ manager,
+ responses,
+ should_use_incremental_field=True,
+ incremental_field="zylo_created_at",
+ db_incremental_field_last_value=None,
+ )
+
+ assert sent_params[0]["zylo_created_at"] == f"{INITIAL_INCREMENTAL_VALUE},gte"
+ assert sent_params[0]["sort"] == "+zylo_created_at"
+
+ def test_incremental_request_uses_db_last_value(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response([{"id": "contract_1"}])]
+ sent_params = self._drive(
+ "Contracts",
+ manager,
+ responses,
+ should_use_incremental_field=True,
+ incremental_field="zylo_modified_at",
+ db_incremental_field_last_value=datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC),
+ )
+
+ assert sent_params[0]["zylo_modified_at"] == "2024-06-01,gte"
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected"),
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.zylo.zylo.make_tracked_session")
+ def test_status_code_mapping(self, mock_session: MagicMock, status_code: int, expected: bool) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("tok_id", "tok_secret") is expected
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.zylo.zylo.make_tracked_session")
+ def test_network_error_returns_false(self, mock_session: MagicMock) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("tok_id", "tok_secret") is False
+
+
+class TestProbeEndpointStatus:
+ @pytest.mark.parametrize("status_code", [200, 401, 403, 429, 500])
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.zylo.zylo.make_tracked_session")
+ def test_returns_status_code(self, mock_session: MagicMock, status_code: int) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert probe_endpoint_status("tok_id", "tok_secret", "/v2/purchaseOrders") == status_code
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.zylo.zylo.make_tracked_session")
+ def test_network_error_returns_none(self, mock_session: MagicMock) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert probe_endpoint_status("tok_id", "tok_secret", "/v2/purchaseOrders") is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/tests/test_zylo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/tests/test_zylo_source.py
new file mode 100644
index 000000000000..d0191cb05a16
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/tests/test_zylo_source.py
@@ -0,0 +1,180 @@
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zylo import ZyloSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.zylo.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.zylo.source import ZyloSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.zylo.zylo import ZyloResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestZyloSource:
+ def setup_method(self) -> None:
+ self.source = ZyloSource()
+ self.team_id = 123
+ self.config = ZyloSourceConfig(token_id="tok_id", token_secret="tok_secret")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.ZYLO
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Zylo"
+ assert config.label == "Zylo"
+ assert config.releaseStatus == "alpha"
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/zylo.png"
+ assert len(config.fields) == 2
+
+ token_id_field, token_secret_field = config.fields
+ assert isinstance(token_id_field, SourceFieldInputConfig)
+ assert token_id_field.name == "token_id"
+ assert token_id_field.type == SourceFieldInputConfigType.TEXT
+ assert token_id_field.required is True
+ assert token_id_field.secret is False
+
+ assert isinstance(token_secret_field, SourceFieldInputConfig)
+ assert token_secret_field.name == "token_secret"
+ assert token_secret_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_secret_field.required is True
+ assert token_secret_field.secret is True
+
+ def test_get_schemas_lists_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))
+ def test_get_schemas_all_support_incremental(self, endpoint: str) -> None:
+ # Every Zylo resource exposes zylo_created_at/zylo_modified_at as genuine server-side filters.
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ assert schema.supports_incremental is True
+ assert schema.supports_append is True
+ fields = {f["field"] for f in schema.incremental_fields}
+ assert fields == {"zylo_created_at", "zylo_modified_at"}
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Applications"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "Applications"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ @pytest.mark.parametrize(
+ ("mock_return", "expected_valid", "expected_message"),
+ [
+ (True, True, None),
+ (False, False, "Invalid Zylo credentials"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zylo.source.validate_zylo_credentials"
+ )
+ def test_validate_credentials(
+ self, mock_validate: MagicMock, mock_return: bool, expected_valid: bool, expected_message: str | None
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("tok_id", "tok_secret")
+
+ @pytest.mark.parametrize(
+ "config",
+ [
+ ZyloSourceConfig(token_id="", token_secret="tok_secret"),
+ ZyloSourceConfig(token_id="tok_id", token_secret=""),
+ ],
+ )
+ def test_validate_credentials_requires_both_fields(self, config: ZyloSourceConfig) -> None:
+ is_valid, error_message = self.source.validate_credentials(config, self.team_id)
+ assert is_valid is False
+ assert error_message == "Zylo token ID and token secret are required"
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ [
+ "401 Client Error: Unauthorized for url",
+ "403 Client Error: Forbidden for url",
+ ],
+ )
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ @pytest.mark.parametrize(
+ ("status", "expected_message"),
+ [
+ (200, None),
+ (429, None),
+ (500, None),
+ (401, "API key is invalid"),
+ (403, "API key is missing the `applications:read and spend:read` permission scope"),
+ ],
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.zylo.source.probe_endpoint_status")
+ def test_get_endpoint_permissions(
+ self, mock_probe: MagicMock, status: int | None, expected_message: str | None
+ ) -> None:
+ mock_probe.return_value = status
+
+ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, ["PurchaseOrders"])
+
+ assert permissions == {"PurchaseOrders": expected_message}
+
+ def test_get_endpoint_permissions_unknown_endpoint_is_reachable(self) -> None:
+ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, ["NotARealEndpoint"])
+ assert permissions == {"NotARealEndpoint": None}
+
+ def test_get_resumable_source_manager_binds_data_class(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ZyloResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.zylo.source.zylo_source")
+ def test_source_for_pipeline_plumbs_inputs(self, mock_zylo_source: MagicMock) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ inputs = MagicMock()
+ inputs.schema_name = "Contracts"
+ inputs.team_id = 7
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.incremental_field = "zylo_modified_at"
+ inputs.db_incremental_field_last_value = "2024-01-01"
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_zylo_source.assert_called_once_with(
+ token_id="tok_id",
+ token_secret="tok_secret",
+ endpoint="Contracts",
+ team_id=7,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ incremental_field="zylo_modified_at",
+ db_incremental_field_last_value="2024-01-01",
+ )
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.zylo.source.zylo_source")
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self, mock_zylo_source: MagicMock) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ inputs = MagicMock()
+ inputs.schema_name = "Applications"
+ inputs.team_id = 7
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = False
+ inputs.incremental_field = None
+ inputs.db_incremental_field_last_value = "2024-01-01"
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ assert mock_zylo_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/zylo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/zylo.py
new file mode 100644
index 000000000000..05d5a72b7c3f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/zylo.py
@@ -0,0 +1,190 @@
+import dataclasses
+from datetime import date, datetime
+from typing import Any, Optional
+
+from dateutil import parser
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ OffsetPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.zylo.settings import (
+ PAGE_LIMIT,
+ ZYLO_BASE_URL,
+ ZYLO_ENDPOINTS,
+ ZyloEndpointConfig,
+)
+
+# Far-past cutoff used on the first incremental sync (no stored watermark yet) so we pull the
+# full history before the cursor takes over on subsequent runs.
+INITIAL_INCREMENTAL_VALUE = "1970-01-01"
+
+
+class ZyloResumeConfig:
+ next_skip: int
+
+
+def _format_zylo_filter_date(value: Any) -> str:
+ """Format an incremental cursor value as the `<value>,gte` filter Zylo expects.
+
+ Zylo's documented filter syntax (https://developer.zylo.com/reference/filtering) only shows
+ date-granularity (`YYYY-MM-DD`) values, even for datetime fields like `zylo_created_at` —
+ there is no documented full-timestamp filter format, so we truncate to the day. Incremental
+ merge-upsert on `id` de-dupes any same-day rows re-fetched across runs.
+ """
+ if isinstance(value, datetime):
+ d = value.date()
+ elif isinstance(value, date):
+ d = value
+ else:
+ try:
+ d = parser.parse(str(value)).date()
+ except (ValueError, OverflowError):
+ return f"{value},gte"
+ return f"{d.isoformat()},gte"
+
+
+def get_resource(
+ endpoint: str,
+ should_use_incremental_field: bool,
+ incremental_field: Optional[str],
+) -> EndpointResource:
+ config: ZyloEndpointConfig = ZYLO_ENDPOINTS[endpoint]
+
+ is_incremental = should_use_incremental_field and bool(config.incremental_fields)
+
+ cursor: Optional[str] = None
+ if is_incremental:
+ # Honor the user's chosen cursor field; fall back to the first advertised option.
+ advertised = {f["field"] for f in config.incremental_fields}
+ cursor = incremental_field if incremental_field in advertised else config.incremental_fields[0]["field"]
+
+ sort_field = cursor or "zylo_created_at"
+ params: dict[str, Any] = {
+ "sort": f"+{sort_field}",
+ }
+ if is_incremental and cursor is not None:
+ params[cursor] = {
+ "type": "incremental",
+ "cursor_path": cursor,
+ "initial_value": INITIAL_INCREMENTAL_VALUE,
+ "convert": _format_zylo_filter_date,
+ }
+
+ endpoint_def: Endpoint = {
+ "path": config.path,
+ "params": params,
+ }
+
+ return {
+ "name": config.name,
+ "table_name": config.table_name,
+ "primary_key": config.primary_keys,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if is_incremental else "replace",
+ "endpoint": endpoint_def,
+ "table_format": "delta",
+ }
+
+
+def zylo_source(
+ token_id: str,
+ token_secret: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ZyloResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool = False,
+ incremental_field: Optional[str] = None,
+) -> SourceResponse:
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": ZYLO_BASE_URL,
+ "auth": {
+ "type": "bearer",
+ "token": f"{token_id}:{token_secret}",
+ },
+ "paginator": OffsetPaginator(
+ limit=PAGE_LIMIT,
+ offset_param="skip",
+ limit_param="limit",
+ total_path=None,
+ ),
+ },
+ # Write disposition is set per-resource in get_resource (it always wins over
+ # resource_defaults), so no default is needed here.
+ "resource_defaults": {},
+ "resources": [get_resource(endpoint, should_use_incremental_field, incremental_field)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"offset": resume_config.next_skip}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only when there's a next page to resume to. Redis TTL handles cleanup on completion.
+ if state and state.get("offset") is not None:
+ resumable_source_manager.save_state(ZyloResumeConfig(next_skip=int(state["offset"])))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ endpoint_config = ZYLO_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=endpoint_config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
+
+
+def validate_credentials(token_id: str, token_secret: str) -> bool:
+ try:
+ response = make_tracked_session(redact_values=(token_secret,)).get(
+ f"{ZYLO_BASE_URL}/v2/applications",
+ params={"limit": 1},
+ headers={"Authorization": f"Bearer {token_id}:{token_secret}"},
+ timeout=30,
+ )
+ except Exception:
+ return False
+ return response.status_code == 200
+
+
+def probe_endpoint_status(token_id: str, token_secret: str, path: str) -> Optional[int]:
+ """Probe a single endpoint with the cheapest possible request; returns the HTTP status,
+ or ``None`` when the request itself failed (network blip — not a permission signal)."""
+ try:
+ response = make_tracked_session(redact_values=(token_secret,)).get(
+ f"{ZYLO_BASE_URL}{path}",
+ params={"limit": 1},
+ headers={"Authorization": f"Bearer {token_id}:{token_secret}"},
+ timeout=30,
+ )
+ except Exception:
+ return None
+ return response.status_code