Skip to content

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

feat(data-warehouse): implement the singular import source (#110280)

Daniel RC313a6fd4b34b
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 72f0a59d9055..d4153e129b68 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -678,6 +678,7 @@ the row lists both.
| simplecast | HTTP | requests | ✅ |
| simplesat | HTTP | requests | ✅ |
| singlestore | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| singular | HTTP | requests | ✅ |
| skio | HTTP (GraphQL) | requests | ✅ |
| skyvern | HTTP | requests | ✅ |
| slack | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -1391,7 +1392,6 @@ doesn't conflict with concurrent PRs.
- simplesat
- simpro
- sinch
-- singular
- site24x7
- skyvern
- slash
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/singular.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/singular.py
index 01fa4dca2f88..385c313dffce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/singular.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/singular.py
@@ -6,4 +6,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class SingularSourceConfig(config.Config):
- pass
+ api_key: str
+ dimensions: str | None = None
+ metrics: str | None = None
+ cohort_metrics: str | None = None
+ cohort_periods: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singular/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/canonical_descriptions.py
new file mode 100644
index 000000000000..d3cbe395d407
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/canonical_descriptions.py
@@ -0,0 +1,57 @@
+"""Canonical, documentation-sourced descriptions for Singular tables and columns.
+
+Sourced from the Singular Reporting API reference and the Metrics and Dimensions glossary
+(https://support.singular.net/hc/en-us/articles/203389179). Keyed by the endpoint names in
+`settings.py`. The `daily_report` columns depend on the dimensions and metrics a source is set up
+with, so only the default ones are described here. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+REPORTING_API_URL = "https://support.singular.net/hc/en-us/articles/360045245692-Reporting-API-Reference"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "daily_report": {
+ "description": "Daily campaign statistics from the Singular Reporting API, one row per day and combination of the chosen dimensions.",
+ "docs_url": "https://support.singular.net/hc/en-us/articles/203389179-Metrics-and-Dimensions",
+ "columns": {
+ "date": "The day the row's statistics cover.",
+ "app": "The app name as configured in the Apps page.",
+ "source": "The name of the data source (usually the ad network).",
+ "os": "The operating system of the marketed product, such as iOS or Android.",
+ "country_field": "The user's country, as reported by the network or derived from the network's targeting settings.",
+ "adn_campaign_id": "The ID of the campaign, as pulled from the ad network.",
+ "adn_campaign_name": "The name of the campaign, as pulled from the ad network.",
+ "adn_cost": "Cost (ad spend) reported by the ad network, in the default currency configured in Singular.",
+ "adn_impressions": "The number of ad views as reported by the ad network.",
+ "adn_clicks": "The number of ad clicks as reported by the ad network.",
+ "adn_installs": "The number of app installs or total conversions as reported by the ad network.",
+ },
+ },
+ "custom_dimensions": {
+ "description": "A custom dimension defined in the Singular account. Use its ID as a dimension in a report.",
+ "docs_url": REPORTING_API_URL,
+ "columns": {
+ "id": "Identifier of the custom dimension, used in report queries.",
+ "display_name": "The name of the custom dimension as it appears in the Singular platform.",
+ },
+ },
+ "cohort_metrics": {
+ "description": "A cohort metric or in-app event available to the Singular account for report queries.",
+ "docs_url": REPORTING_API_URL,
+ "columns": {
+ "name": "The identifier of the metric for use in API queries.",
+ "display_name": "The name of the metric as it appears in the Singular platform.",
+ },
+ },
+ "conversion_metrics": {
+ "description": "A conversion event available to the Singular account, usable as a metric in report queries.",
+ "docs_url": REPORTING_API_URL,
+ "columns": {
+ "name": "The auto-generated identifier of the event, used in report queries.",
+ "display_name": "The name of the conversion event as configured in the Events page.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singular/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/settings.py
new file mode 100644
index 000000000000..66e5fa0d56c3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/settings.py
@@ -0,0 +1,58 @@
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+DAILY_REPORT = "daily_report"
+# Singular's report rows carry the day as `start_date`/`end_date`. The source adds one `date`
+# column per row so the cursor and the primary key do not depend on that shape.
+DATE_FIELD = "date"
+
+# Network data is the one report type every Singular account can query, so the defaults work for
+# an account that has no attribution tracker set up.
+DEFAULT_DIMENSIONS: tuple[str, ...] = (
+ "app",
+ "source",
+ "os",
+ "country_field",
+ "adn_campaign_id",
+ "adn_campaign_name",
+)
+DEFAULT_METRICS: tuple[str, ...] = ("adn_cost", "adn_impressions", "adn_clicks", "adn_installs")
+
+# A first sync reads this many days. Each day is one report, and every row counts against the
+# account's daily row quota, so a deeper default would fail the first sync of a large account.
+HISTORY_DAYS = 30
+# Networks restate recent days. Singular recommends re-reading 7 days of network data on each pull.
+REPORT_LOOKBACK_SECONDS = 7 * 24 * 60 * 60
+
+
+@frozen
+class SingularLookupConfig:
+ """One discovery endpoint that returns a complete list in a single response."""
+
+ path: str
+ data_key: str
+ primary_key: str
+
+
+LOOKUPS: dict[str, SingularLookupConfig] = {
+ "custom_dimensions": SingularLookupConfig(
+ path="/api/custom_dimensions", data_key="custom_dimensions", primary_key="id"
+ ),
+ "cohort_metrics": SingularLookupConfig(path="/api/cohort_metrics", data_key="metrics", primary_key="name"),
+ "conversion_metrics": SingularLookupConfig(path="/api/conversion_metrics", data_key="metrics", primary_key="name"),
+}
+
+ENDPOINTS: tuple[str, ...] = (DAILY_REPORT, *LOOKUPS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ DAILY_REPORT: [incremental_field(DATE_FIELD, IncrementalFieldType.Date)],
+}
+
+DESCRIPTIONS: dict[str, str] = {
+ DAILY_REPORT: "Daily campaign statistics, one row per day and combination of the dimensions you chose.",
+ "custom_dimensions": "The custom dimensions defined in your Singular account.",
+ "cohort_metrics": "The cohort metrics and events you can add to a report.",
+ "conversion_metrics": "The conversion events you can add to a report as metrics.",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singular/singular.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/singular.py
new file mode 100644
index 000000000000..003a9071e51b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/singular.py
@@ -0,0 +1,336 @@
+import json
+import time
+import datetime as dt
+from collections.abc import Callable, Iterator
+from itertools import batched
+from typing import Any, Optional
+from urllib.parse import parse_qsl, urlsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import Retrying, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.singular.settings import (
+ DAILY_REPORT,
+ DATE_FIELD,
+ HISTORY_DAYS,
+ LOOKUPS,
+ SingularLookupConfig,
+)
+
+BASE_URL = "https://api.singular.net"
+REQUEST_TIMEOUT_SECONDS = 60
+DOWNLOAD_TIMEOUT_SECONDS = 300
+CREATE_MAX_ATTEMPTS = 5
+# Singular allows one status call per report every 10 seconds.
+REPORT_POLL_INTERVAL_SECONDS = 15
+# Singular treats a report that is not done after 30 minutes as stuck and says to submit it again.
+REPORT_POLL_MAX_ATTEMPTS = 30 * 60 // REPORT_POLL_INTERVAL_SECONDS
+ROWS_PER_BATCH = 5000
+
+# `get_non_retryable_errors` matches on these, so each one must stay the start of its message.
+AUTH_ERROR = "Singular rejected the API key"
+ACCESS_ERROR = "Singular denied access"
+REQUEST_ERROR = "Singular rejected the request"
+REPORT_FAILED_ERROR = "Singular could not generate the report"
+QUOTA_ERROR = "Singular is still rate limiting this API key"
+# `get_retryable_errors` matches on this one.
+RETRYABLE_ERROR = "Singular request failed and can be retried"
+
+
+class SingularRetryableError(Exception):
+ def __init__(self, detail: str) -> None:
+ super().__init__(f"{RETRYABLE_ERROR}: {detail}")
+ self.detail = detail
+
+
+class SingularRateLimitError(SingularRetryableError):
+ pass
+
+
+class SingularNonRetryableError(Exception):
+ pass
+
+
+@frozen
+class SingularResumeConfig:
+ """The first day a retried run still has to fetch."""
+
+ next_date: str
+
+
+@frozen
+class SingularReportQuery:
+ dimensions: tuple[str, ...]
+ metrics: tuple[str, ...]
+ cohort_metrics: tuple[str, ...] = ()
+ cohort_periods: tuple[str, ...] = ()
+
+
+def parse_field_list(value: Optional[str], default: tuple[str, ...] = ()) -> tuple[str, ...]:
+ names = [name.strip() for name in (value or "").split(",")]
+ # Singular rejects a request that names a field twice.
+ return tuple(dict.fromkeys(name for name in names if name)) or default
+
+
+def as_date(value: Any) -> Optional[dt.date]:
+ """Read the stored `date` cursor, which arrives as a date, a datetime, or a YYYY-MM-DD string."""
+ if isinstance(value, dt.datetime):
+ return value.date()
+ if isinstance(value, dt.date):
+ return value
+ if isinstance(value, str) and value:
+ try:
+ return dt.date.fromisoformat(value[:10])
+ except ValueError:
+ return None
+ return None
+
+
+def report_request_payload(query: SingularReportQuery, day: dt.date) -> dict[str, str]:
+ payload = {
+ "dimensions": ",".join(query.dimensions),
+ "metrics": ",".join(query.metrics),
+ "start_date": day.isoformat(),
+ "end_date": day.isoformat(),
+ "time_breakdown": "day",
+ "format": "json",
+ }
+ if query.cohort_metrics:
+ payload["cohort_metrics"] = ",".join(query.cohort_metrics)
+ if query.cohort_periods:
+ payload["cohort_periods"] = ",".join(query.cohort_periods)
+ return payload
+
+
+def report_rows(body: Any) -> list[dict[str, Any]]:
+ # Singular does not document the downloaded file. Its synchronous API wraps the rows as
+ # `value.results`, so accept that envelope, a bare `results` object, and a bare list.
+ if isinstance(body, dict):
+ body = body.get("value", body)
+ if isinstance(body, dict):
+ body = body.get("results")
+ if not isinstance(body, list):
+ raise ValueError("Singular report file has an unrecognized shape")
+ return body
+
+
+def _error_detail(response: requests.Response) -> str:
+ try:
+ body = response.json()
+ except ValueError:
+ return response.text[:500]
+ value = body.get("value") if isinstance(body, dict) else None
+ return value if isinstance(value, str) else response.text[:500]
+
+
+def _response_value(response: requests.Response) -> dict[str, Any]:
+ """Unwrap Singular's `{"status", "substatus", "value"}` envelope, or raise for a failed call."""
+ status = response.status_code
+ if status == 429:
+ raise SingularRateLimitError(_error_detail(response))
+ if status >= 500:
+ raise SingularRetryableError(f"status={status}")
+ if status == 401:
+ raise SingularNonRetryableError(
+ f"{AUTH_ERROR}. Copy the current key from Developer Tools > API Keys in Singular and update this source. "
+ f"Singular said: {_error_detail(response)}"
+ )
+ if status == 403:
+ raise SingularNonRetryableError(
+ f"{ACCESS_ERROR}. Ask a Singular admin to let this API key view every dimension and metric in the "
+ f"source settings, or remove the ones it cannot view. Singular said: {_error_detail(response)}"
+ )
+
+ value = None
+ if response.ok:
+ try:
+ body = response.json()
+ except ValueError:
+ # A proxy page with a success status is not Singular's answer, so the call is worth repeating.
+ raise SingularRetryableError(f"status={status} with a body that is not JSON") from None
+ value = body.get("value") if isinstance(body, dict) else None
+ if not isinstance(value, dict):
+ raise SingularNonRetryableError(
+ f"{REQUEST_ERROR}. Check the dimensions, metrics, and cohort settings of this source. "
+ f"Singular said: {_error_detail(response)}"
+ )
+ return value
+
+
+class SingularClient:
+ def __init__(self, api_key: str, api_version: str) -> None:
+ self.api_version = api_version
+ self.session = make_tracked_session(headers={"Authorization": api_key}, redact_values=(api_key,))
+ # A report status body carries the presigned download URL, so those calls stay out of
+ # sample capture.
+ self.status_session = make_tracked_session(
+ headers={"Authorization": api_key}, redact_values=(api_key,), capture=False
+ )
+ # The transport retries only GETs, so the report POST needs its own bounded retry.
+ self._create_retrying = Retrying(
+ retry=retry_if_exception_type((SingularRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(CREATE_MAX_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=5, max=60),
+ reraise=True,
+ )
+
+ def get(self, path: str, params: Optional[dict[str, str]] = None, capture: bool = True) -> dict[str, Any]:
+ session = self.session if capture else self.status_session
+ return _response_value(session.get(f"{BASE_URL}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS))
+
+ def _post_report(self, query: SingularReportQuery, day: dt.date) -> dict[str, Any]:
+ return _response_value(
+ self.session.post(
+ f"{BASE_URL}/api/{self.api_version}/create_async_report",
+ data=report_request_payload(query, day),
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ )
+
+ def create_report(self, query: SingularReportQuery, day: dt.date) -> str:
+ try:
+ value = self._create_retrying(self._post_report, query, day)
+ except SingularRateLimitError as error:
+ # Singular does not document how it reports a used-up daily row quota. A 429 that
+ # outlasts the retries is the closest signal, and waiting longer inside one run cannot
+ # clear it, so it stops the sync instead of retrying the whole activity.
+ raise SingularNonRetryableError(
+ f"{QUOTA_ERROR} after several retries. If the account has used its daily row quota, sync again "
+ f"tomorrow. To use fewer rows, remove dimensions or sync less often. Singular said: {error.detail}"
+ ) from error
+
+ report_id = value.get("report_id")
+ if not report_id:
+ raise SingularNonRetryableError(
+ f"{REQUEST_ERROR}. Singular did not return a report ID for {day.isoformat()}: {json.dumps(value)}"
+ )
+ return str(report_id)
+
+ def await_download_url(self, report_id: str, day: dt.date, safe_point: Callable[[], None]) -> str:
+ status = None
+ for _attempt in range(REPORT_POLL_MAX_ATTEMPTS):
+ value = self.get(
+ f"/api/{self.api_version}/get_report_status", params={"report_id": report_id}, capture=False
+ )
+ status = value.get("status")
+
+ if status == "DONE" and value.get("download_url"):
+ return str(value["download_url"])
+ if status == "FAILED":
+ # The report ID stays in the message because Singular support asks for it.
+ raise SingularNonRetryableError(
+ f"{REPORT_FAILED_ERROR} for {day.isoformat()}. Singular said: {json.dumps(value)}"
+ )
+
+ # A worker that shuts down during a long wait hands the run over here.
+ safe_point()
+ time.sleep(REPORT_POLL_INTERVAL_SECONDS)
+
+ raise SingularRetryableError(
+ f"report {report_id} for {day.isoformat()} still {status} after the polling budget"
+ )
+
+ def download_report(self, url: str) -> list[dict[str, Any]]:
+ # The file sits on presigned storage, so the session carries no API key, and the signing
+ # values in the URL are masked in the request log.
+ signing_values = tuple(value for _name, value in parse_qsl(urlsplit(url).query) if len(value) >= 8)
+ session = make_tracked_session(redact_values=signing_values, capture=False)
+ response = session.get(url, timeout=DOWNLOAD_TIMEOUT_SECONDS)
+ if not response.ok:
+ # `raise_for_status` would put the presigned URL in the error the user reads.
+ raise SingularRetryableError(f"report download returned status={response.status_code}")
+ return report_rows(response.json())
+
+
+def validate_credentials(api_key: str, api_version: str) -> tuple[bool, Optional[str]]:
+ try:
+ SingularClient(api_key, api_version).get(LOOKUPS["custom_dimensions"].path)
+ except SingularNonRetryableError as error:
+ return False, str(error)
+ except Exception:
+ return False, "Could not reach Singular to check the API key. Try again in a few minutes."
+ return True, None
+
+
+def report_start_date(
+ today: dt.date, db_incremental_field_last_value: Optional[Any], history_start: Optional[dt.datetime]
+) -> dt.date:
+ cursor = as_date(db_incremental_field_last_value)
+ if cursor is not None:
+ return cursor
+ if history_start is not None:
+ return history_start.date()
+ return today - dt.timedelta(days=HISTORY_DAYS)
+
+
+def _report_rows(
+ client: SingularClient,
+ query: SingularReportQuery,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SingularResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ history_start: Optional[dt.datetime],
+) -> Iterator[list[dict[str, Any]]]:
+ today = dt.datetime.now(dt.UTC).date()
+ day = report_start_date(today, db_incremental_field_last_value, history_start)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ day = max(day, dt.date.fromisoformat(resume.next_date))
+
+ # Singular recommends one report per day when pulling daily data.
+ while day <= today:
+ report_id = client.create_report(query, day)
+ url = client.await_download_url(report_id, day, resumable_source_manager.safe_point)
+ rows = client.download_report(url)
+ logger.debug(f"Singular report for {day.isoformat()} returned {len(rows)} rows")
+
+ for chunk in batched(rows, ROWS_PER_BATCH, strict=False):
+ yield [{**row, DATE_FIELD: day} for row in chunk]
+
+ day += dt.timedelta(days=1)
+ resumable_source_manager.save_state(SingularResumeConfig(next_date=day.isoformat()))
+
+
+def _lookup_rows(client: SingularClient, config: SingularLookupConfig) -> Iterator[list[dict[str, Any]]]:
+ rows = client.get(config.path).get(config.data_key) or []
+ if rows:
+ yield rows
+
+
+def singular_source(
+ api_key: str,
+ api_version: str,
+ endpoint: str,
+ query: SingularReportQuery,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SingularResumeConfig],
+ db_incremental_field_last_value: Optional[Any] = None,
+ history_start: Optional[dt.datetime] = None,
+) -> SourceResponse:
+ is_report = endpoint == DAILY_REPORT
+
+ def items() -> Iterator[list[dict[str, Any]]]:
+ client = SingularClient(api_key, api_version)
+ if is_report:
+ return _report_rows(
+ client, query, logger, resumable_source_manager, db_incremental_field_last_value, history_start
+ )
+ return _lookup_rows(client, LOOKUPS[endpoint])
+
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=[DATE_FIELD, *query.dimensions] if is_report else [LOOKUPS[endpoint].primary_key],
+ partition_mode="datetime" if is_report else None,
+ partition_format="month" if is_report else None,
+ partition_keys=[DATE_FIELD] if is_report else None,
+ sort_mode="asc",
+ supports_resume=is_report,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singular/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/source.py
index 1bcdc804b125..b84dd341a976 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/singular/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/source.py
@@ -1,28 +1,221 @@
-from typing import cast
+import datetime as dt
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+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.singular import (
SingularSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.singular.settings import (
+ DAILY_REPORT,
+ DEFAULT_DIMENSIONS,
+ DEFAULT_METRICS,
+ DESCRIPTIONS,
+ ENDPOINTS,
+ HISTORY_DAYS,
+ INCREMENTAL_FIELDS,
+ LOOKUPS,
+ REPORT_LOOKBACK_SECONDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.singular.singular import (
+ ACCESS_ERROR,
+ AUTH_ERROR,
+ QUOTA_ERROR,
+ REPORT_FAILED_ERROR,
+ REQUEST_ERROR,
+ RETRYABLE_ERROR,
+ SingularReportQuery,
+ SingularResumeConfig,
+ parse_field_list,
+ singular_source,
+ validate_credentials as validate_singular_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+SOURCE_CAPTION = """Enter your Singular API key to sync campaign reports into the PostHog Data warehouse. You can find the key in Singular under **Developer Tools > API Keys**.
+
+The `daily_report` table has one row per day for each combination of the dimensions you choose. Leave the dimensions and metrics empty to sync network campaign data: cost, impressions, clicks, and installs by app, source, OS, country, and campaign.
+
+Every row counts toward your Singular daily row limit (3 million rows by default), so each dimension you add uses more of it."""
+
+
+def report_query(config: SingularSourceConfig) -> SingularReportQuery:
+ return SingularReportQuery(
+ dimensions=parse_field_list(config.dimensions, DEFAULT_DIMENSIONS),
+ metrics=parse_field_list(config.metrics, DEFAULT_METRICS),
+ cohort_metrics=parse_field_list(config.cohort_metrics),
+ cohort_periods=parse_field_list(config.cohort_periods),
+ )
+
@SourceRegistry.register
-class SingularSource(SimpleSource[SingularSourceConfig]):
+class SingularSource(ResumableSource[SingularSourceConfig, SingularResumeConfig]):
+ supported_versions = ("v2.0",)
+ default_version = "v2.0"
+ api_docs_url = "https://support.singular.net/hc/en-us/articles/360045245692-Reporting-API-Reference"
+
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ history_lookback = dt.timedelta(days=HISTORY_DAYS)
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SINGULAR
+ def resume_covers_run(
+ self,
+ *,
+ incremental_or_append: bool,
+ keyset_full_load_enabled: bool = False,
+ schema_name: str | None = None,
+ ) -> bool:
+ # A lookup table is one request, so a retry has nothing to continue from.
+ return schema_name not in LOOKUPS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # The raised messages already name the fix and quote Singular's own error text.
+ return {
+ AUTH_ERROR: None,
+ ACCESS_ERROR: None,
+ REQUEST_ERROR: None,
+ REPORT_FAILED_ERROR: None,
+ QUOTA_ERROR: None,
+ }
+
+ def get_retryable_errors(self) -> set[str]:
+ return {RETRYABLE_ERROR}
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.SINGULAR,
category=DataWarehouseSourceCategory.ADVERTISING,
label="Singular",
+ caption=SOURCE_CAPTION,
iconPath="/static/services/singular.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/singular",
keywords=["mmp", "attribution", "marketing measurement"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="dimensions",
+ label="Dimensions",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder=",".join(DEFAULT_DIMENSIONS),
+ secret=False,
+ caption="Comma-separated dimension names from the Singular Reporting API. For a custom dimension, use its ID. If you change the dimensions later, run a full resync of the `daily_report` table.",
+ ),
+ SourceFieldInputConfig(
+ name="metrics",
+ label="Metrics",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder=",".join(DEFAULT_METRICS),
+ secret=False,
+ caption="Comma-separated metric names from the Singular Reporting API. For a conversion event, use its name from the `conversion_metrics` table, not its display name.",
+ ),
+ SourceFieldInputConfig(
+ name="cohort_metrics",
+ label="Cohort metrics",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="revenue",
+ secret=False,
+ caption="Comma-separated cohort metric names from the `cohort_metrics` table, such as `revenue`. Cohort metrics need at least one cohort period.",
+ ),
+ SourceFieldInputConfig(
+ name="cohort_periods",
+ label="Cohort periods",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="7d,30d",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.singular.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SingularSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ schemas = build_endpoint_schemas(
+ ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only={DAILY_REPORT}, descriptions=DESCRIPTIONS
+ )
+ for schema in schemas:
+ if schema.supports_incremental:
+ schema.default_incremental_lookback_seconds = REPORT_LOOKBACK_SECONDS
+ return schemas
+
+ def validate_credentials(
+ self,
+ config: SingularSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ query = report_query(config)
+ if bool(query.cohort_metrics) != bool(query.cohort_periods):
+ return False, "Cohort metrics and cohort periods go together. Fill in both fields or leave both empty."
+
+ return validate_singular_credentials(config.api_key, self.resolve_api_version(api_version))
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SingularResumeConfig]:
+ return ResumableSourceManager[SingularResumeConfig](inputs, SingularResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SingularSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SingularResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return singular_source(
+ api_key=config.api_key,
+ api_version=self.resolve_api_version(inputs.api_version),
+ endpoint=inputs.schema_name,
+ query=report_query(config),
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ history_start=inputs.history_start,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singular/tests/test_singular.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/tests/test_singular.py
new file mode 100644
index 000000000000..6a4076d10635
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/tests/test_singular.py
@@ -0,0 +1,423 @@
+import json
+import datetime as dt
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+import time_machine
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
+from products.warehouse_sources.backend.temporal.data_imports.sources.singular.settings import HISTORY_DAYS, LOOKUPS
+from products.warehouse_sources.backend.temporal.data_imports.sources.singular.singular import (
+ ACCESS_ERROR,
+ AUTH_ERROR,
+ CREATE_MAX_ATTEMPTS,
+ QUOTA_ERROR,
+ REPORT_FAILED_ERROR,
+ REPORT_POLL_MAX_ATTEMPTS,
+ REQUEST_ERROR,
+ SingularNonRetryableError,
+ SingularReportQuery,
+ SingularResumeConfig,
+ SingularRetryableError,
+ parse_field_list,
+ report_rows,
+ report_start_date,
+ singular_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.singular.source import SingularSource
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.singular.singular"
+_API_KEY = "sk-invented-key"
+_DOWNLOAD_URL = "https://reports.example.com/files/report.json?Signature=invented-signature"
+_NOW = "2026-06-30T12:00:00Z"
+_QUERY = SingularReportQuery(dimensions=("app", "source"), metrics=("adn_cost",))
+
+
+def _response(status: int = 200, value: Any = None) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status
+ resp.ok = status < 400
+ body = {"status": 0 if status < 400 else status, "substatus": 0, "value": value}
+ resp.json.return_value = body
+ resp.text = json.dumps(body)
+ return resp
+
+
+def _file_response(rows: Any, status: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status
+ resp.ok = status < 400
+ resp.json.return_value = rows
+ return resp
+
+
+def _wire(
+ mock_session: mock.MagicMock,
+ rows_by_day: dict[str, list[dict[str, Any]]] | None = None,
+ poll_statuses: list[str] | None = None,
+ create_responses: list[mock.MagicMock] | None = None,
+) -> list[dict[str, str]]:
+ created: list[dict[str, str]] = []
+ statuses = list(poll_statuses or ["DONE"])
+ queued = list(create_responses or [])
+ polled_day: list[str] = []
+
+ def post(url: str, **kwargs: Any) -> mock.MagicMock:
+ if queued:
+ response = queued.pop(0)
+ if not response.ok:
+ return response
+ created.append(kwargs["data"])
+ return _response(value={"report_id": kwargs["data"]["start_date"]})
+
+ def get(url: str, **kwargs: Any) -> mock.MagicMock:
+ if url.endswith("/get_report_status"):
+ polled_day.append(kwargs["params"]["report_id"])
+ status = statuses.pop(0) if len(statuses) > 1 else statuses[0]
+ return _response(
+ value={
+ "status": status,
+ "report_id": polled_day[-1],
+ "download_url": _DOWNLOAD_URL if status == "DONE" else None,
+ }
+ )
+ return _file_response({"value": {"results": (rows_by_day or {}).get(polled_day[-1], [])}})
+
+ mock_session.return_value.post.side_effect = post
+ mock_session.return_value.get.side_effect = get
+ return created
+
+
+def _resume_manager(state: SingularResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = state is not None
+ manager.load_state.return_value = state
+ return manager
+
+
+def _report_batches(
+ manager: mock.MagicMock | None = None, last_value: Any = None, query: SingularReportQuery = _QUERY
+) -> list[list[dict[str, Any]]]:
+ response = singular_source(
+ api_key=_API_KEY,
+ api_version="v2.0",
+ endpoint="daily_report",
+ query=query,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager or _resume_manager(),
+ db_incremental_field_last_value=last_value,
+ )
+ return list(cast(Iterable[list[dict[str, Any]]], response.items()))
+
+
[email protected](f"{_MODULE}.time.sleep")
[email protected](f"{_MODULE}.make_tracked_session")
+class TestDailyReport:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(_NOW, tick=False):
+ yield
+
+ def test_requests_one_report_per_day_in_date_order(self, mock_session, _sleep):
+ created = _wire(
+ mock_session,
+ rows_by_day={
+ "2026-06-28": [{"app": "Invented App", "source": "Example Ads", "adn_cost": 1.5}],
+ "2026-06-30": [{"app": "Invented App", "source": "Example Ads", "adn_cost": 2.5}],
+ },
+ )
+ manager = _resume_manager()
+
+ batches = _report_batches(manager, last_value="2026-06-28")
+
+ assert [(body["start_date"], body["end_date"]) for body in created] == [
+ ("2026-06-28", "2026-06-28"),
+ ("2026-06-29", "2026-06-29"),
+ ("2026-06-30", "2026-06-30"),
+ ]
+ assert created[0] == {
+ "dimensions": "app,source",
+ "metrics": "adn_cost",
+ "start_date": "2026-06-28",
+ "end_date": "2026-06-28",
+ "time_breakdown": "day",
+ "format": "json",
+ }
+ assert [row["date"] for batch in batches for row in batch] == [dt.date(2026, 6, 28), dt.date(2026, 6, 30)]
+ assert [call.args[0].next_date for call in manager.save_state.call_args_list] == [
+ "2026-06-29",
+ "2026-06-30",
+ "2026-07-01",
+ ]
+
+ def test_api_key_travels_in_a_header_and_never_in_a_url(self, mock_session, _sleep):
+ _wire(mock_session)
+
+ _report_batches(last_value="2026-06-30")
+
+ assert mock_session.call_args_list[0].kwargs["headers"] == {"Authorization": _API_KEY}
+ session = mock_session.return_value
+ for call in [*session.post.call_args_list, *session.get.call_args_list]:
+ assert _API_KEY not in call.args[0]
+ assert _API_KEY not in json.dumps(call.kwargs.get("params") or {})
+
+ def test_cohort_fields_are_sent_only_when_set(self, mock_session, _sleep):
+ created = _wire(mock_session)
+ query = SingularReportQuery(
+ dimensions=("app",), metrics=("adn_cost",), cohort_metrics=("revenue",), cohort_periods=("7d", "30d")
+ )
+
+ _report_batches(last_value="2026-06-30", query=query)
+
+ assert created[0]["cohort_metrics"] == "revenue"
+ assert created[0]["cohort_periods"] == "7d,30d"
+
+ def test_retried_run_continues_from_the_saved_day(self, mock_session, _sleep):
+ created = _wire(mock_session)
+
+ _report_batches(_resume_manager(SingularResumeConfig(next_date="2026-06-29")), last_value="2026-06-01")
+
+ assert [body["start_date"] for body in created] == ["2026-06-29", "2026-06-30"]
+
+ def test_polls_until_done_and_reaches_a_safe_point_on_each_wait(self, mock_session, sleep):
+ _wire(
+ mock_session,
+ rows_by_day={"2026-06-30": [{"app": "Invented App", "source": "Example Ads"}]},
+ poll_statuses=["QUEUED", "STARTED", "DONE"],
+ )
+ manager = _resume_manager()
+
+ batches = _report_batches(manager, last_value="2026-06-30")
+
+ assert len(batches) == 1
+ assert sleep.call_count == 2
+ assert manager.safe_point.call_count == 2
+
+ def test_report_that_never_finishes_stops_after_the_polling_budget(self, mock_session, _sleep):
+ _wire(mock_session, poll_statuses=["STARTED"])
+
+ with pytest.raises(SingularRetryableError, match="still STARTED"):
+ _report_batches(last_value="2026-06-30")
+
+ polls = [c for c in mock_session.return_value.get.call_args_list if c.args[0].endswith("/get_report_status")]
+ assert len(polls) == REPORT_POLL_MAX_ATTEMPTS
+
+ def test_failed_report_is_non_retryable_and_keeps_singulars_reason(self, mock_session, _sleep):
+ _wire(mock_session, poll_statuses=["FAILED"])
+
+ with pytest.raises(SingularNonRetryableError, match=REPORT_FAILED_ERROR) as raised:
+ _report_batches(last_value="2026-06-30")
+
+ assert "2026-06-30" in str(raised.value)
+ assert error_message_matches(str(raised.value), SingularSource().get_non_retryable_errors())
+
+ @pytest.mark.parametrize(
+ "status, vendor_message, expected_prefix",
+ [
+ (401, "An invalid API Key was given.", AUTH_ERROR),
+ (
+ 401,
+ "The provided API key has been previously deactivated. Please contact your administrator.",
+ AUTH_ERROR,
+ ),
+ (403, "The provided API key does not have permissions to view the field: adn_cost", ACCESS_ERROR),
+ (400, "The request contains invalid dimensions: not_a_dimension", REQUEST_ERROR),
+ (400, "The request contains invalid metrics: not_a_metric", REQUEST_ERROR),
+ (400, "We could not find cohort periods for the following cohort metrics: revenue.", REQUEST_ERROR),
+ ],
+ )
+ def test_rejected_report_request_is_non_retryable_and_quotes_singular(
+ self, mock_session, _sleep, status, vendor_message, expected_prefix
+ ):
+ _wire(mock_session, create_responses=[_response(status, vendor_message)])
+
+ with pytest.raises(SingularNonRetryableError) as raised:
+ _report_batches(last_value="2026-06-30")
+
+ message = str(raised.value)
+ assert message.startswith(expected_prefix)
+ assert vendor_message in message
+ assert error_message_matches(message, SingularSource().get_non_retryable_errors())
+ assert mock_session.return_value.post.call_count == 1
+
+ @pytest.mark.parametrize(
+ "status, vendor_message, expected_error",
+ [
+ (429, "Too many requests. Only 10 requests per second is currently allowed.", SingularNonRetryableError),
+ (500, "The request has failed due to an internal error.", SingularRetryableError),
+ ],
+ )
+ def test_throttled_or_failing_report_request_stops_after_bounded_retries(
+ self, mock_session, _sleep, status, vendor_message, expected_error
+ ):
+ _wire(mock_session, create_responses=[_response(status, vendor_message)] * CREATE_MAX_ATTEMPTS)
+
+ with pytest.raises(expected_error) as raised:
+ _report_batches(last_value="2026-06-30")
+
+ assert mock_session.return_value.post.call_count == CREATE_MAX_ATTEMPTS
+ source = SingularSource()
+ assert error_message_matches(str(raised.value), source.get_non_retryable_errors()) is (status == 429)
+ assert error_message_matches(str(raised.value), source.get_retryable_errors()) is (status != 429)
+ if status == 429:
+ assert str(raised.value).startswith(QUOTA_ERROR)
+ assert vendor_message in str(raised.value)
+
+ def test_success_status_with_a_non_json_body_is_retryable(self, mock_session, _sleep):
+ page = _response()
+ page.json.side_effect = ValueError("not JSON")
+ mock_session.return_value.post.side_effect = None
+ mock_session.return_value.post.return_value = page
+
+ with pytest.raises(SingularRetryableError) as raised:
+ _report_batches(last_value="2026-06-30")
+
+ source = SingularSource()
+ assert error_message_matches(str(raised.value), source.get_retryable_errors())
+ assert not error_message_matches(str(raised.value), source.get_non_retryable_errors())
+
+ def test_report_request_recovers_from_a_short_throttle(self, mock_session, _sleep):
+ created = _wire(mock_session, create_responses=[_response(429, "Too many requests."), _response(500)])
+
+ _report_batches(last_value="2026-06-30")
+
+ assert [body["start_date"] for body in created] == ["2026-06-30"]
+
+ def test_failed_download_does_not_leak_the_presigned_url(self, mock_session, _sleep):
+ _wire(mock_session)
+ status_get = mock_session.return_value.get.side_effect
+
+ def get(url: str, **kwargs: Any) -> mock.MagicMock:
+ return _file_response(None, status=403) if url == _DOWNLOAD_URL else status_get(url, **kwargs)
+
+ mock_session.return_value.get.side_effect = get
+
+ with pytest.raises(SingularRetryableError) as raised:
+ _report_batches(last_value="2026-06-30")
+
+ assert "invented-signature" not in str(raised.value)
+ assert not error_message_matches(str(raised.value), SingularSource().get_non_retryable_errors())
+
+
+class TestReportShaping:
+ @pytest.mark.parametrize(
+ "last_value, history_start, expected",
+ [
+ ("2026-06-23", None, dt.date(2026, 6, 23)),
+ (dt.date(2026, 6, 23), None, dt.date(2026, 6, 23)),
+ (dt.datetime(2026, 6, 23, 8, 0, tzinfo=dt.UTC), None, dt.date(2026, 6, 23)),
+ ("2026-06-23", dt.datetime(2026, 1, 1, tzinfo=dt.UTC), dt.date(2026, 6, 23)),
+ (None, dt.datetime(2026, 5, 2, 9, 30, tzinfo=dt.UTC), dt.date(2026, 5, 2)),
+ (None, None, dt.date(2026, 6, 30) - dt.timedelta(days=HISTORY_DAYS)),
+ ],
+ )
+ def test_report_start_date(self, last_value, history_start, expected):
+ assert report_start_date(dt.date(2026, 6, 30), last_value, history_start) == expected
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ [{"app": "Invented App"}],
+ {"results": [{"app": "Invented App"}]},
+ {"status": 0, "substatus": 0, "value": {"results": [{"app": "Invented App"}]}},
+ ],
+ )
+ def test_report_rows_accepts_each_known_file_shape(self, body):
+ assert report_rows(body) == [{"app": "Invented App"}]
+
+ @pytest.mark.parametrize("body", [{"value": "not rows"}, {"value": {"rows": []}}, "text", None])
+ def test_report_rows_rejects_an_unrecognized_file(self, body):
+ with pytest.raises(ValueError):
+ report_rows(body)
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, ("app", "source")),
+ (" ", ("app", "source")),
+ (" os , country_field,,os ", ("os", "country_field")),
+ ],
+ )
+ def test_parse_field_list(self, value, expected):
+ assert parse_field_list(value, ("app", "source")) == expected
+
+ def test_report_primary_key_is_the_date_plus_the_chosen_dimensions(self):
+ response = singular_source(
+ api_key=_API_KEY,
+ api_version="v2.0",
+ endpoint="daily_report",
+ query=SingularReportQuery(dimensions=("app", "os", "invented_custom_dimension_id"), metrics=("adn_cost",)),
+ logger=mock.MagicMock(),
+ resumable_source_manager=_resume_manager(),
+ )
+
+ assert response.primary_keys == ["date", "app", "os", "invented_custom_dimension_id"]
+
+
[email protected](f"{_MODULE}.make_tracked_session")
+class TestLookups:
+ @pytest.mark.parametrize(
+ "endpoint, value, expected_rows",
+ [
+ (
+ "custom_dimensions",
+ {"custom_dimensions": [{"display_name": "Channel", "id": "invented-dimension-1"}]},
+ [[{"display_name": "Channel", "id": "invented-dimension-1"}]],
+ ),
+ (
+ "cohort_metrics",
+ {"metrics": [{"display_name": "Revenue", "name": "revenue"}], "periods": ["7d", "30d"]},
+ [[{"display_name": "Revenue", "name": "revenue"}]],
+ ),
+ (
+ "conversion_metrics",
+ {"metrics": [{"display_name": "Sign up", "name": "invented-event-1"}]},
+ [[{"display_name": "Sign up", "name": "invented-event-1"}]],
+ ),
+ ("custom_dimensions", {"custom_dimensions": []}, []),
+ ],
+ )
+ def test_lookup_reads_its_list_from_one_request(self, mock_session, endpoint, value, expected_rows):
+ mock_session.return_value.get.return_value = _response(value=value)
+
+ response = singular_source(
+ api_key=_API_KEY,
+ api_version="v2.0",
+ endpoint=endpoint,
+ query=_QUERY,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_resume_manager(),
+ )
+
+ assert list(cast(Iterable[Any], response.items())) == expected_rows
+ assert response.primary_keys == [LOOKUPS[endpoint].primary_key]
+ mock_session.return_value.get.assert_called_once()
+ assert mock_session.return_value.get.call_args.args[0] == f"https://api.singular.net{LOOKUPS[endpoint].path}"
+
+
[email protected](f"{_MODULE}.make_tracked_session")
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "response, expected_valid, expected_message_part",
+ [
+ (_response(value={"custom_dimensions": []}), True, None),
+ (_response(401, "An invalid API Key was given."), False, AUTH_ERROR),
+ (_response(403, "The request is denied access. Please contact your administrator."), False, ACCESS_ERROR),
+ (requests.ConnectionError("connection refused"), False, "Could not reach Singular"),
+ ],
+ )
+ def test_validate_credentials(self, mock_session, response, expected_valid, expected_message_part):
+ mock_session.return_value.get.side_effect = [response]
+
+ is_valid, message = validate_credentials(_API_KEY, "v2.0")
+
+ assert is_valid is expected_valid
+ if expected_message_part is None:
+ assert message is None
+ else:
+ assert message is not None and expected_message_part in message
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singular/tests/test_singular_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/tests/test_singular_source.py
new file mode 100644
index 000000000000..381d22dd3fc7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singular/tests/test_singular_source.py
@@ -0,0 +1,75 @@
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.singular import (
+ SingularSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.singular.settings import (
+ DEFAULT_DIMENSIONS,
+ DEFAULT_METRICS,
+ LOOKUPS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.singular.source import (
+ SingularSource,
+ report_query,
+)
+
+_VALIDATE = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.singular.source.validate_singular_credentials"
+)
+
+
+class TestSingularSource:
+ def setup_method(self):
+ self.source = SingularSource()
+ self.team_id = 123
+
+ def test_report_merges_on_date_with_a_lookback_and_lookups_are_full_refresh(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(SingularSourceConfig(api_key="k"), 1)}
+
+ report = schemas.pop("daily_report")
+ assert report.supports_incremental
+ assert not report.supports_append
+ assert [field["field"] for field in report.incremental_fields] == ["date"]
+ assert report.default_incremental_lookback_seconds == 7 * 24 * 60 * 60
+
+ assert set(schemas) == set(LOOKUPS)
+ for lookup in schemas.values():
+ assert not lookup.supports_incremental
+ assert lookup.default_incremental_lookback_seconds is None
+
+ def test_empty_inputs_fall_back_to_the_default_report(self):
+ query = report_query(SingularSourceConfig(api_key="k"))
+
+ assert query.dimensions == DEFAULT_DIMENSIONS
+ assert query.metrics == DEFAULT_METRICS
+ assert query.cohort_metrics == ()
+ assert query.cohort_periods == ()
+
+ @pytest.mark.parametrize(
+ "cohort_metrics, cohort_periods",
+ [("revenue", None), (None, "7d"), ("revenue", " , ")],
+ )
+ @mock.patch(_VALIDATE)
+ def test_cohort_fields_must_be_set_together(self, mock_validate, cohort_metrics, cohort_periods):
+ config = SingularSourceConfig(api_key="k", cohort_metrics=cohort_metrics, cohort_periods=cohort_periods)
+
+ is_valid, message = self.source.validate_credentials(config, self.team_id)
+
+ assert is_valid is False
+ assert message is not None and "Cohort metrics and cohort periods go together" in message
+ mock_validate.assert_not_called()
+
+ @mock.patch(_VALIDATE, return_value=(True, None))
+ def test_valid_inputs_reach_the_api_key_check(self, mock_validate):
+ config = SingularSourceConfig(api_key="k", cohort_metrics="revenue", cohort_periods="7d")
+
+ assert self.source.validate_credentials(config, self.team_id) == (True, None)
+ mock_validate.assert_called_once_with("k", "v2.0")
+
+ @pytest.mark.parametrize(
+ "schema_name, expected",
+ [("daily_report", True), ("custom_dimensions", False), ("cohort_metrics", False)],
+ )
+ def test_only_the_report_counts_as_resumable(self, schema_name, expected):
+ assert self.source.resume_covers_run(incremental_or_append=True, schema_name=schema_name) is expected