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 Hyros import source (#84476)

Tom Owers4f0dca69e9ba
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hyros.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hyros.py
index 63d8e191a046..ac48902ff2e0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hyros.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hyros.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class HyrosSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/canonical_descriptions.py
new file mode 100644
index 000000000000..b84250a2d2a4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/canonical_descriptions.py
@@ -0,0 +1,128 @@
+"""Canonical, documentation-sourced descriptions for Hyros endpoints and columns.
+
+Sourced from the official Hyros REST API reference (https://api-docs.hyros.com). Keyed by the
+resource names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a
+synced Hyros table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Leads": {
+ "description": "A person Hyros has attributed to a source, with their tags, stage and first/last touch attribution.",
+ "docs_url": "https://api-docs.hyros.com",
+ "columns": {
+ "id": "Unique identifier for the lead.",
+ "email": "Email address of the lead.",
+ "creationDate": "Date the lead joined, in ISO 8601.",
+ "lastUpdatedDate": "Date the lead was last updated (tag, stage, or attribution change).",
+ "tags": "Tags currently applied to the lead.",
+ "ips": "IP addresses associated with the lead.",
+ "phoneNumbers": "Phone numbers associated with the lead.",
+ "firstName": "Lead's first name.",
+ "lastName": "Lead's last name.",
+ "currentStage": "Most recent stage applied to the lead, with its name and assignment date.",
+ "firstSource": "First attributed source that brought in the lead.",
+ "lastSource": "Last attributed source that brought in the lead.",
+ "originLead": "The origin lead this lead was merged into, when applicable.",
+ "adOptimizationConsent": "Consent status for using this lead in ad platform optimization.",
+ },
+ },
+ "Sales": {
+ "description": "A sale attributed to a lead, with pricing, refund state, and first/last touch attribution.",
+ "docs_url": "https://api-docs.hyros.com",
+ "columns": {
+ "id": "Unique identifier for the sale.",
+ "orderId": "Identifier of the order this sale belongs to.",
+ "creationDate": "Date the sale was created.",
+ "refundDate": "Date the sale was refunded, present only when refunded.",
+ "qualified": "Whether the sale is qualified.",
+ "score": "Attribution score of the sale.",
+ "recurring": "Whether the sale is part of a recurring subscription.",
+ "quantity": "Quantity of the product sold.",
+ "lead": "The lead this sale is attributed to.",
+ "firstSource": "First attributed source for this sale's lead.",
+ "lastSource": "Last attributed source for this sale's lead.",
+ "price": "Price details of the sale, including currency, discount and refunded amount.",
+ "product": "Product sold in this sale.",
+ },
+ },
+ "Calls": {
+ "description": "A phone call attributed to a lead, with its qualification state and attribution.",
+ "docs_url": "https://api-docs.hyros.com",
+ "columns": {
+ "id": "Unique identifier for the call.",
+ "tag": "Product tag associated with the call.",
+ "qualified": "Deprecated. Whether the call was qualified. Use `state` instead.",
+ "name": "Name of the call.",
+ "externalId": "Identifier from the external integration that created the call.",
+ "score": "Attribution score of the call.",
+ "creationDate": "Date the call was processed.",
+ "state": "Qualification state of the call (qualified, unqualified, cancelled, no show).",
+ "lead": "The lead this call is attributed to.",
+ "firstSource": "First attributed source for this call's lead.",
+ "lastSource": "Last attributed source for this call's lead.",
+ },
+ },
+ "Subscriptions": {
+ "description": "A recurring subscription attributed to a lead, with its billing state and attribution.",
+ "docs_url": "https://api-docs.hyros.com",
+ "columns": {
+ "id": "Unique identifier for the subscription.",
+ "startDate": "Date the subscription started.",
+ "endDate": "Date the subscription ended.",
+ "cancelAtDate": "Date the subscription is scheduled to cancel.",
+ "trialStartDate": "Date the subscription's trial period started.",
+ "trialEndDate": "Date the subscription's trial period ended.",
+ "price": "Recurring price of the subscription.",
+ "status": "Current billing status of the subscription.",
+ "periodicity": "Billing interval of the subscription.",
+ "planId": "Identifier of the plan the subscription is on.",
+ "tag": "Product tag associated with the subscription.",
+ "name": "Name of the subscription.",
+ "lead": "The lead this subscription is attributed to.",
+ "firstSource": "First attributed source for this subscription's lead.",
+ "lastSource": "Last attributed source for this subscription's lead.",
+ },
+ },
+ "Sources": {
+ "description": "A traffic source Hyros tracks, either organic or tied to an ad platform account.",
+ "docs_url": "https://api-docs.hyros.com",
+ "columns": {
+ "name": "Name of the source.",
+ "tag": 'Unique tag identifying the source (e.g. "@facebook-adset").',
+ "disregarded": "Whether the source is disregarded when attributing a sale.",
+ "organic": "Whether the source is marked as organic.",
+ "adSource": "Underlying ad platform source (id and platform), when the source is ad-driven.",
+ "creationDate": "Creation date of the source, as epoch milliseconds.",
+ },
+ },
+ "Tags": {
+ "description": "A tag created in Hyros, with the count of leads currently carrying it.",
+ "docs_url": "https://api-docs.hyros.com",
+ "columns": {
+ "name": "Name of the tag.",
+ "amount": "Number of leads currently carrying this tag.",
+ },
+ },
+ "Keywords": {
+ "description": "A keyword tracked against a Google Ads ad group.",
+ "docs_url": "https://api-docs.hyros.com",
+ "columns": {
+ "id": "Unique identifier for the keyword.",
+ "name": "Text of the keyword.",
+ "adGroupId": "Identifier of the Google Ads ad group the keyword belongs to.",
+ "adGroupName": "Name of the Google Ads ad group the keyword belongs to.",
+ },
+ },
+ "Stages": {
+ "description": "A lead stage defined in the account, with the count of leads currently in it.",
+ "docs_url": "https://api-docs.hyros.com",
+ "columns": {
+ "name": "Name of the stage.",
+ "amount": "Number of leads currently in this stage.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/hyros.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/hyros.py
new file mode 100644
index 000000000000..b1ecba49032d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/hyros.py
@@ -0,0 +1,152 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponseCursorPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.hyros.settings import HYROS_ENDPOINTS, PAGE_SIZE
+
+BASE_URL = "https://api.hyros.com/v1"
+
+
+@frozen
+class HyrosResumeConfig:
+ cursor: str
+
+
+def _format_hyros_date(value: Any) -> Optional[str]:
+ """Format an incremental cursor as the ISO 8601, offset-aware date Hyros' `fromDate` /
+ `updatedFromDate` filters expect. `None` passes through so the pipeline drops the param
+ from the request instead of sending a literal "None"."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.isoformat(timespec="seconds")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat(timespec="seconds")
+ return str(value)
+
+
+def _resource_for(endpoint: str, should_use_incremental_field: bool) -> EndpointResource:
+ config = HYROS_ENDPOINTS[endpoint]
+ is_incremental = should_use_incremental_field and config.incremental_query_param is not None
+
+ params: dict[str, Any] = {"pageSize": PAGE_SIZE}
+ if config.incremental_query_param is not None:
+ params[config.incremental_query_param] = (
+ {
+ "type": "incremental",
+ "cursor_path": config.incremental_field_name,
+ "initial_value": None,
+ "convert": _format_hyros_date,
+ }
+ if should_use_incremental_field
+ else None
+ )
+
+ return {
+ "name": endpoint,
+ "table_name": endpoint.lower(),
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if is_incremental else "replace",
+ "endpoint": {
+ "data_selector": "result",
+ "path": config.path,
+ "params": params,
+ },
+ "table_format": "delta",
+ }
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": BASE_URL,
+ "auth": {"type": "api_key", "api_key": api_key, "name": "API-Key", "location": "header"},
+ # A validated host could 3xx to an attacker-controlled host without stripping the
+ # `API-Key` header; refuse to follow redirects (SSRF/credential-leak guard).
+ "allow_redirects": False,
+ # Every list endpoint shares the same `{result, nextPageId, request_id}` envelope.
+ "paginator": JSONResponseCursorPaginator(cursor_path="nextPageId", cursor_param="pageId"),
+ }
+
+
+def hyros_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[HyrosResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> SourceResponse:
+ config = HYROS_ENDPOINTS[endpoint]
+
+ rest_config: RESTAPIConfig = {
+ "client": _client_config(api_key),
+ "resource_defaults": {},
+ "resources": [_resource_for(endpoint, should_use_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 = {"cursor": resume_config.cursor}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on
+ # completion.
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(HyrosResumeConfig(cursor=str(state["cursor"])))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ has_partition = config.partition_key is not None
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=config.primary_keys,
+ partition_count=1 if has_partition else None,
+ partition_size=1 if has_partition else None,
+ partition_mode="datetime" if has_partition else None,
+ partition_format="month" if has_partition else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ # Hyros doesn't document the order `pageId` cursoring returns rows in. Ascending is the
+ # conservative default the framework and every other cursor-paginated source here assume;
+ # flag it explicitly since it's unverified rather than confirmed against the live API.
+ sort_mode="asc",
+ column_hints=resource.column_hints,
+ )
+
+
+def validate_credentials(api_key: str) -> tuple[bool, int | None]:
+ """Probe Hyros' `/user-info` endpoint to confirm the API key is genuine."""
+ url = f"{BASE_URL}/api/v1.0/user-info"
+ return validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,)),
+ url,
+ headers={"API-Key": api_key},
+ # API-Key rides a custom header requests won't strip on a cross-origin redirect.
+ allow_redirects=False,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/settings.py
new file mode 100644
index 000000000000..f4075c353c55
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/settings.py
@@ -0,0 +1,107 @@
+from dataclasses import field
+from typing import Optional
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Hyros caps `pageSize` at 250 on every cursor-paginated list endpoint.
+PAGE_SIZE = 250
+
+
+def _incremental_field(field_name: str) -> list[IncrementalField]:
+ return [
+ {
+ "label": field_name,
+ "type": IncrementalFieldType.DateTime,
+ "field": field_name,
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+
+
+@frozen
+class HyrosEndpointConfig:
+ name: str
+ path: str # under https://api.hyros.com/v1
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Query parameter Hyros expects for the incremental start-date filter (e.g. "fromDate" or
+ # "updatedFromDate"). None when the endpoint has no server-side date filter.
+ incremental_query_param: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-time field to partition by. None when there's no reliable created-date column.
+ partition_key: Optional[str] = None
+
+ @property
+ def incremental_field_name(self) -> Optional[str]:
+ return self.incremental_fields[0]["field"] if self.incremental_fields else None
+
+
+HYROS_ENDPOINTS: dict[str, HyrosEndpointConfig] = {
+ "Leads": HyrosEndpointConfig(
+ name="Leads",
+ path="/api/v1.0/leads",
+ primary_keys=["id"],
+ # `updatedFromDate` filters on `lastUpdatedDate`, so it also catches tag/stage changes
+ # on existing leads that `fromDate` (join date only) would miss.
+ incremental_query_param="updatedFromDate",
+ incremental_fields=_incremental_field("lastUpdatedDate"),
+ partition_key="creationDate",
+ ),
+ "Sales": HyrosEndpointConfig(
+ name="Sales",
+ path="/api/v1.0/sales",
+ primary_keys=["id"],
+ incremental_query_param="fromDate",
+ incremental_fields=_incremental_field("creationDate"),
+ partition_key="creationDate",
+ ),
+ "Calls": HyrosEndpointConfig(
+ name="Calls",
+ path="/api/v1.0/calls",
+ primary_keys=["id"],
+ incremental_query_param="fromDate",
+ incremental_fields=_incremental_field("creationDate"),
+ partition_key="creationDate",
+ ),
+ "Subscriptions": HyrosEndpointConfig(
+ name="Subscriptions",
+ path="/api/v1.0/subscriptions",
+ primary_keys=["id"],
+ # The API docs don't name which field `fromDate`/`toDate` filters on subscriptions.
+ # `startDate` is the closest analogue to the creation-date filter documented on
+ # leads/sales/calls, so it's used for both the incremental cursor and partitioning.
+ incremental_query_param="fromDate",
+ incremental_fields=_incremental_field("startDate"),
+ partition_key="startDate",
+ ),
+ "Sources": HyrosEndpointConfig(
+ name="Sources",
+ path="/api/v1.0/sources",
+ # `tag` (e.g. "@facebook-adset") is the identifier the API itself uses to address a
+ # source (see `PUT /sources/{tag}`); the object has no `id` field.
+ primary_keys=["tag"],
+ ),
+ "Tags": HyrosEndpointConfig(
+ name="Tags",
+ # `GET /tags` is deprecated in favor of this endpoint, which also returns lead counts.
+ path="/api/v1.0/tags/count",
+ primary_keys=["name"],
+ ),
+ "Keywords": HyrosEndpointConfig(
+ name="Keywords",
+ path="/api/v1.0/keywords",
+ primary_keys=["id"],
+ ),
+ "Stages": HyrosEndpointConfig(
+ name="Stages",
+ path="/api/v1.0/stages",
+ primary_keys=["name"],
+ ),
+}
+
+ENDPOINTS = tuple(HYROS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in HYROS_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/source.py
index af7aa7eb95a6..de0e64a02350 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/source.py
@@ -1,31 +1,136 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hyros import HyrosSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.hyros.hyros import (
+ HyrosResumeConfig,
+ hyros_source,
+ validate_credentials as validate_hyros_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hyros.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class HyrosSource(SimpleSource[HyrosSourceConfig]):
+class HyrosSource(ResumableSource[HyrosSourceConfig, HyrosResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v1.0",)
+ default_version = "v1.0"
+ api_docs_url = "https://api-docs.hyros.com"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HYROS
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": (
+ "Your Hyros API key is invalid. Copy a fresh key from Hyros under Settings > Profile and reconnect."
+ ),
+ "403 Client Error: Forbidden for url": (
+ "Your Hyros API key doesn't have the role required for this table. "
+ "Grant the missing role in Hyros and try again."
+ ),
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.hyros.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: HyrosSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: HyrosSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ ok, status = validate_hyros_credentials(config.api_key)
+ if ok:
+ return True, None
+ return (
+ False,
+ "Invalid Hyros API key. Copy the key from Hyros under Settings > Profile and try again.",
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HyrosResumeConfig]:
+ return ResumableSourceManager[HyrosResumeConfig](inputs, HyrosResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: HyrosSourceConfig,
+ resumable_source_manager: ResumableSourceManager[HyrosResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return hyros_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ 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.HYROS,
category=DataWarehouseSourceCategory.ADVERTISING,
- keywords=["ad attribution", "ad tracking"],
+ keywords=["ad attribution", "ad tracking", "roas", "call tracking"],
label="Hyros",
+ releaseStatus=ReleaseStatus.ALPHA,
+ docsUrl="https://posthog.com/docs/cdp/sources/hyros",
iconPath="/static/services/hyros.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ caption="Find this in Hyros under Settings > Profile.",
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/tests/test_hyros.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/tests/test_hyros.py
new file mode 100644
index 000000000000..97df025c331b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/tests/test_hyros.py
@@ -0,0 +1,270 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+
+from unittest import mock
+
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.hyros.hyros import (
+ HyrosResumeConfig,
+ _format_hyros_date,
+ hyros_source,
+ validate_credentials,
+)
+
+# RESTClient builds its session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+# validate_credentials builds its own tracked session in the hyros module.
+HYROS_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hyros.hyros.make_tracked_session"
+)
+
+
+class _FakeResumeManager(ResumableSourceManager[HyrosResumeConfig]):
+ def __init__(self, state: HyrosResumeConfig | None = None) -> None:
+ self.state = state
+ self.saved: list[HyrosResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> HyrosResumeConfig | None:
+ return self.state
+
+ def save_state(self, data: HyrosResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestFormatHyrosDate:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),
+ ("string_passthrough", "2026-03-04T02:58:14-05:00", "2026-03-04T02:58:14-05:00"),
+ ("none_passthrough", None, None),
+ ]
+ )
+ def test_format(self, _name: str, value: Any, expected: str | None) -> None:
+ assert _format_hyros_date(value) == expected
+
+
+def _response(result: list[dict[str, Any]] | None, next_page_id: str | None = None, drop_key: bool = False) -> Response:
+ body: dict[str, Any] = {"request_id": "req-1"}
+ if not drop_key:
+ body["result"] = result or []
+ if next_page_id is not None:
+ body["nextPageId"] = next_page_id
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session and return a list that captures each request AT SEND TIME.
+
+ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the
+ run shows only the final state — snapshot a copy when each request is prepared instead.
+ """
+ session.headers = {}
+ snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return snapshots
+
+
+def _source(endpoint: str, manager: ResumableSourceManager[HyrosResumeConfig], **kwargs: Any):
+ return hyros_source(
+ api_key="key",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ should_use_incremental_field=kwargs.pop("should_use_incremental_field", False),
+ db_incremental_field_last_value=kwargs.pop("db_incremental_field_last_value", None),
+ )
+
+
+def _rows(source_response: Any) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+class TestHyrosSourcePagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_paginates_until_no_next_page_id(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"id": "1"}, {"id": "2"}], next_page_id="cursor-1"),
+ _response([{"id": "3"}]),
+ ],
+ )
+
+ rows = _rows(_source("Leads", _FakeResumeManager()))
+
+ assert [r["id"] for r in rows] == ["1", "2", "3"]
+ assert session.send.call_count == 2
+ assert snapshots[0]["url"] == "https://api.hyros.com/v1/api/v1.0/leads"
+ assert snapshots[0]["params"] == {"pageSize": 250}
+ assert snapshots[1]["params"] == {"pageSize": 250, "pageId": "cursor-1"}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_auth_is_framework_api_key_header(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([{"id": "1"}])])
+
+ _rows(_source("Stages", _FakeResumeManager()))
+
+ auth = snapshots[0]["auth"]
+ assert isinstance(auth, APIKeyAuth)
+ assert auth.api_key == "key"
+ assert auth.name == "API-Key"
+ assert auth.location == "header"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_does_not_follow_redirects(self, MockSession) -> None:
+ # A redirect off the validated Hyros host would carry the API-Key header with it to an
+ # attacker-controlled origin; the client must refuse to follow it (credential-leak guard).
+ session = MockSession.return_value
+ _wire(session, [_response([{"id": "1"}])])
+
+ _rows(_source("Stages", _FakeResumeManager()))
+
+ assert session.send.call_args.kwargs["allow_redirects"] is False
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_saves_resume_state_only_while_pages_remain(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": "1"}], next_page_id="cursor-1"),
+ _response([{"id": "2"}]),
+ ],
+ )
+
+ manager = _FakeResumeManager()
+ _rows(_source("Leads", manager))
+
+ assert manager.saved == [HyrosResumeConfig(cursor="cursor-1")]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_cursor(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([{"id": "2"}])])
+
+ rows = _rows(_source("Leads", _FakeResumeManager(HyrosResumeConfig(cursor="cursor-1"))))
+
+ assert [r["id"] for r in rows] == ["2"]
+ assert session.send.call_count == 1
+ assert snapshots[0]["params"]["pageId"] == "cursor-1"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_missing_result_key_stops_quietly(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response(None, drop_key=True)])
+
+ rows = _rows(_source("Sources", _FakeResumeManager()))
+
+ assert rows == []
+ assert session.send.call_count == 1
+
+ @parameterized.expand(
+ [
+ ("Leads", "updatedFromDate"),
+ ("Sales", "fromDate"),
+ ("Calls", "fromDate"),
+ ("Subscriptions", "fromDate"),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_endpoint_sends_expected_date_param(self, endpoint, param_name, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([{"id": "1"}])])
+
+ _rows(
+ _source(
+ endpoint,
+ _FakeResumeManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+ )
+
+ assert snapshots[0]["params"][param_name] == "2026-03-04T02:58:14+00:00"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_endpoint_never_filters_by_date(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([{"id": "1"}])])
+
+ _rows(
+ _source(
+ "Stages",
+ _FakeResumeManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ )
+
+ assert snapshots[0]["params"] == {"pageSize": 250}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_endpoint_without_cursor_omits_date_param(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([{"id": "1"}])])
+
+ _rows(
+ _source(
+ "Leads", _FakeResumeManager(), should_use_incremental_field=True, db_incremental_field_last_value=None
+ )
+ )
+
+ assert snapshots[0]["params"] == {"pageSize": 250}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_response_shape_by_endpoint(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response([{"name": "!tag1", "amount": 3}])])
+
+ rows = _rows(_source("Tags", _FakeResumeManager()))
+
+ assert rows == [{"name": "!tag1", "amount": 3}]
+
+
+class TestValidateCredentials:
+ @mock.patch(HYROS_SESSION_PATCH)
+ def test_ok(self, mock_session) -> None:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+ assert validate_credentials("key") == (True, 200)
+
+ @mock.patch(HYROS_SESSION_PATCH)
+ def test_unauthorized(self, mock_session) -> None:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)
+ assert validate_credentials("key") == (False, 401)
+
+ @mock.patch(HYROS_SESSION_PATCH)
+ def test_swallows_transport_errors(self, mock_session) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key") == (False, None)
+
+ @mock.patch(HYROS_SESSION_PATCH)
+ def test_probes_user_info_with_api_key_header(self, mock_session) -> None:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+ validate_credentials("key")
+
+ call = mock_session.return_value.get.call_args
+ assert call.args[0] == "https://api.hyros.com/v1/api/v1.0/user-info"
+ assert call.kwargs["headers"]["API-Key"] == "key"
+ assert call.kwargs["allow_redirects"] is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/tests/test_hyros_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/tests/test_hyros_source.py
new file mode 100644
index 000000000000..3da4938125df
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyros/tests/test_hyros_source.py
@@ -0,0 +1,161 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hyros import HyrosSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.hyros.hyros import HyrosResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.hyros.settings import ENDPOINTS, HYROS_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.hyros.source import HyrosSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_INCREMENTAL_ENDPOINTS = {"Leads", "Sales", "Calls", "Subscriptions"}
+_FULL_REFRESH_ENDPOINTS = {"Sources", "Tags", "Keywords", "Stages"}
+
+
+class TestHyrosSource:
+ def setup_method(self):
+ self.source = HyrosSource()
+ self.team_id = 123
+ self.config = HyrosSourceConfig(api_key="key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.HYROS
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Hyros"
+ assert config.label == "Hyros"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/hyros.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/hyros"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ def test_api_version_metadata(self):
+ assert self.source.supported_versions == ("v1.0",)
+ assert self.source.default_version == "v1.0"
+ assert self.source.api_docs_url == "https://api-docs.hyros.com"
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.hyros.com/v1/api/v1.0/leads",
+ "403 Client Error: Forbidden for url: https://api.hyros.com/v1/api/v1.0/calls",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://api.hyros.com/v1/api/v1.0/leads",
+ "500 Server Error: Internal Server Error for url: https://api.hyros.com/v1/api/v1.0/leads",
+ "HTTPSConnectionPool(host='api.hyros.com', port=443): Read timed out.",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_transient(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ for name in _INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ expected_field = HYROS_ENDPOINTS[name].incremental_field_name
+ assert [f["field"] for f in schemas[name].incremental_fields] == [expected_field]
+ for name in _FULL_REFRESH_ENDPOINTS:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Leads"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "Leads"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_lists_tables_without_credentials_publishes_catalog(self):
+ assert self.source.lists_tables_without_credentials is True
+ documented = self.source.get_documented_tables()
+ assert {table["name"] for table in documented} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ canonical = self.source.get_canonical_descriptions()
+ assert set(canonical) == set(HYROS_ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ((True, 200), True, None),
+ ((False, 401), False, "Invalid Hyros API key"),
+ ((False, 403), False, "Invalid Hyros API key"),
+ ((False, None), False, "Invalid Hyros API key"),
+ ]
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hyros.source.validate_hyros_credentials"
+ )
+ def test_validate_credentials(self, mock_return, expected_valid, expected_message_prefix, mock_validate):
+ 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
+ if expected_message_prefix is None:
+ assert error_message is None
+ else:
+ assert error_message is not None
+ assert error_message.startswith(expected_message_prefix)
+ mock_validate.assert_called_once_with("key")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is HyrosResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.hyros.source.hyros_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_hyros_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Leads"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_hyros_source.assert_called_once()
+ kwargs = mock_hyros_source.call_args.kwargs
+ assert kwargs["api_key"] == "key"
+ assert kwargs["endpoint"] == "Leads"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.hyros.source.hyros_source")
+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_hyros_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Stages"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_hyros_source.call_args.kwargs["db_incremental_field_last_value"] is None