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 promptwatch import source (#111912)

Tom Owers47959fcf2a7f
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 2e4c6dde80e3..d7acfab1e779 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -622,6 +622,7 @@ the row lists both.
| productboard | HTTP | requests | ✅ |
| productive | HTTP | requests + `rest_source.RESTClient` | ✅ |
| profound | HTTP | requests (rest_source.RESTClient) | ✅ |
+| promptwatch | HTTP | requests | ✅ |
| propertyware | HTTP | requests + `rest_source.RESTClient` | ✅ |
| pulumi_cloud | HTTP | requests | ✅ |
| pylon | HTTP | requests | ✅ |
@@ -1331,7 +1332,6 @@ doesn't conflict with concurrent PRs.
- procore
- productiv
- prompting_company
-- promptwatch
- proofpoint_tap
- pubnub
- qonto
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/promptwatch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/promptwatch.py
index 33dc591c48bf..360d9213e36d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/promptwatch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/promptwatch.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class PromptWatchSourceConfig(config.Config):
- pass
+ api_key: str
+ start_date: str
+ project_id: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/canonical_descriptions.py
new file mode 100644
index 000000000000..6b80480e6860
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/canonical_descriptions.py
@@ -0,0 +1,67 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "prompts": {
+ "description": "Tracked prompts and their response counts and visibility scores.",
+ "docs_url": "https://promptwatch.com/docs/api-reference/prompts/list-prompts",
+ "columns": {
+ "id": "Unique prompt identifier.",
+ "prompt": "Text sent to the model.",
+ "llmMonitorId": "Monitor that owns this prompt.",
+ "isActive": "Whether the prompt is active.",
+ "createdAt": "Time when the prompt was created.",
+ "updatedAt": "Time when the prompt was last updated.",
+ },
+ },
+ "responses": {
+ "description": "Model answers to tracked prompts, with citations and brand mentions.",
+ "docs_url": "https://promptwatch.com/docs/api-reference/responses/list-responses",
+ "columns": {
+ "id": "Unique response identifier.",
+ "content": "Text of the model answer.",
+ "model": "Model that produced the answer.",
+ "createdAt": "Time when the response was created.",
+ "citations": "Sources cited in the answer.",
+ "brandMentions": "Brands found in the answer, with metrics for each brand.",
+ "visibilityScore": "Brand visibility score for this response.",
+ },
+ },
+ "monitors": {
+ "description": "Active project monitors. Visibility and response metrics use the API's default seven-day range.",
+ "docs_url": "https://promptwatch.com/docs/api-reference/monitors/list-monitors",
+ "columns": {
+ "id": "Unique monitor identifier.",
+ "name": "Monitor name.",
+ "models": "Models selected for this monitor.",
+ },
+ },
+ "tags": {
+ "description": "Project tags and the number of prompts that use each tag.",
+ "docs_url": "https://promptwatch.com/docs/api-reference/tags/list-tags",
+ "columns": {
+ "id": "Unique tag identifier.",
+ "name": "Tag name.",
+ "promptCount": "Number of prompts with this tag.",
+ },
+ },
+ "topics": {
+ "description": "Project topics and the number of prompts that use each topic.",
+ "docs_url": "https://promptwatch.com/docs/api-reference/topics/list-topics",
+ "columns": {
+ "id": "Unique topic identifier.",
+ "name": "Topic name.",
+ "promptCount": "Number of prompts with this topic.",
+ },
+ },
+ "personas": {
+ "description": "Audience profiles configured for the project.",
+ "docs_url": "https://promptwatch.com/docs/api-reference/personas/list-personas",
+ "columns": {
+ "id": "Unique persona identifier.",
+ "name": "Persona name.",
+ "description": "Description of the audience profile.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/promptwatch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/promptwatch.py
new file mode 100644
index 000000000000..9dd88d5c177d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/promptwatch.py
@@ -0,0 +1,175 @@
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any
+
+import structlog
+from requests import Response, Session
+from urllib3.util.retry import Retry
+
+from posthog.dataclasses import frozen
+from posthog.temporal.common.errors import NonReportableError
+
+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.auth import APIKeyAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.promptwatch import (
+ PromptWatchSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.promptwatch.settings import (
+ AUTH_ERROR,
+ BASE_URL,
+ MAX_PAGES,
+ PAGE_SIZE,
+ PAGINATED_ENDPOINTS,
+ PROJECT_ERROR,
+ QUOTA_ERROR,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+@frozen
+class PromptWatchResumeConfig:
+ page: int
+ from_date: str | None
+ until: str
+
+
+def make_session(api_key: str, *, enforce_row_limit: bool) -> Session:
+ session = make_tracked_session(retry=Retry(total=0), redact_values=(api_key,))
+ warned_page_cap = False
+
+ def check_response(response: Response, **kwargs: object) -> None:
+ nonlocal warned_page_cap
+ if response.status_code != 429 and not response.ok:
+ return
+ try:
+ body = response.json()
+ except ValueError:
+ return
+ if not isinstance(body, dict):
+ return
+ if response.status_code == 429 and "hourly API request limit" in str(body.get("message", "")):
+ raise NonReportableError("PROMPTWATCH_HOURLY_QUOTA")
+ if response.ok and PAGINATED_ENDPOINTS.intersection(body):
+ total_pages = body.get("totalPages")
+ if not isinstance(total_pages, int) or isinstance(total_pages, bool) or total_pages < 0:
+ raise ValueError("Promptwatch returned invalid pagination metadata.")
+ if total_pages > MAX_PAGES:
+ if enforce_row_limit:
+ raise NonReportableError("PROMPTWATCH_ROW_LIMIT")
+ if not warned_page_cap:
+ logger.warning("promptwatch.page_cap_reached", maximum_page=MAX_PAGES, total_pages=total_pages)
+ warned_page_cap = True
+
+ session.hooks["response"].append(check_response)
+ return session
+
+
+def validate_credentials(config: PromptWatchSourceConfig, api_version: str) -> tuple[bool, str | None]:
+ try:
+ date.fromisoformat(config.start_date)
+ except ValueError:
+ return False, "Enter the response start date in YYYY-MM-DD format."
+ with make_session(config.api_key, enforce_row_limit=True) as session:
+ try:
+ response = session.get(
+ f"{BASE_URL}/{api_version}/auth/validate",
+ auth=APIKeyAuth(config.api_key, name="X-API-Key"),
+ headers={"X-Project-Id": config.project_id} if config.project_id else {},
+ timeout=30,
+ allow_redirects=False,
+ )
+ except NonReportableError:
+ return False, QUOTA_ERROR
+ if response.status_code == 401:
+ return False, AUTH_ERROR
+ if response.status_code == 403:
+ return False, PROJECT_ERROR
+ response.raise_for_status()
+ body = response.json()
+ if not body.get("valid"):
+ return False, AUTH_ERROR
+ if not body.get("project"):
+ return False, "Enter a project ID when you use an organization API key."
+ return True, None
+
+
+def promptwatch_source(
+ config: PromptWatchSourceConfig,
+ inputs: SourceInputs,
+ manager: ResumableSourceManager[PromptWatchResumeConfig],
+ api_version: str,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint = inputs.schema_name
+ paginated = endpoint in PAGINATED_ENDPOINTS
+ resume = manager.load_state() if paginated and manager.can_resume() else None
+ if resume and resume.page == 0:
+ return
+ from_date: str | None = None
+ until = datetime.now(UTC).isoformat()
+ if endpoint == "responses":
+ start = datetime.combine(date.fromisoformat(config.start_date), datetime.min.time(), tzinfo=UTC)
+ if inputs.should_use_incremental_field and inputs.db_incremental_field_last_value is not None:
+ watermark = inputs.db_incremental_field_last_value
+ last = watermark if isinstance(watermark, datetime) else datetime.fromisoformat(str(watermark))
+ last = last.replace(tzinfo=UTC) if last.tzinfo is None else last
+ start = max(start, last - timedelta(seconds=1))
+ from_date = start.isoformat()
+ if resume:
+ from_date, until = resume.from_date, resume.until
+ params: dict[str, Any] = {}
+ if paginated:
+ params.update(size=PAGE_SIZE, sortBy="createdAt", sortOrder="asc")
+ if from_date is not None:
+ params.update({"from": from_date, "until": until})
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ manager.save_state(
+ PromptWatchResumeConfig(page=int(state["page"]) if state else 0, from_date=from_date, until=until)
+ )
+
+ with make_session(
+ config.api_key, enforce_row_limit=not (endpoint == "responses" and inputs.should_use_incremental_field)
+ ) as session:
+ endpoint_config: Endpoint = {
+ "path": endpoint,
+ "params": params,
+ "data_selector": "$" if endpoint == "monitors" else endpoint,
+ "data_selector_required": True,
+ "paginator": PageNumberPaginator(base_page=1, total_path="totalPages", maximum_page=MAX_PAGES)
+ if paginated
+ else "single_page",
+ }
+ resource: EndpointResource = {"name": endpoint, "endpoint": endpoint_config}
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": f"{BASE_URL}/{api_version}",
+ "auth": {"type": "api_key", "name": "X-API-Key", "api_key": config.api_key},
+ "headers": {"X-Project-Id": config.project_id} if config.project_id else {},
+ "session": session,
+ "allow_redirects": False,
+ "request_timeout": 30,
+ },
+ "resources": [resource],
+ }
+ yield from rest_api_resource(
+ rest_config,
+ inputs.team_id,
+ inputs.job_id,
+ db_incremental_field_last_value=None,
+ resume_hook=save_checkpoint if paginated else None,
+ initial_paginator_state={"page": resume.page} if resume else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/settings.py
new file mode 100644
index 000000000000..3c9b1587e3f1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/settings.py
@@ -0,0 +1,20 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+
+BASE_URL = "https://server.promptwatch.com/api"
+PAGE_SIZE = 50
+MAX_PAGES = 20
+ENDPOINTS = ("prompts", "responses", "monitors", "tags", "topics", "personas")
+PAGINATED_ENDPOINTS = {"prompts", "responses"}
+INCREMENTAL_FIELDS = {"responses": [incremental_field("createdAt")]}
+AUTH_ERROR = "Promptwatch rejected your API key. Check the key in Settings > API Keys."
+PROJECT_ERROR = "Promptwatch denied access. Check your project ID and API key permissions."
+QUOTA_ERROR = "Promptwatch reached its hourly API quota. Wait until the next UTC hour or upgrade your plan."
+ROW_LIMIT_ERROR = (
+ "Promptwatch exceeded the sync limit of 1,000 rows. Use a smaller project or a later response start date."
+)
+NON_RETRYABLE_ERRORS = {
+ "401 Client Error": AUTH_ERROR,
+ "403 Client Error": PROJECT_ERROR,
+ "PROMPTWATCH_HOURLY_QUOTA": QUOTA_ERROR,
+ "PROMPTWATCH_ROW_LIMIT": ROW_LIMIT_ERROR,
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/source.py
index 0b0fc53dcefa..1a6db16be0e5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/source.py
@@ -1,27 +1,141 @@
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,
+ 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.generated_configs.promptwatch import (
PromptWatchSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.promptwatch.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.promptwatch.promptwatch import (
+ PromptWatchResumeConfig,
+ promptwatch_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.promptwatch.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ NON_RETRYABLE_ERRORS,
+ PAGINATED_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PromptWatchSource(SimpleSource[PromptWatchSourceConfig]):
+class PromptWatchSource(ResumableSource[PromptWatchSourceConfig, PromptWatchResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://promptwatch.com/docs/v2/openapi.json"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PROMPTWATCH
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return dict(NON_RETRYABLE_ERRORS)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: PromptWatchSourceConfig,
+ 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: PromptWatchSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config, self.resolve_api_version(api_version))
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PromptWatchResumeConfig]:
+ return ResumableSourceManager(inputs, PromptWatchResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PromptWatchSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PromptWatchResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ schema_for_resource(CANONICAL_DESCRIPTIONS, inputs.schema_name)
+ return SourceResponse(
+ name=inputs.schema_name,
+ items=lambda: promptwatch_source(
+ config, inputs, resumable_source_manager, self.resolve_api_version(inputs.api_version)
+ ),
+ primary_keys=["id"],
+ sort_mode="asc" if inputs.schema_name in PAGINATED_ENDPOINTS else None,
+ supports_resume=inputs.schema_name in PAGINATED_ENDPOINTS,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.PROMPTWATCH,
- category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="PromptWatch",
+ category=DataWarehouseSourceCategory.ANALYTICS,
+ label="Promptwatch",
iconPath="/static/services/promptwatch.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption=(
+ "Create a read-only API key in Promptwatch under Settings > API Keys. "
+ "Requires the Explore plan or higher. Syncs use your account's API units (hourly request quota). "
+ "Each paginated table allows up to 1,000 rows per sync. Responses start from your chosen date."
+ ),
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="project_id",
+ secret=False,
+ label="Project ID (required for organization API keys)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="00000000-0000-0000-0000-000000000000",
+ ),
+ SourceFieldInputConfig(
+ name="start_date",
+ secret=False,
+ label="Response start date",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="YYYY-MM-DD",
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/tests/test_promptwatch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/tests/test_promptwatch.py
new file mode 100644
index 000000000000..134bc944a251
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/tests/test_promptwatch.py
@@ -0,0 +1,300 @@
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests_mock
+from requests import HTTPError
+
+from posthog.temporal.common.errors import NonReportableError
+
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.promptwatch import (
+ PromptWatchSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.promptwatch.promptwatch import (
+ PromptWatchResumeConfig,
+ promptwatch_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.promptwatch.settings import (
+ AUTH_ERROR,
+ BASE_URL,
+ MAX_PAGES,
+ NON_RETRYABLE_ERRORS,
+ PROJECT_ERROR,
+ QUOTA_ERROR,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.promptwatch.source import PromptWatchSource
+
+
+def config() -> PromptWatchSourceConfig:
+ return PromptWatchSourceConfig(api_key="fake-api-key", project_id="test-project", start_date="2026-01-01")
+
+
+def inputs() -> SourceInputs:
+ return SourceInputs(
+ schema_name="responses",
+ schema_id="schema",
+ source_id="source",
+ team_id=1,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field="createdAt",
+ incremental_field_type=None,
+ job_id="job",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+def manager() -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ return manager
+
+
+ "incremental,watermark,expected",
+ [
+ (False, "2026-02-03T12:00:00+00:00", "2026-01-01T00:00:00+00:00"),
+ (True, None, "2026-01-01T00:00:00+00:00"),
+ (True, "2026-02-03T12:00:00+00:00", "2026-02-03T11:59:59+00:00"),
+ (True, datetime(2026, 2, 3, 12, tzinfo=UTC), "2026-02-03T11:59:59+00:00"),
+ (True, datetime(2026, 2, 3, 12), "2026-02-03T11:59:59+00:00"),
+ ],
+)
+def test_response_requests(
+ config: PromptWatchSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ incremental: bool,
+ watermark: str | datetime | None,
+ expected: str,
+) -> None:
+ inputs.should_use_incremental_field = incremental
+ inputs.db_incremental_field_last_value = watermark
+ with requests_mock.Mocker() as mock:
+ mock.get(
+ f"{BASE_URL}/v2/responses",
+ [
+ {"json": {"responses": [{"id": "first"}], "totalPages": 2}},
+ {"json": {"responses": [{"id": "last"}], "totalPages": 2}},
+ ],
+ )
+ response = PromptWatchSource().source_for_pipeline(config, manager, inputs)
+ items = cast(Iterable[list[dict[str, str]]], response.items())
+ assert list(items) == [[{"id": "first"}], [{"id": "last"}]]
+ assert response.sort_mode == "asc"
+ assert len(mock.request_history) == 2
+ for index, request in enumerate(mock.request_history, start=1):
+ assert request.headers["X-API-Key"] == "fake-api-key"
+ assert request.headers["X-Project-Id"] == "test-project"
+ assert request.qs["page"] == [str(index)]
+ assert request.qs["size"] == ["50"]
+ assert request.qs["sortby"] == ["createdat"]
+ assert request.qs["sortorder"] == ["asc"]
+ assert request.qs["from"] == [expected.lower()]
+ assert request.qs["until"] == mock.request_history[0].qs["until"]
+ assert [call.args[0].page for call in manager.save_state.call_args_list] == [2, 0]
+
+
+ "endpoint,body",
+ [
+ ("prompts", {"prompts": [{"id": "prompt"}], "totalPages": 1}),
+ ("monitors", [{"id": "monitor"}]),
+ ("tags", {"tags": [{"id": "tag"}]}),
+ ("topics", {"topics": [{"id": "topic"}]}),
+ ("personas", {"personas": [{"id": "persona"}]}),
+ ],
+)
+def test_configuration_tables(
+ config: PromptWatchSourceConfig, inputs: SourceInputs, manager: MagicMock, endpoint: str, body: object
+) -> None:
+ inputs.schema_name = endpoint
+ config.project_id = None
+ with requests_mock.Mocker() as mock:
+ mock.get(f"{BASE_URL}/v2/{endpoint}", json=body)
+ pages = list(promptwatch_source(config, inputs, manager, "v2"))
+ assert len(pages) == 1 and len(pages[0]) == 1
+ assert len(mock.request_history) == 1
+ assert "from" not in mock.last_request.qs
+ assert "until" not in mock.last_request.qs
+ assert "X-Project-Id" not in mock.last_request.headers
+
+
[email protected]("page", [0, 2])
+def test_resume(config: PromptWatchSourceConfig, inputs: SourceInputs, manager: MagicMock, page: int) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = PromptWatchResumeConfig(
+ page=page, from_date="2026-01-02T00:00:00+00:00", until="2026-01-03T00:00:00+00:00"
+ )
+ inputs.db_incremental_field_last_value = "2026-01-02T12:00:00Z"
+ with requests_mock.Mocker() as mock:
+ mock.get(f"{BASE_URL}/v2/responses", json={"responses": [{"id": "last"}], "totalPages": 2})
+ pages = list(promptwatch_source(config, inputs, manager, "v2"))
+ if page == 0:
+ assert pages == []
+ assert mock.call_count == 0
+ else:
+ assert pages == [[{"id": "last"}]]
+ assert mock.last_request.qs["page"] == ["2"]
+ assert mock.last_request.qs["from"] == ["2026-01-02t00:00:00+00:00"]
+ assert mock.last_request.qs["until"] == ["2026-01-03t00:00:00+00:00"]
+
+
+ "rows,total_pages,incremental,error,expected_pages",
+ [
+ ([], 0, True, None, 1),
+ ([{"id": "record"}], MAX_PAGES + 1, False, "PROMPTWATCH_ROW_LIMIT", 1),
+ ([{"id": "record"}], MAX_PAGES + 1, True, None, MAX_PAGES),
+ ],
+)
+def test_empty_and_oversized_tables(
+ config: PromptWatchSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ rows: list[dict[str, str]],
+ total_pages: int,
+ incremental: bool,
+ error: str | None,
+ expected_pages: int,
+) -> None:
+ inputs.should_use_incremental_field = incremental
+ with (
+ requests_mock.Mocker() as mock,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.promptwatch.promptwatch.logger"
+ ) as logger,
+ ):
+ mock.get(f"{BASE_URL}/v2/responses", json={"responses": rows, "totalPages": total_pages})
+ if error:
+ with pytest.raises(NonReportableError, match=error):
+ list(promptwatch_source(config, inputs, manager, "v2"))
+ assert error in NON_RETRYABLE_ERRORS
+ else:
+ assert list(promptwatch_source(config, inputs, manager, "v2")) == ([rows] * expected_pages if rows else [])
+ assert [request.qs["page"] for request in mock.request_history] == [
+ [str(page)] for page in range(1, expected_pages + 1)
+ ]
+ if total_pages > MAX_PAGES and incremental:
+ logger.warning.assert_called_once_with(
+ "promptwatch.page_cap_reached", maximum_page=MAX_PAGES, total_pages=total_pages
+ )
+ else:
+ logger.warning.assert_not_called()
+
+
+ "status,body,message",
+ [
+ (200, {"valid": True, "project": {"id": "test-project"}}, None),
+ (200, {"valid": False}, AUTH_ERROR),
+ (200, {"valid": True, "project": None}, "Enter a project ID when you use an organization API key."),
+ (401, {"message": "Invalid API key"}, AUTH_ERROR),
+ (403, {"message": "Forbidden"}, PROJECT_ERROR),
+ (
+ 429,
+ {
+ "message": "You've hit your hourly API request limit of 500 requests. Try again in 30 minutes, or upgrade your plan to increase your limit."
+ },
+ QUOTA_ERROR,
+ ),
+ ],
+)
+def test_credential_validation(
+ config: PromptWatchSourceConfig, status: int, body: dict[str, object], message: str | None
+) -> None:
+ with requests_mock.Mocker() as mock:
+ mock.get(f"{BASE_URL}/v2/auth/validate", status_code=status, json=body)
+ assert validate_credentials(config, "v2") == (message is None, message)
+ assert mock.call_count == 1
+ assert mock.last_request.headers["X-API-Key"] == "fake-api-key"
+ assert mock.last_request.headers["X-Project-Id"] == "test-project"
+
+
+def test_invalid_date(config: PromptWatchSourceConfig) -> None:
+ config.start_date = "not-a-date"
+ with requests_mock.Mocker() as mock:
+ assert validate_credentials(config, "v2") == (False, "Enter the response start date in YYYY-MM-DD format.")
+ assert mock.call_count == 0
+
+
+ "status,body,retry",
+ [
+ (401, {"message": "Invalid API key"}, False),
+ (403, {"message": "Forbidden"}, False),
+ (429, {"message": "You've hit your hourly API request limit of 500 requests."}, False),
+ (429, {"message": "You're sending requests too quickly."}, True),
+ (500, {"error": "Internal Server Error"}, True),
+ ],
+)
+def test_error_classification(
+ config: PromptWatchSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ status: int,
+ body: dict[str, str],
+ retry: bool,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(RESTClient._send_request.retry, "wait", lambda _: 0) # type: ignore[attr-defined]
+ with requests_mock.Mocker() as mock:
+ mock.get(
+ f"{BASE_URL}/v2/responses",
+ [
+ {"status_code": status, "json": body},
+ {"json": {"responses": [], "totalPages": 0}},
+ ],
+ )
+ if retry:
+ list(promptwatch_source(config, inputs, manager, "v2"))
+ assert mock.call_count == 2
+ else:
+ with pytest.raises((HTTPError, NonReportableError)) as exc:
+ list(promptwatch_source(config, inputs, manager, "v2"))
+ assert any(pattern in str(exc.value) for pattern in PromptWatchSource().get_non_retryable_errors())
+ assert mock.call_count == 1
+
+
[email protected]("total_pages", [None, "2", -1, True])
+def test_invalid_pagination(
+ config: PromptWatchSourceConfig, inputs: SourceInputs, manager: MagicMock, total_pages: object
+) -> None:
+ with requests_mock.Mocker() as mock:
+ mock.get(f"{BASE_URL}/v2/responses", json={"responses": [{"id": "record"}], "totalPages": total_pages})
+ with pytest.raises(ValueError, match="invalid pagination metadata"):
+ list(promptwatch_source(config, inputs, manager, "v2"))
+ assert mock.call_count == 1
+
+
[email protected]("status", [200, 429])
+def test_malformed_response_retries(
+ config: PromptWatchSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ status: int,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(RESTClient._send_request.retry, "wait", lambda _: 0) # type: ignore[attr-defined]
+ with requests_mock.Mocker() as mock:
+ mock.get(
+ f"{BASE_URL}/v2/responses",
+ [
+ {"status_code": status, "text": '{"responses":'},
+ {"json": {"responses": [], "totalPages": 0}},
+ ],
+ )
+ list(promptwatch_source(config, inputs, manager, "v2"))
+ assert mock.call_count == 2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/tests/test_promptwatch_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/tests/test_promptwatch_source.py
new file mode 100644
index 000000000000..e98960444ce4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/promptwatch/tests/test_promptwatch_source.py
@@ -0,0 +1,17 @@
+import pytest
+from unittest.mock import MagicMock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.promptwatch import (
+ PromptWatchSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.promptwatch.source import PromptWatchSource
+
+
+def test_unknown_table() -> None:
+ inputs = MagicMock(spec=SourceInputs)
+ inputs.schema_name = "unknown"
+ config = PromptWatchSourceConfig(api_key="fake-key", start_date="2026-01-01")
+ with pytest.raises(UnknownResourceError, match="unknown"):
+ PromptWatchSource().source_for_pipeline(config, MagicMock(), inputs)