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 scrunch import source (#113248)

Tom Owers69414404de6b
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 1cb9045a9254..ad5b93955607 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -712,6 +712,7 @@ the row lists both.
| scale_ai | HTTP | requests | ✅ |
| scaleway | HTTP | requests | ✅ |
| scalr | HTTP | requests | ✅ |
+| scrunch | HTTP | requests | ✅ |
| secoda | HTTP | requests | ✅ |
| secureframe | HTTP | requests | ✅ |
| segment | HTTP | requests | ✅ |
@@ -1399,7 +1400,6 @@ doesn't conflict with concurrent PRs.
- scale_ai
- scaleway
- schematic
-- scrunch
- search_ads_360
- sec_edgar
- secureframe
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/scrunch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/scrunch.py
index 9bca4cb6ec00..793e5f2c8e63 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/scrunch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/scrunch.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class ScrunchSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/canonical_descriptions.py
new file mode 100644
index 000000000000..58f4027afda6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/canonical_descriptions.py
@@ -0,0 +1,81 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "brands": {
+ "description": "Brands available to the Scrunch API key.",
+ "docs_url": "https://developers.scrunch.com/api-reference/list-brands",
+ "columns": {
+ "id": "The unique identifier of the brand.",
+ "name": "The name of the brand.",
+ "website": "The website of the brand.",
+ },
+ },
+ "prompts": {
+ "description": "Tracked prompts, including active, paused, and archived prompts.",
+ "docs_url": "https://developers.scrunch.com/api-reference/list-prompts",
+ "columns": {
+ "id": "The unique identifier of the prompt.",
+ "brand_id": "The identifier of the brand that owns the prompt.",
+ "text": "The prompt text that Scrunch tracks.",
+ "stage": "The name of the customer journey stage configured for the brand.",
+ "persona_id": "The identifier of the associated persona, if present.",
+ "platforms": "The AI platforms on which Scrunch tracks the prompt.",
+ "tags": "Custom tags assigned to the prompt.",
+ "topics": "Topics assigned to the prompt or detected automatically.",
+ "status": "The prompt status: active, paused, or archived.",
+ "created_at": "The time when the prompt was created.",
+ },
+ },
+ "competitors": {
+ "description": "Competitors configured for each accessible brand.",
+ "docs_url": "https://developers.scrunch.com/api-reference/list-competitors",
+ "columns": {
+ "id": "The identifier of the competitor.",
+ "brand_id": "The identifier of the brand that tracks the competitor.",
+ "name": "The name of the competitor.",
+ "alternative_names": "Other names used to identify the competitor.",
+ "websites": "Websites associated with the competitor.",
+ "case_sensitive": "Whether name matching uses case sensitivity.",
+ },
+ },
+ "personas": {
+ "description": "Personas configured for each accessible brand.",
+ "docs_url": "https://developers.scrunch.com/api-reference/list-personas",
+ "columns": {
+ "id": "The identifier of the persona.",
+ "brand_id": "The identifier of the brand that owns the persona.",
+ "name": "The name of the persona.",
+ "description": "The description of the persona.",
+ },
+ },
+ "responses": {
+ "description": "AI answers to tracked prompts, with brand evaluations, citations, and competitor evaluations.",
+ "docs_url": "https://developers.scrunch.com/api-reference/responses/overview",
+ "columns": {
+ "id": "The globally unique identifier of the response.",
+ "brand_id": "The identifier of the brand whose responses were requested.",
+ "created_at": "The UTC time when Scrunch collected the response.",
+ "prompt_id": "The identifier of the prompt that generated the response.",
+ "prompt": "The prompt text sent to the AI platform.",
+ "platform": "The AI platform that generated the response.",
+ "persona_id": "The identifier of the persona used for the response, if present.",
+ "persona_name": "The display name of the persona, if present.",
+ "country": "The country code for the geographic context of the response.",
+ "stage": "The name of the customer journey stage configured for the brand.",
+ "branded": "Whether the prompt explicitly mentions the brand.",
+ "brand_present": "Whether the AI answer mentions the brand.",
+ "brand_sentiment": "The sentiment of the brand mention. A value of none means a mention without discernible sentiment.",
+ "brand_position": "The third of the answer containing the brand mention: top, middle, or bottom.",
+ "response_text": "The complete text of the AI answer.",
+ "tags": "Custom tags associated with the prompt.",
+ "key_topics": "Topics associated with the prompt.",
+ "citations": "Cited URLs with their source classifications.",
+ "competitors": "Evaluations of competitors mentioned in the answer.",
+ "competitors_present": "Names of competitors mentioned in the answer.",
+ "query_fanout": "Search queries generated internally by the AI platform, if available.",
+ "shopping_results": "Product listings included in the response, if present.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/scrunch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/scrunch.py
new file mode 100644
index 000000000000..5204afd5f21f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/scrunch.py
@@ -0,0 +1,149 @@
+from datetime import UTC, datetime
+from typing import Any
+
+from requests import HTTPError
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resources,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ rename_parent_fields,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+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 schema_for_resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.scrunch.settings import (
+ BASE_URL,
+ ENDPOINTS,
+ NON_RETRYABLE_ERRORS,
+ PAGE_SIZE,
+ PRIMARY_KEYS,
+)
+
+
+@frozen
+class ScrunchResumeConfig:
+ paginator_state: dict[str, Any] | None
+ start_date: str | None
+ end_date: str | None
+ complete: bool = False
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ client = RESTClient(
+ base_url=BASE_URL,
+ auth=BearerTokenAuth(api_key),
+ request_timeout=60,
+ allowed_hosts=[],
+ allow_redirects=False,
+ )
+ try:
+ next(
+ client.paginate(
+ "brands",
+ params={"limit": 1},
+ paginator=SinglePagePaginator(),
+ data_selector="items",
+ data_selector_required=True,
+ )
+ )
+ except HTTPError as error:
+ for pattern, message in NON_RETRYABLE_ERRORS.items():
+ if pattern in str(error):
+ return False, message
+ raise
+ return True, None
+
+
+def scrunch_source(
+ api_key: str,
+ inputs: SourceInputs,
+ manager: ResumableSourceManager[ScrunchResumeConfig],
+) -> SourceResponse:
+ path = schema_for_resource(ENDPOINTS, inputs.schema_name)
+ is_responses = inputs.schema_name == "responses"
+ resume = manager.load_state() if manager.can_resume() else None
+ start_date = None
+ # Exclude the open UTC day so new responses cannot move offsets during a sync.
+ end_date = datetime.now(UTC).date().isoformat() if is_responses else None
+ if resume is not None:
+ start_date, end_date = resume.start_date, resume.end_date
+ elif is_responses and inputs.should_use_incremental_field and inputs.db_incremental_field_last_value is not None:
+ watermark = parse_datetime_value(inputs.db_incremental_field_last_value)
+ if watermark is None:
+ raise ValueError("Invalid Scrunch response watermark. Reset this table's sync.")
+ # Date filters include the whole watermark day; merging prevents duplicate rows.
+ start_date = watermark.date().isoformat()
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ manager.save_state(
+ ScrunchResumeConfig(
+ paginator_state=state,
+ start_date=start_date,
+ end_date=end_date,
+ complete=state is None,
+ )
+ )
+
+ parent: EndpointResource = {"name": "brands", "endpoint": {"path": ENDPOINTS["brands"]}}
+ resources: list[str | EndpointResource] = [parent]
+ if inputs.schema_name != "brands":
+ params: dict[str, Any] = {"brand_id": {"type": "resolve", "resource": "brands", "field": "id"}}
+ if inputs.schema_name == "prompts":
+ params["status"] = "all"
+ if is_responses:
+ params["end_date"] = end_date
+ if start_date is not None:
+ params["start_date"] = start_date
+ resources.append(
+ {
+ "name": inputs.schema_name,
+ "include_from_parent": ["id"],
+ "endpoint": {"path": path, "params": params},
+ "data_map": rename_parent_fields("brands", {"id": "brand_id"}),
+ }
+ )
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": BASE_URL,
+ "auth": {"type": "bearer", "token": api_key},
+ "paginator": {"type": "offset", "limit": PAGE_SIZE, "total_path": "total"},
+ "request_timeout": 60,
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ },
+ "resource_defaults": {"endpoint": {"data_selector": "items", "data_selector_required": True}},
+ "resources": resources,
+ }
+ resource = next(
+ resource
+ for resource in rest_api_resources(
+ config,
+ inputs.team_id,
+ inputs.job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=resume.paginator_state if resume else None,
+ )
+ if resource.name == inputs.schema_name
+ )
+ return SourceResponse(
+ name=inputs.schema_name,
+ items=(lambda: []) if resume and resume.complete else (lambda: resource),
+ primary_keys=PRIMARY_KEYS[inputs.schema_name],
+ sort_mode="desc" if is_responses else None,
+ partition_keys=["created_at"] if is_responses else None,
+ partition_mode="datetime" if is_responses else None,
+ partition_format="month" if is_responses else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/settings.py
new file mode 100644
index 000000000000..0e714c172e6a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/settings.py
@@ -0,0 +1,26 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+
+API_VERSION = "v1"
+BASE_URL = f"https://api.scrunchai.com/{API_VERSION}"
+PAGE_SIZE = 100
+
+ENDPOINTS = {
+ "brands": "brands",
+ "prompts": "{brand_id}/prompts",
+ "competitors": "brands/{brand_id}/competitors",
+ "personas": "brands/{brand_id}/personas",
+ "responses": "{brand_id}/responses",
+}
+INCREMENTAL_FIELDS = {"responses": [incremental_field("created_at")]}
+PRIMARY_KEYS = {name: ["id"] if name == "brands" else ["brand_id", "id"] for name in ENDPOINTS}
+
+AUTH_ERROR = "Scrunch rejected the API key. Check the key in your organization's API Keys menu."
+PERMISSION_ERROR = (
+ "Scrunch denied access. Check the key's brand access and Query scope. "
+ "API access requires an Agency or Enterprise plan, or an override from Scrunch."
+)
+NON_RETRYABLE_ERRORS: dict[str, str | None] = {
+ "401 Client Error": AUTH_ERROR,
+ "403 Client Error": PERMISSION_ERROR,
+ "402 Client Error": PERMISSION_ERROR,
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/source.py
index 80fcc3c63578..612cda90d3ea 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/source.py
@@ -1,28 +1,118 @@
from typing import 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.scrunch import (
ScrunchSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.scrunch.scrunch import (
+ ScrunchResumeConfig,
+ scrunch_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.scrunch.settings import (
+ API_VERSION,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ NON_RETRYABLE_ERRORS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ScrunchSource(SimpleSource[ScrunchSourceConfig]):
+class ScrunchSource(ResumableSource[ScrunchSourceConfig, ScrunchResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = (API_VERSION,)
+ default_version = API_VERSION
+ api_docs_url = "https://developers.scrunch.com/api-reference/openapi.json"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SCRUNCH
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return NON_RETRYABLE_ERRORS
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.scrunch.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: ScrunchSourceConfig,
+ 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, merge_only={"responses"})
+
+ def validate_credentials(
+ self,
+ config: ScrunchSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ScrunchResumeConfig]:
+ return ResumableSourceManager(inputs, ScrunchResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ScrunchSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ScrunchResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return scrunch_source(config.api_key, inputs, resumable_source_manager)
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.SCRUNCH,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Scrunch",
- keywords=["ai search visibility", "aeo", "geo"],
+ keywords=["scrunch ai", "ai search visibility", "aeo", "geo"],
iconPath="/static/services/scrunch.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption=(
+ "An organization admin can create an API key under the organization menu > API Keys in Scrunch. "
+ "Select Query scope and the brands to import. "
+ "API access requires an Agency or Enterprise plan, or an override from Scrunch. "
+ "Responses become available after their UTC day ends."
+ ),
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ )
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/tests/test_scrunch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/tests/test_scrunch.py
new file mode 100644
index 000000000000..e68c1a7798bd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scrunch/tests/test_scrunch.py
@@ -0,0 +1,314 @@
+import json
+from collections.abc import Iterable, Iterator
+from datetime import UTC, datetime
+from typing import Any, cast
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import HTTPError, Response, Session
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import activate_safe_point
+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.scrunch import (
+ ScrunchSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.scrunch.scrunch import (
+ ScrunchResumeConfig,
+ scrunch_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.scrunch.settings import (
+ AUTH_ERROR,
+ PERMISSION_ERROR,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.scrunch.source import ScrunchSource
+
+
+def inputs() -> SourceInputs:
+ return SourceInputs(
+ schema_name="brands",
+ schema_id="test-schema",
+ source_id="test-source",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="test-job",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+def manager() -> MagicMock:
+ result = MagicMock()
+ result.can_resume.return_value = False
+ return result
+
+
+def transport() -> Iterator[MagicMock]:
+ session = Session()
+ with (
+ patch.object(session, "send") as send,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session",
+ return_value=session,
+ ) as tracked,
+ patch("products.warehouse_sources.backend.temporal.data_imports.sources.scrunch.scrunch.PAGE_SIZE", 2),
+ activate_safe_point(lambda: None, covers_framework_checkpoints=True),
+ ):
+ yield send
+ assert tracked.call_args.kwargs["redact_values"] == ("test-key",)
+
+
+def page(rows: list[dict[str, Any]], total: int, status: int = 200) -> Response:
+ response = Response()
+ response.status_code = status
+ response.url = "https://api.scrunchai.com/v1/brands"
+ response._content = json.dumps({"items": rows, "total": total}).encode()
+ response.headers["Content-Type"] = "application/json"
+ return response
+
+
+def params(transport: MagicMock, index: int) -> dict[str, list[str]]:
+ return parse_qs(urlsplit(transport.call_args_list[index].args[0].url).query)
+
+
+def sync_batches(response: SourceResponse) -> Iterable[Any]:
+ return cast(Iterable[Any], response.items())
+
+
[email protected]("terminal", [[], [{"id": 3}], [{"id": 3}, {"id": 4}]])
+def test_brand_pagination(
+ terminal: list[dict[str, Any]], inputs: SourceInputs, manager: MagicMock, transport: MagicMock
+) -> None:
+ total = 2 + len(terminal) if terminal else 5
+ transport.side_effect = [page([{"id": 1}, {"id": 2}], total), page(terminal, total)]
+ result = scrunch_source("test-key", inputs, manager)
+ iterator = iter(sync_batches(result))
+ assert next(iterator) == [{"id": 1}, {"id": 2}]
+ assert manager.save_state.call_args.args[0].paginator_state == {"offset": 2}
+ remaining = list(iterator)
+ assert [row for batch in remaining for row in batch] == terminal
+ assert manager.save_state.call_args.args[0].complete is True
+ assert transport.call_count == 2
+ assert [params(transport, index) for index in range(2)] == [
+ {"offset": ["0"], "limit": ["2"]},
+ {"offset": ["2"], "limit": ["2"]},
+ ]
+ for call in transport.call_args_list:
+ assert call.args[0].headers["Authorization"] == "Bearer test-key"
+ assert urlsplit(call.args[0].url).path == "/v1/brands"
+
+
+ "table,path",
+ [
+ ("prompts", "/v1/11/prompts"),
+ ("competitors", "/v1/brands/11/competitors"),
+ ("personas", "/v1/brands/11/personas"),
+ ("responses", "/v1/11/responses"),
+ ],
+)
+def test_children_keep_brand_identity_and_reset_offsets(
+ table: str, path: str, inputs: SourceInputs, manager: MagicMock, transport: MagicMock
+) -> None:
+ inputs.schema_name = table
+ transport.side_effect = [
+ page([{"id": 11}, {"id": 22}], 2),
+ page([{"id": 1}, {"id": 2}], 3),
+ page([{"id": 3}], 3),
+ page([{"id": 1}], 1),
+ ]
+ result = scrunch_source("test-key", inputs, manager)
+ rows = [row for batch in sync_batches(result) for row in batch]
+ assert rows == [
+ {"id": 1, "brand_id": 11},
+ {"id": 2, "brand_id": 11},
+ {"id": 3, "brand_id": 11},
+ {"id": 1, "brand_id": 22},
+ ]
+ assert result.primary_keys == ["brand_id", "id"]
+ assert [params(transport, index)["offset"] for index in range(4)] == [["0"], ["0"], ["2"], ["0"]]
+ assert urlsplit(transport.call_args_list[1].args[0].url).path == path
+ assert urlsplit(transport.call_args_list[3].args[0].url).path == path.replace("11", "22")
+ for index in range(1, 4):
+ assert "brand_id" not in params(transport, index)
+ if table == "prompts":
+ assert params(transport, index)["status"] == ["all"]
+ if table != "responses":
+ assert "start_date" not in params(transport, index)
+ assert "end_date" not in params(transport, index)
+
+
+def test_child_requests_reject_off_host_brand_ids(
+ inputs: SourceInputs, manager: MagicMock, transport: MagicMock
+) -> None:
+ inputs.schema_name = "prompts"
+ transport.return_value = page([{"id": "https://attacker.example/collect"}], 1)
+
+ with pytest.raises(ValueError, match="disallowed host"):
+ list(sync_batches(scrunch_source("test-key", inputs, manager)))
+
+ assert transport.call_count == 1
+
+
+ "incremental,watermark,expected_start",
+ [
+ (False, "2026-08-01T10:00:00Z", None),
+ (True, None, None),
+ (True, "2026-08-01T10:00:00Z", "2026-08-01"),
+ (True, datetime(2026, 8, 1, 10, tzinfo=UTC), "2026-08-01"),
+ (True, "2026-08-01T23:30:00-05:00", "2026-08-02"),
+ ],
+)
+def test_response_date_filters(
+ incremental: bool,
+ watermark: str | datetime | None,
+ expected_start: str | None,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ transport: MagicMock,
+) -> None:
+ inputs.schema_name = "responses"
+ inputs.should_use_incremental_field = incremental
+ inputs.db_incremental_field_last_value = watermark
+ transport.side_effect = [
+ page([{"id": 11}], 1),
+ page([{"id": 1}, {"id": 2}], 3),
+ page([{"id": 3}], 3),
+ ]
+ today = datetime.now(UTC).date().isoformat()
+ result = scrunch_source("test-key", inputs, manager)
+ list(sync_batches(result))
+ assert result.sort_mode == "desc"
+ assert result.partition_keys == ["created_at"]
+ for index in (1, 2):
+ query = params(transport, index)
+ assert query["end_date"] == [today]
+ assert query.get("start_date") == ([expected_start] if expected_start else None)
+ assert "start_date" not in params(transport, 0)
+
+
[email protected]("terminal", [False, True])
+def test_child_resume_keeps_window_and_skips_completed_brands(
+ terminal: bool, inputs: SourceInputs, manager: MagicMock, transport: MagicMock
+) -> None:
+ inputs.schema_name = "responses"
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ScrunchResumeConfig(
+ paginator_state={
+ "completed": ["11/responses"],
+ "current": None if terminal else "22/responses",
+ "child_state": None if terminal else {"offset": 2},
+ },
+ start_date="2026-08-01",
+ end_date="2026-08-03",
+ )
+ transport.side_effect = [page([{"id": 11}, {"id": 22}], 2), page([{"id": 9}], 3 if not terminal else 1)]
+ result = scrunch_source("test-key", inputs, manager)
+ iterator = iter(sync_batches(result))
+ assert next(iterator) == [{"id": 9, "brand_id": 22}]
+ assert manager.save_state.call_args.args[0].paginator_state == {
+ "completed": ["11/responses", "22/responses"],
+ "current": None,
+ "child_state": None,
+ }
+ assert list(iterator) == []
+ assert transport.call_count == 2
+ assert params(transport, 1) == {
+ "offset": ["0" if terminal else "2"],
+ "limit": ["2"],
+ "start_date": ["2026-08-01"],
+ "end_date": ["2026-08-03"],
+ }
+ assert urlsplit(transport.call_args_list[1].args[0].url).path == "/v1/22/responses"
+
+
[email protected]("complete", [False, True])
+def test_brand_resume(inputs: SourceInputs, manager: MagicMock, transport: MagicMock, complete: bool) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ScrunchResumeConfig(
+ paginator_state=None if complete else {"offset": 2},
+ start_date=None,
+ end_date=None,
+ complete=complete,
+ )
+ transport.return_value = page([{"id": 3}], 3)
+ rows = [row for batch in sync_batches(scrunch_source("test-key", inputs, manager)) for row in batch]
+ assert rows == ([] if complete else [{"id": 3}])
+ assert transport.call_count == (0 if complete else 1)
+ if not complete:
+ assert params(transport, 0)["offset"] == ["2"]
+
+
[email protected]("has_brands", [False, True])
+def test_empty_children_do_not_stop_parent_pagination(
+ has_brands: bool, inputs: SourceInputs, manager: MagicMock, transport: MagicMock
+) -> None:
+ inputs.schema_name = "personas"
+ transport.side_effect = (
+ [
+ page([{"id": 11}, {"id": 22}], 3),
+ page([], 0),
+ page([], 0),
+ page([{"id": 33}], 3),
+ page([{"id": 1}], 1),
+ ]
+ if has_brands
+ else [page([], 0)]
+ )
+ safe_point = MagicMock()
+ with activate_safe_point(safe_point, covers_framework_checkpoints=True):
+ result = scrunch_source("test-key", inputs, manager)
+ assert [row for batch in sync_batches(result) for row in batch] == (
+ [{"id": 1, "brand_id": 33}] if has_brands else []
+ )
+ assert transport.call_count == (5 if has_brands else 1)
+ if has_brands:
+ assert params(transport, 3)["offset"] == ["2"]
+ assert manager.save_state.call_args.args[0].paginator_state["completed"] == [
+ "brands/11/personas",
+ "brands/22/personas",
+ "brands/33/personas",
+ ]
+ safe_point.assert_called()
+
+
+ "status,message", [(200, None), (401, AUTH_ERROR), (403, PERMISSION_ERROR), (402, PERMISSION_ERROR)]
+)
+def test_credentials_and_error_mapping(status: int, message: str | None, transport: MagicMock) -> None:
+ transport.return_value = page([], 0, status=status)
+ source = ScrunchSource()
+ assert source.validate_credentials(ScrunchSourceConfig(api_key="test-key"), 1) == (status == 200, message)
+ assert transport.call_count == 1
+ assert params(transport, 0) == {"limit": ["1"]}
+ assert transport.call_args.args[0].headers["Authorization"] == "Bearer test-key"
+ if status != 200:
+ with pytest.raises(HTTPError) as error:
+ transport.return_value.raise_for_status()
+ assert any(
+ pattern in str(error.value) and value == message
+ for pattern, value in source.get_non_retryable_errors().items()
+ )
+
+
+def test_unexpected_validation_failure_propagates(transport: MagicMock) -> None:
+ transport.return_value = page([], 0, status=404)
+ with pytest.raises(HTTPError):
+ ScrunchSource().validate_credentials(ScrunchSourceConfig(api_key="test-key"), 1)
+
+
+def test_invalid_watermark_fails_before_requests(inputs: SourceInputs, manager: MagicMock) -> None:
+ inputs.schema_name = "responses"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "not-a-date"
+ with pytest.raises(ValueError, match="watermark"):
+ scrunch_source("test-key", inputs, manager)