: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement helicone import source (#70714)
Tom Owers5e1164c48a43
diff --git a/frontend/public/services/helicone.svg b/frontend/public/services/helicone.svgnew file mode 100644index 000000000000..a3a0dc784c5e--- /dev/null+++ b/frontend/public/services/helicone.svg@@ -0,0 +1,8 @@+<svg width="39" height="38" viewBox="0 0 39 38" fill="none" xmlns="http://www.w3.org/2000/svg">+<mask id="mask0_1875_4928" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="39" height="38">+<path d="M5.25781 10.7161L19.4739 4.49658C19.6055 4.43899 19.7552 4.43899 19.8868 4.49658L34.103 10.7161M5.25781 10.7161V23.7222M5.25781 10.7161L16.4427 15.6095M34.103 10.7161L30.2398 12.4063M34.103 10.7161V14.0642M19.6804 33.3802V28.6156M19.6804 33.3802L22.8997 32.0292M19.6804 33.3802L6.54554 27.8682M19.6804 17.026L30.2398 12.4063M19.6804 17.026L16.4427 15.6095M19.6804 17.026V18.4425M19.6804 28.6156L30.2398 12.4063M19.6804 28.6156V18.4425M22.8997 32.0292L33.7872 27.4604C33.9785 27.3801 34.103 27.1929 34.103 26.9854V14.0642M22.8997 32.0292L34.103 14.0642M5.25781 23.7222V26.9854C5.25781 27.1929 5.38228 27.3801 5.57359 27.4604L6.54554 27.8682M5.25781 23.7222L16.4427 15.6095M6.54554 27.8682L19.6804 18.4425" stroke="#1E1E1E" stroke-width="1.03018" stroke-linecap="round" stroke-linejoin="round"/>+</mask>+<g mask="url(#mask0_1875_4928)">+<rect x="2.35156" y="1.49805" width="34.6643" height="34.6643" fill="black"/>+</g>+</svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex e04764362c9c..93315e314d2b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -216,6 +216,7 @@ the row lists both.| hatchet | HTTP | requests | ✅ || healthchecks | HTTP | requests | ✅ || height | HTTP | requests | ✅ |+| helicone | HTTP | requests | ✅ || hellobaton | HTTP | requests | ✅ || hetzner | HTTP | requests | ✅ || hibob | HTTP | requests | ✅ |@@ -665,7 +666,6 @@ doesn't conflict with concurrent PRs.- harness- harvey- heap-- helicone- helpscout- heroku- hetznerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 22039ae2e82f..7b1992ecde16 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -1892,7 +1892,8 @@ class HeightSourceConfig(config.Config):@config.configclass HeliconeSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu"] = config.value(default="us")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/canonical_descriptions.pynew file mode 100644index 000000000000..015b882a0efe--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/canonical_descriptions.py@@ -0,0 +1,91 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "requests": {+ "description": (+ "One row per LLM request logged through Helicone, with the model, provider, token usage, "+ "cost, latency, user, and custom properties attached to the call."+ ),+ "docs_url": "https://docs.helicone.ai/rest/request/post-v1requestquery-clickhouse",+ "columns": {+ "request_id": "Unique identifier (UUID) of the logged request.",+ "request_created_at": "Timestamp when Helicone received the request.",+ "response_id": "Unique identifier of the response paired with the request.",+ "response_created_at": "Timestamp when the provider's response was received.",+ "response_status": "HTTP status code returned by the LLM provider.",+ "request_body": "The request payload sent to the provider (may be truncated or offloaded to storage).",+ "response_body": "The response payload from the provider (may be truncated or offloaded to storage).",+ "signed_body_url": "Short-lived signed URL to the full request/response bodies in Helicone's storage.",+ "request_model": "Model name as sent in the request.",+ "response_model": "Model name as reported in the provider's response.",+ "model": "Resolved model name for the request.",+ "provider": "LLM provider that served the request (e.g. OpenAI, Anthropic).",+ "request_path": "Provider API path the request was sent to.",+ "target_url": "Full provider URL the request was forwarded to.",+ "request_user_id": "User identifier attached to the request via the Helicone-User-Id header.",+ "request_properties": "Custom properties attached to the request via Helicone-Property-* headers.",+ "prompt_tokens": "Number of prompt (input) tokens used by the request.",+ "completion_tokens": "Number of completion (output) tokens generated.",+ "total_tokens": "Total tokens used by the request.",+ "reasoning_tokens": "Reasoning tokens used, for models that report them.",+ "prompt_cache_read_tokens": "Prompt tokens served from the provider's prompt cache.",+ "prompt_cache_write_tokens": "Prompt tokens written to the provider's prompt cache.",+ "cost": "Cost of the request as calculated by Helicone.",+ "delay_ms": "End-to-end latency of the request in milliseconds.",+ "time_to_first_token": "Milliseconds until the first token of the response arrived.",+ "prompt_id": "Identifier of the Helicone prompt used for the request, if any.",+ "prompt_version": "Version of the Helicone prompt used for the request, if any.",+ "feedback_rating": "User feedback rating submitted for the request, if any.",+ "scores": "Evaluation scores attached to the request, if any.",+ "country_code": "Country the request originated from.",+ "cache_enabled": "Whether Helicone response caching was enabled for the request.",+ "cached": "Whether the response was served from Helicone's cache.",+ },+ },+ "sessions": {+ "description": (+ "Aggregated metrics for each Helicone session (requests grouped via the Helicone-Session-Id "+ "header): totals for cost, requests, and tokens, plus the users involved."+ ),+ "docs_url": "https://docs.helicone.ai/rest/session/post-v1sessionquery",+ "columns": {+ "session_id": "Unique identifier of the session (Helicone-Session-Id header value).",+ "session_name": "Name given to the session via the Helicone-Session-Name header.",+ "created_at": "Timestamp of the first request in the session.",+ "latest_request_created_at": "Timestamp of the most recent request in the session.",+ "total_cost": "Total cost of all requests in the session.",+ "total_requests": "Number of requests in the session.",+ "prompt_tokens": "Total prompt (input) tokens used across the session.",+ "completion_tokens": "Total completion (output) tokens generated across the session.",+ "total_tokens": "Total tokens used across the session.",+ "avg_latency": "Average request latency across the session, in milliseconds.",+ "user_ids": "User identifiers that appear on the session's requests.",+ },+ },+ "users": {+ "description": (+ "Per-user usage aggregates across all logged requests: request count, token usage, and cost, "+ "keyed by the Helicone-User-Id header value."+ ),+ "docs_url": "https://docs.helicone.ai/rest/user/post-v1userquery",+ "columns": {+ "user_id": "User identifier attached to requests via the Helicone-User-Id header.",+ "count": "Number of requests made by the user.",+ "prompt_tokens": "Total prompt (input) tokens used by the user.",+ "completion_tokens": "Total completion (output) tokens generated for the user.",+ "cost": "Total cost of the user's requests.",+ },+ },+ "prompts": {+ "description": "Prompts managed in Helicone's prompt registry, with their names and tags.",+ "docs_url": "https://docs.helicone.ai/rest/prompts/post-v1prompt-2025-query",+ "columns": {+ "id": "Unique identifier of the prompt.",+ "name": "Name of the prompt.",+ "tags": "Tags associated with the prompt.",+ "created_at": "Timestamp when the prompt was created.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/helicone.py b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/helicone.pynew file mode 100644index 000000000000..1bd2d6a9650f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/helicone.py@@ -0,0 +1,357 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.helicone.settings import (+ HELICONE_ENDPOINTS,+ HELICONE_HOSTS,+ PROMPTS_ENDPOINT,+ PROMPTS_PAGE_SIZE,+ REQUESTS_DEFAULT_LOOKBACK_DAYS,+ REQUESTS_ENDPOINT,+ REQUESTS_PAGE_SIZE,+ SESSIONS_ENDPOINT,+ SESSIONS_PAGE_SIZE,+ USERS_ENDPOINT,+)++REQUEST_TIMEOUT_SECONDS = 120+RETRY_MAX_ATTEMPTS = 5+++class HeliconeRetryableError(Exception):+ pass+++class HeliconeResumeConfig:+ # Where to resume the endpoint being paged: for offset-based endpoints (requests, sessions)+ # it's the next request's `offset` (rows already yielded); for the page-based prompts endpoint+ # it's the next page index.+ offset: int = 0+ # The window bounds captured when the run started, pinned in the resume state so a resumed+ # attempt pages the exact same result set instead of recomputing "now" and shifting rows+ # across page boundaries. `created_after` is the ISO gte cutoff for the incremental request+ # log; `end_time_unix_ms` bounds the sessions time filter.+ created_after: str | None = None+ end_time_unix_ms: int | None = None+++def _host(region: str) -> str:+ return HELICONE_HOSTS.get(region, HELICONE_HOSTS["us"])+++def _headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}+++def _format_timestamp(value: Any) -> str | None:+ """Format an incremental cursor as the ISO 8601 UTC string Helicone's timestamp operators take."""+ if isinstance(value, datetime):+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+ if isinstance(value, date):+ return _format_timestamp(datetime.combine(value, datetime.min.time(), tzinfo=UTC))+ if isinstance(value, str) and value:+ return value+ return None+++def _extract_data(body: Any, url: str) -> list[dict[str, Any]]:+ """Unwrap Helicone's `{"data": [...], "error": null}` result union.++ The prompts endpoint documents a bare array response, so lists pass through as-is.+ """+ if isinstance(body, list):+ return body+ if isinstance(body, dict):+ error = body.get("error")+ if error:+ raise Exception(f"Helicone API returned an error for {url}: {error}")+ data = body.get("data")+ if isinstance(data, list):+ return data+ return []+ return []+++@retry(+ retry=retry_if_exception_type((HeliconeRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(RETRY_MAX_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _post(+ session: requests.Session, url: str, headers: dict[str, str], body: dict[str, Any], logger: FilteringBoundLogger+) -> Any:+ response = session.post(url, headers=headers, json=body, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise HeliconeRetryableError(f"Helicone API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Helicone API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str, region: str) -> tuple[bool, Optional[str]]:+ # Probe the point-query request endpoint with a single-row lookup: it authenticates with the+ # same key as every other endpoint and is designed for small reads (the bulk clickhouse+ # variant is documented to time out on point queries).+ url = f"{_host(region)}/v1/request/query"+ try:+ # capture=False so request/response bodies (which can carry customer prompts and model+ # output) never land in diagnostic HTTP samples; redact the key for defense in depth.+ response = make_tracked_session(redact_values=(api_key,), capture=False).post(+ url,+ headers=_headers(api_key),+ json={"filter": "all", "limit": 1, "offset": 0},+ timeout=30,+ )+ except Exception as e:+ return False, f"Could not reach Helicone ({e}). Please check your network and selected region, then retry."++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return (+ False,+ "Helicone rejected the API key. Check the key in your Helicone dashboard (Settings → API Keys) "+ "and that the selected region matches where your Helicone organization lives.",+ )+ return False, f"Unexpected response from Helicone (status {response.status_code})."+++def _requests_rows(+ session: requests.Session,+ host: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HeliconeResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> Iterator[list[dict[str, Any]]]:+ url = f"{host}{HELICONE_ENDPOINTS[REQUESTS_ENDPOINT].path}"++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ offset = resume.offset+ created_after = resume.created_after+ logger.debug(f"Helicone: resuming requests from offset={offset}, created_after={created_after}")+ else:+ offset = 0+ if should_use_incremental_field and not db_incremental_field_last_value:+ # First incremental sync: bound the backfill instead of paging the org's full history.+ db_incremental_field_last_value = datetime.now(UTC) - timedelta(days=REQUESTS_DEFAULT_LOOKBACK_DAYS)+ created_after = (+ _format_timestamp(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value+ else None+ )++ filter_field = incremental_field or "request_created_at"+ # Each condition must be its own filter leaf in Helicone's AST; a single gte condition needs no+ # branch node. The gte filter rides in the body of every page request, so pagination stays+ # bounded by the watermark on every page (no client-side termination needed).+ filter_node: Any = {"request_response_rmt": {filter_field: {"gte": created_after}}} if created_after else "all"++ while True:+ body = {+ "filter": filter_node,+ "limit": REQUESTS_PAGE_SIZE,+ "offset": offset,+ # Ascending creation-time sort so the pipeline's incremental watermark can checkpoint+ # after every batch (matches SourceResponse.sort_mode="asc"). Appends land after the+ # current offset, so new rows arriving mid-sync can't shift earlier pages.+ "sort": {"created_at": "asc"},+ }+ rows = _extract_data(_post(session, url, headers, body, logger), url)+ if not rows:+ break++ yield rows+ offset += len(rows)+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge+ # dedupes on request_id.+ resumable_source_manager.save_state(HeliconeResumeConfig(offset=offset, created_after=created_after))++ if len(rows) < REQUESTS_PAGE_SIZE:+ break+++def _sessions_rows(+ session: requests.Session,+ host: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HeliconeResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ url = f"{host}{HELICONE_ENDPOINTS[SESSIONS_ENDPOINT].path}"++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.end_time_unix_ms is not None:+ offset = resume.offset+ end_time_unix_ms = resume.end_time_unix_ms+ logger.debug(f"Helicone: resuming sessions from offset={offset}")+ else:+ offset = 0+ end_time_unix_ms = int(datetime.now(UTC).timestamp() * 1000)++ while True:+ # search/timeFilter/timezoneDifference/filter are required by the API even when unused.+ body = {+ "search": "",+ "timeFilter": {"startTimeUnixMs": 0, "endTimeUnixMs": end_time_unix_ms},+ "timezoneDifference": 0,+ "filter": "all",+ "offset": offset,+ "limit": SESSIONS_PAGE_SIZE,+ }+ rows = _extract_data(_post(session, url, headers, body, logger), url)+ if not rows:+ break++ yield rows+ offset += len(rows)+ resumable_source_manager.save_state(HeliconeResumeConfig(offset=offset, end_time_unix_ms=end_time_unix_ms))++ if len(rows) < SESSIONS_PAGE_SIZE:+ break+++def _users_rows(+ session: requests.Session,+ host: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ url = f"{host}{HELICONE_ENDPOINTS[USERS_ENDPOINT].path}"+ # The endpoint takes an optional userIds/timeFilter and has no pagination; an explicit+ # epoch-to-now window makes the full-history intent unambiguous.+ body = {+ "timeFilter": {+ "startTimeUnixSeconds": 0,+ "endTimeUnixSeconds": int(datetime.now(UTC).timestamp()),+ }+ }+ rows = _extract_data(_post(session, url, headers, body, logger), url)+ if rows:+ yield rows+++def _prompts_rows(+ session: requests.Session,+ host: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HeliconeResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ url = f"{host}{HELICONE_ENDPOINTS[PROMPTS_ENDPOINT].path}"++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ # This endpoint is page-based, so `offset` holds the next page index directly (not a row count)+ # — deriving a page from an accumulated row count drifts the moment a page comes back short.+ page = resume.offset if resume is not None else 0++ while True:+ # search/tagsFilter are required by the API; empty values match every prompt.+ body = {+ "search": "",+ "tagsFilter": [],+ "page": page,+ "pageSize": PROMPTS_PAGE_SIZE,+ }+ rows = _extract_data(_post(session, url, headers, body, logger), url)+ if not rows:+ break++ yield rows+ page += 1+ resumable_source_manager.save_state(HeliconeResumeConfig(offset=page))++ if len(rows) < PROMPTS_PAGE_SIZE:+ break+++def _get_rows(+ api_key: str,+ region: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HeliconeResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> Iterator[list[dict[str, Any]]]:+ host = _host(region)+ headers = _headers(api_key)+ # One session reused across every page so urllib3 keeps the connection alive instead of+ # re-handshaking per request. capture=False so request/response bodies (which can carry+ # customer prompts and model output) never land in diagnostic HTTP samples; redact the key+ # for defense in depth.+ session = make_tracked_session(redact_values=(api_key,), capture=False)++ if endpoint == REQUESTS_ENDPOINT:+ yield from _requests_rows(+ session,+ host,+ headers,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ incremental_field,+ )+ elif endpoint == SESSIONS_ENDPOINT:+ yield from _sessions_rows(session, host, headers, logger, resumable_source_manager)+ elif endpoint == USERS_ENDPOINT:+ yield from _users_rows(session, host, headers, logger)+ elif endpoint == PROMPTS_ENDPOINT:+ yield from _prompts_rows(session, host, headers, logger, resumable_source_manager)+ else:+ raise ValueError(f"Unknown Helicone endpoint: {endpoint}")+++def helicone_source(+ api_key: str,+ region: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HeliconeResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = HELICONE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: _get_rows(+ api_key=api_key,+ region=region,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/settings.pynew file mode 100644index 000000000000..8790fcd2808d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/settings.py@@ -0,0 +1,87 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Helicone runs regional deployments. An API key belongs to a single org in one region, so the+# host is chosen by the `region` form field rather than a user-supplied URL (no SSRF surface —+# the set is fixed).+HELICONE_HOSTS: dict[str, str] = {+ "us": "https://api.helicone.ai",+ "eu": "https://eu.api.helicone.ai",+}++REQUESTS_ENDPOINT = "requests"+SESSIONS_ENDPOINT = "sessions"+USERS_ENDPOINT = "users"+PROMPTS_ENDPOINT = "prompts"++# /v1/request/query-clickhouse is Helicone's bulk-export endpoint; their export CLI pages it with+# limit/offset up to 10k rows per request. Rows can embed full request/response bodies, so we keep+# pages an order of magnitude smaller to bound response sizes.+REQUESTS_PAGE_SIZE = 1000+SESSIONS_PAGE_SIZE = 1000+PROMPTS_PAGE_SIZE = 100++# Bound the first incremental sync of the request log to a recent window so an initial backfill of+# a high-volume org doesn't attempt to page through years of history. Subsequent incremental syncs+# only fetch rows newer than the stored cursor.+REQUESTS_DEFAULT_LOOKBACK_DAYS = 365+++@dataclass+class HeliconeEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ supports_incremental: bool = False+ supports_append: bool = False+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Must be a STABLE datetime field (never an update-tracking one) so partitions don't rewrite+ # on every sync.+ partition_key: str | None = None+++HELICONE_ENDPOINTS: dict[str, HeliconeEndpointConfig] = {+ REQUESTS_ENDPOINT: HeliconeEndpointConfig(+ name=REQUESTS_ENDPOINT,+ path="/v1/request/query-clickhouse",+ primary_keys=["request_id"],+ supports_incremental=True,+ supports_append=True,+ # The request log is append-only, so the creation timestamp is a reliable server-side+ # cursor (the filter AST supports gte on request_created_at).+ incremental_fields=[+ {+ "label": "request_created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "request_created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ partition_key="request_created_at",+ ),+ # Sessions, users, and prompts are aggregates/metadata whose rows change in place (a session+ # accrues requests, a user accrues cost) with no server-side "changed since" filter, so they+ # are full-refresh only.+ SESSIONS_ENDPOINT: HeliconeEndpointConfig(+ name=SESSIONS_ENDPOINT,+ path="/v1/session/query",+ primary_keys=["session_id"],+ ),+ USERS_ENDPOINT: HeliconeEndpointConfig(+ name=USERS_ENDPOINT,+ path="/v1/user/query",+ primary_keys=["user_id"],+ ),+ PROMPTS_ENDPOINT: HeliconeEndpointConfig(+ name=PROMPTS_ENDPOINT,+ path="/v1/prompt-2025/query",+ primary_keys=["id"],+ ),+}++ENDPOINTS = tuple(HELICONE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in HELICONE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/source.pyindex af07a7c1907f..56aaed8b17b9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/source.py@@ -1,31 +1,169 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HeliconeSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.helicone.helicone import (+ HeliconeResumeConfig,+ helicone_source,+ validate_credentials as validate_helicone_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.helicone.settings import (+ HELICONE_ENDPOINTS,+ REQUESTS_DEFAULT_LOOKBACK_DAYS,+ REQUESTS_ENDPOINT,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class HeliconeSource(SimpleSource[HeliconeSourceConfig]):+class HeliconeSource(ResumableSource[HeliconeSourceConfig, HeliconeResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.HELICONE+ @property+ def connection_host_fields(self) -> list[str]:+ # `region` picks the host the stored API key is sent to. Retargeting it must re-require the+ # secret so a preserved key can't be aimed at a different regional endpoint without re-entry.+ return ["region"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.HELICONE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Helicone",- iconPath="/static/services/helicone.png",+ caption=(+ "Connect Helicone to sync your logged LLM requests, sessions, per-user usage, and prompts "+ "into the PostHog Data warehouse.\n\n"+ "Generate an API key in your [Helicone dashboard](https://us.helicone.ai/settings/api-keys) "+ "(Settings → API Keys). Pick the region that matches where your Helicone organization lives."+ ),+ iconPath="/static/services/helicone.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/helicone",keywords=["llm", "observability", "ai gateway", "helicone"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="sk-helicone-...",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (api.helicone.ai)", value="us"),+ SourceFieldSelectConfigOption(label="EU (eu.api.helicone.ai)", value="eu"),+ ],+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.helicone.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ invalid_key_message = (+ "Your Helicone API key is invalid or has been revoked, or the selected region doesn't match your "+ "Helicone organization. Generate a new key in your Helicone dashboard (Settings → API Keys) and "+ "reconnect."+ )+ # A bad key surfaces as a requests HTTPError when the transport calls raise_for_status().+ # Match the stable status text and both regional hosts, not the per-request path.+ return {+ "401 Client Error: Unauthorized for url: https://api.helicone.ai": invalid_key_message,+ "401 Client Error: Unauthorized for url: https://eu.api.helicone.ai": invalid_key_message,+ "403 Client Error: Forbidden for url: https://api.helicone.ai": invalid_key_message,+ "403 Client Error: Forbidden for url: https://eu.api.helicone.ai": invalid_key_message,+ }++ def get_schemas(+ self,+ config: HeliconeSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == REQUESTS_ENDPOINT:+ return f"Only syncs the last {REQUESTS_DEFAULT_LOOKBACK_DAYS} days on initial incremental sync"+ return None++ schemas = [+ SourceSchema(+ name=endpoint.name,+ supports_incremental=endpoint.supports_incremental,+ supports_append=endpoint.supports_append,+ incremental_fields=endpoint.incremental_fields,+ description=_description(endpoint.name),+ )+ for endpoint in HELICONE_ENDPOINTS.values()+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: HeliconeSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_helicone_credentials(config.api_key, config.region)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HeliconeResumeConfig]:+ return ResumableSourceManager[HeliconeResumeConfig](inputs, HeliconeResumeConfig)++ def source_for_pipeline(+ self,+ config: HeliconeSourceConfig,+ resumable_source_manager: ResumableSourceManager[HeliconeResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return helicone_source(+ api_key=config.api_key,+ region=config.region,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/tests/test_helicone.py b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/tests/test_helicone.pynew file mode 100644index 000000000000..fdfcdf44dce8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/tests/test_helicone.py@@ -0,0 +1,356 @@+from datetime import UTC, datetime+from typing import Any++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.helicone.helicone import (+ HeliconeResumeConfig,+ _extract_data,+ _format_timestamp,+ _prompts_rows,+ _requests_rows,+ _sessions_rows,+ _users_rows,+ helicone_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.helicone.settings import (+ PROMPTS_ENDPOINT,+ REQUESTS_ENDPOINT,+ SESSIONS_ENDPOINT,+ USERS_ENDPOINT,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.helicone.helicone"+++def _response(status: int = 200, json_body: Any = None, text: str = "") -> mock.MagicMock:+ response = mock.MagicMock(spec=requests.Response)+ response.status_code = status+ response.ok = 200 <= status < 300+ response.text = text+ response.json.return_value = json_body+ return response+++def _session_returning(responses: list[mock.MagicMock]) -> mock.MagicMock:+ session = mock.MagicMock(spec=requests.Session)+ session.post.side_effect = responses+ return session+++def _no_resume_manager() -> mock.MagicMock:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ return manager+++class TestExtractData:+ @parameterized.expand(+ [+ ("wrapped", {"data": [{"id": 1}], "error": None}, [{"id": 1}]),+ ("bare_list", [{"id": 2}], [{"id": 2}]),+ ("null_data", {"data": None, "error": None}, []),+ ("missing_data", {}, []),+ ]+ )+ def test_unwraps_result_shapes(self, _name: str, body: Any, expected: list[dict[str, Any]]) -> None:+ assert _extract_data(body, "https://api.helicone.ai/x") == expected++ def test_error_result_raises(self) -> None:+ with pytest.raises(Exception, match="unauthorized"):+ _extract_data({"data": None, "error": "unauthorized"}, "https://api.helicone.ai/x")+++class TestFormatTimestamp:+ @parameterized.expand(+ [+ ("aware_datetime", datetime(2026, 3, 4, 2, 58, 14, 123000, tzinfo=UTC), "2026-03-04T02:58:14.123Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),+ ("string_passthrough", "2026-03-04T00:00:00Z", "2026-03-04T00:00:00Z"),+ ("none", None, None),+ ]+ )+ def test_formats_cursor_values(self, _name: str, value: Any, expected: str | None) -> None:+ assert _format_timestamp(value) == expected+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("forbidden", 403, False),+ ("server_error", 500, False),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, expected_valid: bool) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.post.return_value = _response(status=status)+ is_valid, message = validate_credentials("key", "us")++ assert is_valid is expected_valid+ if expected_valid:+ assert message is None+ else:+ assert message is not None++ def test_network_error_is_not_valid(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.post.side_effect = requests.ConnectionError("boom")+ is_valid, message = validate_credentials("key", "us")++ assert is_valid is False+ assert message is not None++ @parameterized.expand([("us", "https://api.helicone.ai"), ("eu", "https://eu.api.helicone.ai")])+ def test_uses_regional_host(self, region: str, expected_host: str) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.post.return_value = _response(status=200)+ validate_credentials("key", region)++ called_url = make_session.return_value.post.call_args.args[0]+ assert called_url.startswith(expected_host)+++class TestRequestsRows:+ def _rows(self, session: mock.MagicMock, manager: mock.MagicMock, **kwargs: Any) -> list[list[dict[str, Any]]]:+ defaults: dict[str, Any] = {+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "incremental_field": None,+ }+ defaults.update(kwargs)+ return list(+ _requests_rows(+ session,+ "https://api.helicone.ai",+ {},+ mock.MagicMock(),+ manager,+ **defaults,+ )+ )++ def test_full_refresh_pages_until_short_page(self) -> None:+ with mock.patch(f"{MODULE}.REQUESTS_PAGE_SIZE", 2):+ session = _session_returning(+ [+ _response(json_body={"data": [{"request_id": "a"}, {"request_id": "b"}], "error": None}),+ _response(json_body={"data": [{"request_id": "c"}], "error": None}),+ ]+ )+ manager = _no_resume_manager()++ batches = self._rows(session, manager)++ assert [row["request_id"] for batch in batches for row in batch] == ["a", "b", "c"]++ bodies = [call.kwargs["json"] for call in session.post.call_args_list]+ assert [body["offset"] for body in bodies] == [0, 2]+ assert all(body["filter"] == "all" for body in bodies)+ assert all(body["sort"] == {"created_at": "asc"} for body in bodies)++ # State is saved after each yielded page with the cumulative offset.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert [state.offset for state in saved] == [2, 3]++ def test_incremental_builds_gte_filter_leaf(self) -> None:+ session = _session_returning([_response(json_body={"data": [], "error": None})])+ manager = _no_resume_manager()++ self._rows(+ session,+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 1, 12, 0, 0, tzinfo=UTC),+ incremental_field="request_created_at",+ )++ body = session.post.call_args.kwargs["json"]+ # Helicone's filter AST requires one condition per leaf, wrapped in the table name.+ assert body["filter"] == {"request_response_rmt": {"request_created_at": {"gte": "2026-06-01T12:00:00.000Z"}}}++ @freeze_time("2026-06-04 12:00:00")+ def test_first_incremental_sync_bounds_backfill_to_lookback(self) -> None:+ session = _session_returning([_response(json_body={"data": [], "error": None})])+ manager = _no_resume_manager()++ self._rows(session, manager, should_use_incremental_field=True, db_incremental_field_last_value=None)++ body = session.post.call_args.kwargs["json"]+ assert body["filter"] == {"request_response_rmt": {"request_created_at": {"gte": "2025-06-04T12:00:00.000Z"}}}++ def test_resume_state_restores_offset_and_pins_cutoff(self) -> None:+ session = _session_returning([_response(json_body={"data": [], "error": None})])+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = HeliconeResumeConfig(offset=4000, created_after="2026-01-01T00:00:00.000Z")++ self._rows(+ session,+ manager,+ should_use_incremental_field=True,+ # A resumed run must page the window captured at run start, not this newer value.+ db_incremental_field_last_value=datetime(2026, 5, 1, tzinfo=UTC),+ )++ body = session.post.call_args.kwargs["json"]+ assert body["offset"] == 4000+ assert body["filter"] == {"request_response_rmt": {"request_created_at": {"gte": "2026-01-01T00:00:00.000Z"}}}++ def test_api_error_result_raises(self) -> None:+ session = _session_returning([_response(json_body={"data": None, "error": "invalid filter"})])+ manager = _no_resume_manager()++ with pytest.raises(Exception, match="invalid filter"):+ self._rows(session, manager)+++class TestSessionsRows:+ @freeze_time("2026-06-04 12:00:00")+ def test_sends_required_params_and_pages_until_short_page(self) -> None:+ with mock.patch(f"{MODULE}.SESSIONS_PAGE_SIZE", 2):+ session = _session_returning(+ [+ _response(json_body={"data": [{"session_id": "s1"}, {"session_id": "s2"}], "error": None}),+ _response(json_body={"data": [], "error": None}),+ ]+ )+ manager = _no_resume_manager()++ batches = list(_sessions_rows(session, "https://api.helicone.ai", {}, mock.MagicMock(), manager))++ assert [row["session_id"] for batch in batches for row in batch] == ["s1", "s2"]++ body = session.post.call_args_list[0].kwargs["json"]+ # These fields are required by the API even when unused; dropping one is a 400.+ assert body["search"] == ""+ assert body["timezoneDifference"] == 0+ assert body["filter"] == "all"+ assert body["timeFilter"] == {"startTimeUnixMs": 0, "endTimeUnixMs": 1780574400000}++ def test_resume_pins_time_window_across_attempts(self) -> None:+ session = _session_returning([_response(json_body={"data": [], "error": None})])+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = HeliconeResumeConfig(offset=6, end_time_unix_ms=1700000000000)++ list(_sessions_rows(session, "https://api.helicone.ai", {}, mock.MagicMock(), manager))++ body = session.post.call_args.kwargs["json"]+ assert body["offset"] == 6+ # Recomputing "now" on resume would shift rows across page boundaries.+ assert body["timeFilter"]["endTimeUnixMs"] == 1700000000000+++class TestUsersRows:+ def test_yields_rows_from_single_unpaginated_request(self) -> None:+ session = _session_returning([_response(json_body={"data": [{"user_id": "u1", "cost": 1.5}], "error": None})])++ batches = list(_users_rows(session, "https://api.helicone.ai", {}, mock.MagicMock()))++ assert batches == [[{"user_id": "u1", "cost": 1.5}]]+ assert session.post.call_count == 1+ assert "timeFilter" in session.post.call_args.kwargs["json"]++ def test_empty_result_yields_nothing(self) -> None:+ session = _session_returning([_response(json_body={"data": [], "error": None})])+ assert list(_users_rows(session, "https://api.helicone.ai", {}, mock.MagicMock())) == []+++class TestPromptsRows:+ def test_pages_with_page_numbers_and_handles_bare_array_response(self) -> None:+ with mock.patch(f"{MODULE}.PROMPTS_PAGE_SIZE", 2):+ session = _session_returning(+ [+ # The prompts endpoint documents a bare-array response (no {data, error} wrapper).+ _response(json_body=[{"id": "p1"}, {"id": "p2"}]),+ _response(json_body=[{"id": "p3"}]),+ ]+ )+ manager = _no_resume_manager()++ batches = list(_prompts_rows(session, "https://api.helicone.ai", {}, mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["p1", "p2", "p3"]++ bodies = [call.kwargs["json"] for call in session.post.call_args_list]+ assert [body["page"] for body in bodies] == [0, 1]+ assert all(body["search"] == "" and body["tagsFilter"] == [] for body in bodies)++ def test_resume_requests_saved_page_and_advances_by_page(self) -> None:+ # Resume state holds the page index directly; deriving a page from a cumulative row count+ # (offset // pageSize) would drift and re-request an already-paged page after a short page.+ session = _session_returning([_response(json_body=[{"id": "p8"}])])+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = HeliconeResumeConfig(offset=3)++ list(_prompts_rows(session, "https://api.helicone.ai", {}, mock.MagicMock(), manager))++ assert session.post.call_args.kwargs["json"]["page"] == 3+ assert manager.save_state.call_args_list[0].args[0].offset == 4+++class TestHeliconeSourceResponse:+ def test_requests_response_metadata(self) -> None:+ response = helicone_source(+ api_key="key",+ region="us",+ endpoint=REQUESTS_ENDPOINT,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(spec=ResumableSourceManager),+ )++ assert response.name == REQUESTS_ENDPOINT+ assert response.primary_keys == ["request_id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["request_created_at"]+ assert response.partition_format == "week"+ assert response.sort_mode == "asc"++ @parameterized.expand(+ [+ (SESSIONS_ENDPOINT, ["session_id"]),+ (USERS_ENDPOINT, ["user_id"]),+ (PROMPTS_ENDPOINT, ["id"]),+ ]+ )+ def test_full_refresh_response_metadata(self, endpoint: str, expected_primary_keys: list[str]) -> None:+ response = helicone_source(+ api_key="key",+ region="us",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(spec=ResumableSourceManager),+ )++ assert response.name == endpoint+ assert response.primary_keys == expected_primary_keys+ assert response.partition_mode is None+ assert response.partition_keys is None+++class TestNonRetryableErrorMessages:+ def test_401_http_error_matches_a_non_retryable_key(self) -> None:+ # `get_non_retryable_errors` matches on substrings of str(exc); this guards the keys+ # against drift from the message `requests.raise_for_status` actually produces.+ from products.warehouse_sources.backend.temporal.data_imports.sources.helicone.source import HeliconeSource++ response = requests.Response()+ response.status_code = 401+ response.url = "https://api.helicone.ai/v1/request/query-clickhouse"+ response.reason = "Unauthorized"++ with pytest.raises(requests.HTTPError) as exc_info:+ response.raise_for_status()++ keys = HeliconeSource().get_non_retryable_errors().keys()+ assert any(key in str(exc_info.value) for key in keys)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/tests/test_helicone_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/tests/test_helicone_source.pynew file mode 100644index 000000000000..c6085b983d16--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/tests/test_helicone_source.py@@ -0,0 +1,154 @@+from types import SimpleNamespace+from typing import cast++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HeliconeSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.helicone.helicone import HeliconeResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.helicone.settings import (+ ENDPOINTS,+ PROMPTS_ENDPOINT,+ REQUESTS_ENDPOINT,+ SESSIONS_ENDPOINT,+ USERS_ENDPOINT,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.helicone.source import HeliconeSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++FULL_REFRESH_ENDPOINTS = [SESSIONS_ENDPOINT, USERS_ENDPOINT, PROMPTS_ENDPOINT]+++class TestHeliconeSource:+ def setup_method(self):+ self.source = HeliconeSource()+ self.team_id = 123+ self.config = HeliconeSourceConfig(api_key="sk-helicone-key", region="us")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.HELICONE++ def test_region_is_a_connection_host_field(self):+ # Changing the regional host must force re-entry of the API key (credential retargeting guard).+ assert self.source.connection_host_fields == ["region"]++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Helicone"+ assert config.label == "Helicone"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/helicone.svg"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/helicone"+ assert len(config.fields) == 2++ api_key_field = config.fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ region_field = config.fields[1]+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.name == "region"+ assert region_field.defaultValue == "us"+ assert {option.value for option in region_field.options} == {"us", "eu"}++ @pytest.mark.parametrize("status_text", ["401 Client Error: Unauthorized", "403 Client Error: Forbidden"])+ @pytest.mark.parametrize("host", ["https://api.helicone.ai", "https://eu.api.helicone.ai"])+ def test_non_retryable_errors_cover_both_regional_hosts(self, status_text, host):+ assert f"{status_text} for url: {host}" in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_every_endpoint(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_requests_endpoint_advertises_incremental(self):+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == REQUESTS_ENDPOINT)+ assert schema.supports_incremental is True+ assert schema.supports_append is True+ assert {field["field"] for field in schema.incremental_fields} == {"request_created_at"}++ @pytest.mark.parametrize("endpoint", FULL_REFRESH_ENDPOINTS)+ def test_full_refresh_endpoints_do_not_advertise_incremental(self, endpoint):+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=[REQUESTS_ENDPOINT])+ assert [schema.name for schema in schemas] == [REQUESTS_ENDPOINT]++ @pytest.mark.parametrize(+ "mock_return",+ [(True, None), (False, "Helicone rejected the API key.")],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.helicone.source.validate_helicone_credentials"+ )+ def test_validate_credentials_plumbs_transport_result(self, mock_validate, mock_return):+ mock_validate.return_value = mock_return++ assert self.source.validate_credentials(self.config, self.team_id) == mock_return+ mock_validate.assert_called_once_with(self.config.api_key, self.config.region)++ def test_get_resumable_source_manager_is_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is HeliconeResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.helicone.source.helicone_source")+ def test_source_for_pipeline_plumbs_inputs(self, mock_helicone_source):+ mock_helicone_source.return_value = SimpleNamespace(name=REQUESTS_ENDPOINT)+ manager = mock.MagicMock(spec=ResumableSourceManager)+ logger = mock.MagicMock()+ inputs = SimpleNamespace(+ schema_name=REQUESTS_ENDPOINT,+ team_id=self.team_id,+ job_id="job-1",+ logger=logger,+ should_use_incremental_field=True,+ incremental_field="request_created_at",+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )++ response = self.source.source_for_pipeline(self.config, manager, cast(SourceInputs, inputs))++ mock_helicone_source.assert_called_once_with(+ api_key="sk-helicone-key",+ region="us",+ endpoint=REQUESTS_ENDPOINT,+ logger=logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ incremental_field="request_created_at",+ )+ assert response is mock_helicone_source.return_value++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.helicone.source.helicone_source")+ def test_source_for_pipeline_drops_last_value_on_full_refresh(self, mock_helicone_source):+ mock_helicone_source.return_value = SimpleNamespace(name=SESSIONS_ENDPOINT)+ inputs = SimpleNamespace(+ schema_name=SESSIONS_ENDPOINT,+ team_id=self.team_id,+ job_id="job-2",+ logger=mock.MagicMock(),+ should_use_incremental_field=False,+ incremental_field=None,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )++ self.source.source_for_pipeline(+ self.config, mock.MagicMock(spec=ResumableSourceManager), cast(SourceInputs, inputs)+ )++ # When the user isn't running incrementally, no watermark should leak through.+ assert mock_helicone_source.call_args.kwargs["db_incremental_field_last_value"] is None