: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 langfuse import source (#70711)
Tom Owersdef91405551a
diff --git a/frontend/public/services/langfuse.svg b/frontend/public/services/langfuse.svgnew file mode 100644index 000000000000..d56d582be783--- /dev/null+++ b/frontend/public/services/langfuse.svg@@ -0,0 +1,8 @@+<svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M254.75 302.25L285.25 326.75C285.25 326.75 308.587 309.418 325.75 306.875C343.75 304.208 362.954 314.244 380.75 326.208C407.629 344.279 430.25 367.208 430.25 367.208L456.75 341.208C456.75 341.208 383.686 262.047 325.75 269.208C287.75 273.905 254.75 302.25 254.75 302.25Z" fill="#FF5D5F"/>+<path d="M80.25 151.286L55.25 178.786C55.25 178.786 124.902 243.786 179.75 243.786C204.75 243.786 239.419 224.201 269.25 198.757C286.25 184.257 305.25 167.786 324.25 167.786C337.021 167.786 353.866 174.551 369.75 192.316C369.75 192.316 380.003 186.168 386.25 181.75C391.74 177.868 399.896 171.25 399.896 171.25C377.047 146.864 343.998 129.038 324.25 130.786C292.25 130.79 269.25 150.711 240.75 173.75C212.25 196.789 200.25 206.286 179.75 206.286C145.25 206.286 80.25 151.286 80.25 151.286Z" fill="#4E9CFF"/>+<path d="M80.25 360.75L55.25 333.25C55.25 333.25 124.902 268.25 179.75 268.25C204.75 268.25 239.419 287.835 269.25 313.279C286.25 327.779 305.25 344.25 324.25 344.25C337.083 344.25 353.799 337.207 369.75 319.25C369.75 319.25 379.339 325.161 385.25 329.25C391.328 333.455 400.25 340.407 400.25 340.407C377.39 364.987 344.1 383.007 324.25 381.25C292.25 381.246 273.25 364.289 244.75 341.25C216.25 318.211 200.25 305.75 179.75 305.75C145.25 305.75 80.25 360.75 80.25 360.75Z" fill="#4E9CFF"/>+<path d="M406.25 213.25C399.745 217.746 389.25 224.25 389.25 224.25C389.25 224.25 395.25 237.25 395.25 254.75C395.25 272.25 389.75 287.25 389.75 287.25C389.75 287.25 399.172 293.135 405.25 297.25C411.564 301.525 421.25 308.75 421.25 308.75C421.25 308.75 432.75 284.75 432.75 254.75C432.75 224.75 421.25 202.25 421.25 202.25C421.25 202.25 412.226 209.12 406.25 213.25Z" fill="#4E9CFF"/>+<path d="M256.25 209.25L285.25 185.25C285.25 185.25 308.587 202.04 325.75 204.583C343.75 207.25 362.954 197.214 380.75 185.25C407.629 167.179 430.25 144.25 430.25 144.25L456.75 170.25C456.75 170.25 383.686 249.411 325.75 242.25C287.75 237.553 256.25 209.25 256.25 209.25Z" fill="#FF5D5F"/>+<path d="M186.255 130.25C223.755 130.25 255.25 162.25 255.25 162.25C255.25 162.25 246.487 169.155 240.75 173.75C234.775 178.536 225.25 186.25 225.25 186.25C225.25 186.25 208.755 168.75 186.255 168.75C177.028 168.75 165.039 174.292 152.255 185.25C142.391 193.705 132.129 204.216 125.255 217.25C119.31 228.52 116.068 241.802 115.755 255.75C115.361 273.269 121.571 291.634 131.755 306.25C138.58 316.046 146.726 323.418 155.255 329.75C166.323 337.968 177.865 343.75 186.255 343.75C195.217 343.75 203.274 340.635 209.255 337.75C218.755 332.25 226.25 325.75 226.25 325.75L255.75 350.25C255.75 350.25 243.75 362.25 227.255 371.25C216.595 376.507 202.895 381.75 186.255 381.75C169.626 381.75 150.315 372.915 132.255 359.25C120.579 350.416 109.135 339.948 100.255 327.25C85.7005 306.438 78.2004 281.118 78.2502 255.75C78.3008 230.065 86.5823 204.625 101.255 183.75C124.255 153.75 158.273 130.25 186.255 130.25Z" fill="#FF5D5F"/>+</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 123da38b482d..43746c7b546e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -241,6 +241,7 @@ the row lists both.| kernel | HTTP | requests | ✅ || klaviyo | HTTP | requests | ✅ || lago | HTTP | requests | ✅ |+| langfuse | HTTP | requests | ✅ || launchdarkly | HTTP | requests | ✅ || kustomer | HTTP | requests | ✅ || lattice | HTTP | requests | ✅ |@@ -640,7 +641,6 @@ doesn't conflict with concurrent PRs.- koyeb- kyve- lambda_labs-- langfuse- langsmith- leexi- lemon_squeezydiff --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 ea113d92df07..348ff2cdf072 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@@ -2050,7 +2050,9 @@ class LangSmithSourceConfig(config.Config):@config.configclass LangfuseSourceConfig(config.Config):- pass+ public_key: str+ secret_key: str+ host: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/canonical_descriptions.pynew file mode 100644index 000000000000..fbd34fd3dd43--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/canonical_descriptions.py@@ -0,0 +1,164 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "traces": {+ "description": "Top-level executions of your LLM application. A trace groups the observations, scores, and metadata for one end-to-end interaction.",+ "docs_url": "https://api.reference.langfuse.com/#tag/trace/get/api/public/traces",+ "columns": {+ "id": "The unique identifier of a trace.",+ "timestamp": "The timestamp when the trace was created.",+ "name": "The name of the trace.",+ "input": "The input data of the trace. Can be any JSON.",+ "output": "The output data of the trace. Can be any JSON.",+ "sessionId": "The session identifier associated with the trace.",+ "release": "The release version of the application when the trace was created.",+ "version": "The version of the trace.",+ "userId": "The user identifier associated with the trace.",+ "metadata": "The metadata associated with the trace. Can be any JSON.",+ "tags": "The tags associated with the trace.",+ "public": "Whether the trace is accessible via URL without login.",+ "environment": "The environment from which this trace originated.",+ "htmlPath": "Path of the trace in the Langfuse UI.",+ "latency": "Latency of the trace in seconds.",+ "totalCost": "Cost of the trace in USD.",+ "observations": "List of observation IDs belonging to the trace.",+ "scores": "List of score IDs attached to the trace.",+ },+ },+ "observations": {+ "description": "Individual units of work within a trace: LLM generations, spans, tool calls, and events, with token usage, cost, and latency detail.",+ "docs_url": "https://api.reference.langfuse.com/#tag/observations/get/api/public/v2/observations",+ "columns": {+ "id": "The unique identifier of the observation.",+ "traceId": "The trace ID associated with the observation.",+ "startTime": "The start time of the observation.",+ "endTime": "The end time of the observation.",+ "projectId": "The project ID this observation belongs to.",+ "parentObservationId": "The parent observation ID.",+ "type": "The type of the observation (e.g. GENERATION, SPAN, EVENT).",+ "name": "The name of the observation.",+ "level": "The log level of the observation (DEBUG, DEFAULT, WARNING, ERROR).",+ "statusMessage": "The status message of the observation.",+ "version": "The version of the observation.",+ "environment": "The environment from which this observation originated.",+ "userId": "The user ID associated with the observation.",+ "sessionId": "The session ID associated with the observation.",+ "completionStartTime": "The completion start time of the observation.",+ "createdAt": "The creation timestamp of the observation.",+ "updatedAt": "The last update timestamp of the observation.",+ "input": "The input data of the observation.",+ "output": "The output data of the observation.",+ "metadata": "Additional metadata of the observation.",+ "providedModelName": "The model name as provided by the user.",+ "internalModelId": "The internal model ID matched by Langfuse.",+ "modelParameters": "The parameters of the model used for the observation.",+ "usageDetails": "Usage details keyed by usage metric name, with the number of units consumed.",+ "costDetails": "Cost details keyed by cost metric name, with the cost in USD.",+ "totalCost": "The total cost of the observation in USD.",+ "promptId": "The prompt ID associated with the observation.",+ "promptName": "The prompt name associated with the observation.",+ "promptVersion": "The prompt version associated with the observation.",+ "latency": "The latency in seconds.",+ "timeToFirstToken": "The time to first token in seconds.",+ "traceName": "The name of the parent trace.",+ "tags": "Tags from the parent trace (denormalized onto the observation).",+ "release": "The release version of the parent trace.",+ },+ },+ "scores": {+ "description": "Evaluation scores attached to traces, observations, sessions, or experiments. The value type depends on dataType (numeric, boolean, categorical, text, or correction).",+ "docs_url": "https://api.reference.langfuse.com/#tag/scoresv3/get/api/public/v3/scores",+ "columns": {+ "id": "The unique identifier of the score.",+ "projectId": "The project ID this score belongs to.",+ "name": "The name of the score.",+ "value": "The score value. Its type depends on dataType: number for NUMERIC, boolean for BOOLEAN, string otherwise.",+ "dataType": "The data type of the score (NUMERIC, BOOLEAN, CATEGORICAL, TEXT, CORRECTION).",+ "source": "The source of the score (e.g. API, ANNOTATION, EVAL).",+ "timestamp": "The timestamp of the score.",+ "environment": "The environment from which this score originated.",+ "createdAt": "The creation timestamp of the score.",+ "updatedAt": "The last update timestamp of the score.",+ "comment": "Optional comment attached to the score.",+ "configId": "The score config ID, if this score was created from a config.",+ "metadata": "Arbitrary metadata attached to the score.",+ "authorUserId": "The user who created this score, if available.",+ "queueId": "The annotation queue this score belongs to, if any.",+ "subject": "The entity this score is attached to (trace, observation, session, or experiment).",+ },+ },+ "sessions": {+ "description": "Sessions group related traces, e.g. a conversation or thread of interactions.",+ "docs_url": "https://api.reference.langfuse.com/#tag/sessions/get/api/public/sessions",+ "columns": {+ "id": "The unique identifier of the session.",+ "createdAt": "The timestamp when the session was created.",+ "projectId": "The project ID this session belongs to.",+ "environment": "The environment from which this session originated.",+ },+ },+ "prompts": {+ "description": "Prompts managed in Langfuse prompt management, one row per prompt name with its versions and labels.",+ "docs_url": "https://api.reference.langfuse.com/#tag/prompts/get/api/public/v2/prompts",+ "columns": {+ "name": "The name of the prompt.",+ "type": "Whether the prompt is a text or chat prompt.",+ "versions": "The list of version numbers that exist for the prompt.",+ "labels": "The labels assigned across the prompt's versions.",+ "tags": "The tags associated with the prompt.",+ "lastUpdatedAt": "The timestamp when the prompt was last created or updated.",+ "lastConfig": "Config object of the most recent prompt version.",+ },+ },+ "datasets": {+ "description": "Datasets of test inputs and expected outputs used for experiments and evaluation.",+ "docs_url": "https://api.reference.langfuse.com/#tag/datasets/get/api/public/v2/datasets",+ "columns": {+ "id": "The unique identifier of the dataset.",+ "name": "The name of the dataset.",+ "description": "Description of the dataset.",+ "metadata": "Metadata associated with the dataset.",+ "inputSchema": "JSON Schema for validating dataset item inputs.",+ "expectedOutputSchema": "JSON Schema for validating dataset item expected outputs.",+ "projectId": "The project ID this dataset belongs to.",+ "createdAt": "The timestamp when the dataset was created.",+ "updatedAt": "The timestamp when the dataset was last updated.",+ },+ },+ "dataset_items": {+ "description": "Individual items within datasets: an input, an optional expected output, and links back to the trace or observation that sourced them.",+ "docs_url": "https://api.reference.langfuse.com/#tag/datasetitems/get/api/public/dataset-items",+ "columns": {+ "id": "The unique identifier of the dataset item.",+ "status": "The status of the dataset item (ACTIVE or ARCHIVED).",+ "input": "Input data for the dataset item.",+ "expectedOutput": "Expected output for the dataset item.",+ "metadata": "Metadata associated with the dataset item.",+ "sourceTraceId": "The trace ID that sourced this dataset item.",+ "sourceObservationId": "The observation ID that sourced this dataset item.",+ "datasetId": "The dataset this item belongs to.",+ "datasetName": "The name of the dataset this item belongs to.",+ "createdAt": "The timestamp when the dataset item was created.",+ "updatedAt": "The timestamp when the dataset item was last updated.",+ },+ },+ "models": {+ "description": "Model definitions used for matching generations to models and computing token usage and USD cost.",+ "docs_url": "https://api.reference.langfuse.com/#tag/models/get/api/public/models",+ "columns": {+ "id": "The unique identifier of the model definition.",+ "modelName": "Name of the model definition.",+ "matchPattern": "Regex pattern which matches this model definition to generation.model.",+ "startDate": "Apply only to generations which are newer than this ISO date.",+ "unit": "Unit used by this model (e.g. TOKENS).",+ "inputPrice": "Price (USD) per input unit (deprecated in favor of prices).",+ "outputPrice": "Price (USD) per output unit (deprecated in favor of prices).",+ "totalPrice": "Price (USD) per total unit (deprecated in favor of prices).",+ "tokenizerId": "Tokenizer applied to observations which match this model.",+ "tokenizerConfig": "Configuration for the selected tokenizer.",+ "isLangfuseManaged": "Whether the model definition is managed by Langfuse or user-defined.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.pynew file mode 100644index 000000000000..92f2f70681ab--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py@@ -0,0 +1,438 @@+import re+import json+import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++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.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.settings import (+ LANGFUSE_ENDPOINTS,+ LangfuseEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 6+# Langfuse rate limits are per-minute windows (as low as 15 req/min for legacy read endpoints on+# the Hobby plan), so honor Retry-After up to a full window plus slack.+MAX_RETRY_AFTER_SECONDS = 120++# The host is customer-controlled (self-hosted Langfuse), so bound how much a single page fetch can+# cost a shared worker. The per-read `timeout` only limits the gap between bytes — a hostile host can+# return an unbounded body (OOM) or drip bytes just under that gap to occupy a worker for days. These+# cap the decoded body size and the total transfer wall-clock before the JSON is parsed. A legitimate+# page (at most `page_size` rows) is far smaller and far faster, so both limits are generous.+MAX_RESPONSE_BYTES = 512 * 1024 * 1024+MAX_TRANSFER_SECONDS = 600+RESPONSE_CHUNK_BYTES = 1024 * 1024++# Pagination is server-driven (totalPages / an opaque cursor), so a hostile host could keep the+# loop alive until the activity timeout by always reporting more pages. Cap the pages fetched per+# run: hitting the cap raises a RETRYABLE error on purpose — the resume checkpoint was saved after+# the last yielded page, so a legitimately huge sync continues from where it stopped on the next+# activity attempt, while a hostile host is bounded per attempt. At the default page sizes this cap+# allows 2.5M rows per run on page endpoints and 50M observations, far above a normal sync.+MAX_PAGES_PER_RUN = 50_000++DEFAULT_HOST = "https://cloud.langfuse.com"+HOST_NOT_ALLOWED_ERROR = "Langfuse host is not allowed"+HTTP_NOT_ALLOWED_ERROR = "Langfuse host must use HTTPS"+RESPONSE_LIMIT_ERROR = "Langfuse response exceeded a transfer limit"+PAGE_LIMIT_ERROR = "Langfuse pagination page limit reached"+REPEATED_CURSOR_ERROR = "Langfuse API returned the same pagination cursor twice"+++class LangfuseRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++class LangfuseHostNotAllowedError(Exception):+ pass+++class LangfuseResponseTooLargeError(Exception):+ """A page response blew past the byte or wall-clock cap — treated as non-retryable (a hostile or+ misbehaving host won't return a smaller/faster body on retry)."""++ pass+++class LangfusePaginationError(Exception):+ """Pagination metadata tried to extend the run beyond its bounds.++ Raised with PAGE_LIMIT_ERROR (retryable — the resume checkpoint lets the next attempt continue)+ or REPEATED_CURSOR_ERROR (non-retryable — a compliant server never repeats a cursor, so a retry+ would loop on the same response)."""++ pass+++class LangfuseResumeConfig:+ # Next page number ("page" endpoints) or opaque cursor ("cursor" endpoints) to fetch.+ page: int | None = None+ cursor: str | None = None+ # The from-filter value the interrupted run started with. Reused verbatim on resume so the+ # saved page/cursor stays aligned with the query it was produced by (the incremental watermark+ # can advance mid-run for ascending endpoints).+ from_value: str | None = None+++def normalize_host(host: str | None) -> str:+ """Turn whatever the user typed into a bare Langfuse base URL.++ Accepts ``us.cloud.langfuse.com``, ``https://cloud.langfuse.com/``, or a self-hosted URL and+ returns it scheme-prefixed with no trailing slash. Defaults to https when no scheme is given.+ """+ host = (host or "").strip()+ if not host:+ return DEFAULT_HOST+ if not re.match(r"^https?://", host, flags=re.IGNORECASE):+ host = f"https://{host}"+ return host.rstrip("/")+++def _host_only(host: str | None) -> str:+ return (urlparse(normalize_host(host)).hostname or "").lower()+++def _is_https(host: str | None) -> bool:+ # The secret key rides in the Authorization header (Basic auth), so refuse plaintext HTTP to+ # keep an on-path attacker from capturing it.+ return urlparse(normalize_host(host)).scheme == "https"+++def _check_host(host: str | None, team_id: int) -> None:+ """Refuse plaintext or internal hosts before any credential-bearing request goes out.++ Raises LangfuseHostNotAllowedError with a message get_non_retryable_errors() matches, so the+ workflow fails fast instead of retrying an SSRF/host failure.+ """+ if not _is_https(host):+ raise LangfuseHostNotAllowedError(HTTP_NOT_ALLOWED_ERROR)++ # The host is customer-controlled (self-hosted Langfuse), so block hosts that resolve to+ # private/internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.+ host_ok, host_err = _is_host_safe(_host_only(host), team_id)+ if not host_ok:+ raise LangfuseHostNotAllowedError(+ f"{HOST_NOT_ALLOWED_ERROR}: {host_err}" if host_err else HOST_NOT_ALLOWED_ERROR+ )+++def _format_incremental_value(value: Any) -> str:+ """Langfuse timestamp filters want ISO 8601; we normalize to UTC with a literal Z."""+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def _from_filter_value(+ config: LangfuseEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> str | None:+ """The formatted lower-bound filter value for this run, or None for a full / first sync."""+ if not (should_use_incremental_field and db_incremental_field_last_value and config.incremental_filter_param):+ return None++ field = incremental_field or config.default_incremental_field+ if field != config.default_incremental_field:+ raise ValueError(+ f"Unsupported Langfuse incremental field '{field}' for endpoint '{config.name}'. "+ f"Expected '{config.default_incremental_field}'."+ )++ value = db_incremental_field_last_value+ if config.incremental_lookback is not None and isinstance(value, datetime):+ value = value - config.incremental_lookback+ elif config.incremental_lookback is not None and isinstance(value, date):+ value = datetime.combine(value, datetime.min.time(), tzinfo=UTC) - config.incremental_lookback++ return _format_incremental_value(value)+++def _build_params(config: LangfuseEndpointConfig, from_value: str | None) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": config.page_size}+ if from_value is not None and config.incremental_filter_param:+ params[config.incremental_filter_param] = from_value+ params.update(config.extra_params)+ return params+++def _parse_retry_after(response: requests.Response) -> float | None:+ """Honor ``Retry-After`` in whole seconds on 429. Ignore HTTP-date forms."""+ raw = response.headers.get("Retry-After")+ if raw and raw.strip().isdigit():+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)+ return None+++def _read_capped_body(response: requests.Response, endpoint: str) -> bytes:+ """Stream the response body under a byte cap and a wall-clock deadline, then return the raw bytes.++ Called only when the caller opened the request with ``stream=True`` so the body isn't buffered+ until here. ``iter_content`` decodes any content-encoding, so ``total`` and the cap track the+ decoded size that actually lands in memory. Raises :class:`LangfuseResponseTooLargeError` (which+ is non-retryable) before the JSON is decoded rather than letting a hostile host OOM or occupy the+ worker.+ """+ started = time.monotonic()+ total = 0+ chunks: list[bytes] = []+ for chunk in response.iter_content(chunk_size=RESPONSE_CHUNK_BYTES):+ if not chunk:+ continue+ total += len(chunk)+ if total > MAX_RESPONSE_BYTES:+ raise LangfuseResponseTooLargeError(+ f"{RESPONSE_LIMIT_ERROR}: {endpoint} returned more than {MAX_RESPONSE_BYTES} bytes"+ )+ if time.monotonic() - started > MAX_TRANSFER_SECONDS:+ raise LangfuseResponseTooLargeError(+ f"{RESPONSE_LIMIT_ERROR}: {endpoint} transfer exceeded {MAX_TRANSFER_SECONDS}s"+ )+ chunks.append(chunk)+ return b"".join(chunks)+++def _retry_wait(retry_state: RetryCallState) -> float:+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, LangfuseRetryableError) and exc.retry_after is not None:+ return exc.retry_after+ return wait_exponential_jitter(initial=2, max=60)(retry_state)+++def validate_credentials(+ host: str | None, public_key: str, secret_key: str, team_id: Optional[int] = None+) -> tuple[bool, str | None]:+ """Probe the project endpoint to confirm the key pair is genuine for the configured host."""+ if not public_key or not public_key.strip():+ return False, "Missing public key"+ if not secret_key or not secret_key.strip():+ return False, "Missing secret key"++ if not _host_only(host):+ return False, "Invalid Langfuse host"++ if not _is_https(host):+ return False, HTTP_NOT_ALLOWED_ERROR++ if team_id is not None:+ host_ok, host_err = _is_host_safe(_host_only(host), team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ url = f"{normalize_host(host)}/api/public/projects"+ try:+ # Don't follow redirects: the validated host could 3xx to an internal address (SSRF).+ # `retry=Retry(total=0)` disables adapter-level retries, whose Retry-After handling is+ # uncapped — a hostile host could park the worker with a huge Retry-After on a 429.+ response = make_tracked_session(retry=Retry(total=0)).get(+ url, auth=(public_key.strip(), secret_key.strip()), timeout=10, allow_redirects=False+ )+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.is_redirect or response.is_permanent_redirect:+ return False, (+ "The Langfuse host returned an unexpected redirect. Enter just the API base URL for your "+ "region (for example https://cloud.langfuse.com or https://us.cloud.langfuse.com) or your "+ "self-hosted instance, with no extra path."+ )++ if response.status_code == 200:+ return True, None++ if response.status_code in (401, 403):+ return False, (+ "Invalid Langfuse API keys. Check the project public key and secret key, and make sure the "+ "host matches your Langfuse data region."+ )++ try:+ body = response.json()+ return False, body.get("message", response.text)+ except Exception:+ return False, response.text+++def get_rows(+ host: str | None,+ public_key: str,+ secret_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LangfuseResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = LANGFUSE_ENDPOINTS[endpoint]++ # Re-check at run time (not just at source-create) in case the host was edited or now+ # resolves to an internal address (SSRF / DNS rebinding).+ _check_host(host, team_id)++ from_value = _from_filter_value(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )++ page: int = 1+ cursor: str | None = None+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None:+ # Reuse the interrupted run's from-filter so the saved page/cursor matches its query.+ from_value = resume_config.from_value+ page = resume_config.page or 1+ cursor = resume_config.cursor+ logger.debug(f"Langfuse: resuming {endpoint} from page={page}, cursor={cursor}")++ base_params = _build_params(config, from_value)+ url = f"{normalize_host(host)}{config.path}"+ auth = (public_key.strip(), secret_key.strip())+ # One session reused across every page so urllib3 keeps the connection alive instead of+ # re-handshaking per request. `retry=Retry(total=0)` disables adapter-level retries, whose+ # Retry-After handling is uncapped — a hostile host could park the worker with a huge+ # Retry-After on a 429. The tenacity policy on fetch_page (which caps Retry-After at+ # MAX_RETRY_AFTER_SECONDS) is the only retry layer.+ session = make_tracked_session(retry=Retry(total=0))++ @retry(+ retry=retry_if_exception_type((LangfuseRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+ )+ def fetch_page(params: dict[str, Any]) -> dict[str, Any]:+ # stream=True so the (customer-controlled) body isn't buffered until we read it under a cap.+ # Don't follow redirects: an attacker-controlled host could 3xx to an internal address (SSRF).+ response = session.get(+ url, params=params, auth=auth, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False, stream=True+ )++ if response.status_code == 429 or response.status_code >= 500:+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None+ raise LangfuseRetryableError(+ f"Langfuse API error (retryable): status={response.status_code}, endpoint={endpoint}",+ retry_after=retry_after,+ )++ if response.is_redirect or response.is_permanent_redirect:+ raise LangfuseHostNotAllowedError(+ f"{HOST_NOT_ALLOWED_ERROR}: Langfuse API returned an unexpected redirect "+ f"(status={response.status_code}); refusing to follow it"+ )++ body = _read_capped_body(response, endpoint)++ if not response.ok:+ logger.error(f"Langfuse API error: status={response.status_code}, body={body[:2048]!r}, url={url}")+ response.raise_for_status()++ return json.loads(body)++ pages_fetched = 0+ while True:+ params = dict(base_params)+ if config.pagination == "page":+ params["page"] = page+ elif cursor is not None:+ params["cursor"] = cursor++ data = fetch_page(params)+ pages_fetched += 1+ items = data.get("data") or []+ meta = data.get("meta") or {}++ if config.pagination == "page":+ # totalPages is documented as always present; stop rather than loop if it ever isn't.+ total_pages = meta.get("totalPages")+ has_next = bool(items) and total_pages is not None and page < total_pages+ next_state = LangfuseResumeConfig(page=page + 1, from_value=from_value)+ else:+ next_cursor = meta.get("cursor")+ # A compliant server never hands back the cursor it was just given; looping on it would+ # re-fetch the same page until the activity timeout. Raise (non-retryable) before+ # yielding or saving state so the poisoned cursor is never checkpointed.+ if next_cursor is not None and next_cursor == cursor:+ raise LangfusePaginationError(f"{REPEATED_CURSOR_ERROR} (endpoint {endpoint})")+ has_next = bool(items) and next_cursor is not None+ next_state = LangfuseResumeConfig(cursor=next_cursor, from_value=from_value)++ if items:+ yield items+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last+ # page rather than skipping it — merge dedupes on the primary key.+ if has_next:+ resumable_source_manager.save_state(next_state)++ if not has_next:+ break++ # The checkpoint above already points at the next page, so raising here (retryable) lets a+ # legitimately huge sync continue on the next activity attempt while bounding what a hostile+ # host's pagination metadata can extract from a single run.+ if pages_fetched >= MAX_PAGES_PER_RUN:+ logger.warning(f"Langfuse: page limit reached for {endpoint} after {pages_fetched} pages")+ raise LangfusePaginationError(f"{PAGE_LIMIT_ERROR}: {pages_fetched} pages fetched from {endpoint}")++ if config.pagination == "page":+ page += 1+ else:+ cursor = meta.get("cursor")+++def langfuse_source(+ host: str | None,+ public_key: str,+ secret_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LangfuseResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = LANGFUSE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ host=host,+ public_key=public_key,+ secret_key=secret_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ team_id=team_id,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=endpoint_config.primary_keys,+ sort_mode=endpoint_config.sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/settings.pynew file mode 100644index 000000000000..05e6b424ab1b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/settings.py@@ -0,0 +1,149 @@+from dataclasses import dataclass, field+from datetime import timedelta+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass+class LangfuseEndpointConfig:+ name: str+ path: str+ # "page" endpoints use ?page=N with a meta.totalPages envelope; "cursor" endpoints+ # (v2 observations, v3 scores) return an opaque meta.cursor for the next page.+ pagination: Literal["page", "cursor"]+ page_size: int+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None+ # Server-side lower-bound query param for the incremental field (e.g. fromTimestamp).+ incremental_filter_param: Optional[str] = None+ # Extra query params sent on every request (orderBy, fields selection, ...).+ extra_params: dict[str, str] = field(default_factory=dict)+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ partition_key: Optional[str] = None+ # The order rows are emitted in. Only traces accepts an explicit orderBy, which we pin+ # ascending; the other list endpoints return newest-first, so they are "desc".+ sort_mode: Literal["asc", "desc"] = "desc"+ # Safety overlap subtracted from the incremental watermark each run. Langfuse's time filters+ # are on event/creation time, so rows that arrive late (ingestion lag) would otherwise be+ # skipped forever. Re-pulled rows are deduped on the primary key by merge.+ incremental_lookback: Optional[timedelta] = None+++_DEFAULT_LOOKBACK = timedelta(hours=1)++# Observation field groups: everything the v2 endpoint can return. Without this the API only+# returns the `core` and `basic` groups (no io/usage/cost columns).+_OBSERVATION_FIELDS = "core,basic,time,io,metadata,model,usage,prompt,metrics,trace_context"++# Score field groups added on top of the always-returned core fields.+_SCORE_FIELDS = "details,subject,annotation"++# Endpoints cover the resources a user most commonly wants to analyze from an LLM observability+# platform: traces, observations, scores, sessions, prompts, datasets, and model pricing.+# Incremental support is only declared where the API documents a server-side timestamp filter.+LANGFUSE_ENDPOINTS: dict[str, LangfuseEndpointConfig] = {+ "traces": LangfuseEndpointConfig(+ name="traces",+ path="/api/public/traces",+ pagination="page",+ page_size=50,+ incremental_fields=[_datetime_incremental_field("timestamp")],+ default_incremental_field="timestamp",+ incremental_filter_param="fromTimestamp",+ # Pin a stable ascending order so pages don't shift as new traces arrive mid-sync,+ # and so the pipeline's incremental watermark advances safely per batch.+ extra_params={"orderBy": "timestamp.asc"},+ partition_key="timestamp",+ sort_mode="asc",+ incremental_lookback=_DEFAULT_LOOKBACK,+ ),+ "observations": LangfuseEndpointConfig(+ name="observations",+ path="/api/public/v2/observations",+ pagination="cursor",+ page_size=1000, # documented maximum for the v2 bulk endpoint+ incremental_fields=[_datetime_incremental_field("startTime")],+ default_incremental_field="startTime",+ incremental_filter_param="fromStartTime",+ extra_params={"fields": _OBSERVATION_FIELDS},+ partition_key="startTime",+ # v2 observations return newest-first (startTime descending) and accept no orderBy.+ sort_mode="desc",+ incremental_lookback=_DEFAULT_LOOKBACK,+ ),+ "scores": LangfuseEndpointConfig(+ name="scores",+ path="/api/public/v3/scores",+ pagination="cursor",+ page_size=100, # documented maximum for the v3 scores endpoint+ incremental_fields=[_datetime_incremental_field("timestamp")],+ default_incremental_field="timestamp",+ incremental_filter_param="fromTimestamp",+ extra_params={"fields": _SCORE_FIELDS},+ partition_key="timestamp",+ sort_mode="desc",+ incremental_lookback=_DEFAULT_LOOKBACK,+ ),+ "sessions": LangfuseEndpointConfig(+ name="sessions",+ path="/api/public/sessions",+ pagination="page",+ page_size=50,+ incremental_fields=[_datetime_incremental_field("createdAt")],+ default_incremental_field="createdAt",+ incremental_filter_param="fromTimestamp",+ partition_key="createdAt",+ sort_mode="desc",+ incremental_lookback=_DEFAULT_LOOKBACK,+ ),+ "prompts": LangfuseEndpointConfig(+ name="prompts",+ path="/api/public/v2/prompts",+ pagination="page",+ page_size=50,+ incremental_fields=[_datetime_incremental_field("lastUpdatedAt")],+ default_incremental_field="lastUpdatedAt",+ incremental_filter_param="fromUpdatedAt",+ # One row per prompt name (with a versions array); no stable creation field to partition on.+ primary_keys=["name"],+ sort_mode="desc",+ ),+ "datasets": LangfuseEndpointConfig(+ name="datasets",+ path="/api/public/v2/datasets",+ pagination="page",+ page_size=50,+ # No server-side timestamp filter -> full refresh only.+ ),+ "dataset_items": LangfuseEndpointConfig(+ name="dataset_items",+ path="/api/public/dataset-items",+ pagination="page",+ page_size=50,+ # Only filterable by datasetName/version, not by time -> full refresh only.+ partition_key="createdAt",+ ),+ "models": LangfuseEndpointConfig(+ name="models",+ path="/api/public/models",+ pagination="page",+ page_size=50,+ # No server-side timestamp filter -> full refresh only.+ ),+}++ENDPOINTS = tuple(LANGFUSE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in LANGFUSE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/source.pyindex bb322b07f1de..7f2ed339f47a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/source.py@@ -1,19 +1,46 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.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 LangfuseSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.langfuse import (+ HOST_NOT_ALLOWED_ERROR,+ HTTP_NOT_ALLOWED_ERROR,+ REPEATED_CURSOR_ERROR,+ RESPONSE_LIMIT_ERROR,+ LangfuseResumeConfig,+ langfuse_source,+ validate_credentials as validate_langfuse_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class LangfuseSource(SimpleSource[LangfuseSourceConfig]):+class LangfuseSource(ResumableSource[LangfuseSourceConfig, LangfuseResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LANGFUSE@@ -24,8 +51,110 @@ class LangfuseSource(SimpleSource[LangfuseSourceConfig]):name=SchemaExternalDataSourceType.LANGFUSE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Langfuse",- iconPath="/static/services/langfuse.png",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Sync traces, observations, scores, sessions, prompts, and datasets from your Langfuse project.++Find your project API keys in your Langfuse **Project settings > API Keys**. Set the host to match your data region (`https://cloud.langfuse.com` for EU, `https://us.cloud.langfuse.com` for US) or your self-hosted instance URL.""",+ iconPath="/static/services/langfuse.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/langfuse",keywords=["llm", "observability", "traces", "prompts"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="host",+ label="Host",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://cloud.langfuse.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="public_key",+ label="Public key",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="pk-lf-...",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="secret_key",+ label="Secret key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="sk-lf-...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Langfuse API keys. Check the project public key and secret key, and make sure the host matches your Langfuse data region.",+ "403 Client Error": "Your Langfuse API keys do not have access to this resource. Check the keys and try again.",+ HOST_NOT_ALLOWED_ERROR: "The Langfuse host is not allowed. Please use a publicly reachable instance URL.",+ HTTP_NOT_ALLOWED_ERROR: "The Langfuse host must use HTTPS. Please update the host to use https://.",+ RESPONSE_LIMIT_ERROR: "The Langfuse host returned a response that was too large or too slow to download. Check that the host points at a real Langfuse instance.",+ # PAGE_LIMIT_ERROR is intentionally absent: it is retryable, so a huge sync resumes+ # from its checkpoint on the next attempt instead of failing permanently.+ REPEATED_CURSOR_ERROR: "The Langfuse host repeated a pagination cursor, so the sync was stopped to avoid looping. Check that the host points at a real Langfuse instance.",+ }++ def get_schemas(+ self,+ config: LangfuseSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in ENDPOINTS+ ]+ 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: LangfuseSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_langfuse_credentials(config.host, config.public_key, config.secret_key, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LangfuseResumeConfig]:+ return ResumableSourceManager[LangfuseResumeConfig](inputs, LangfuseResumeConfig)++ def source_for_pipeline(+ self,+ config: LangfuseSourceConfig,+ resumable_source_manager: ResumableSourceManager[LangfuseResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return langfuse_source(+ host=config.host,+ public_key=config.public_key,+ secret_key=config.secret_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ team_id=inputs.team_id,+ 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/langfuse/tests/test_langfuse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse.pynew file mode 100644index 000000000000..2e2097ece75c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse.py@@ -0,0 +1,509 @@+import json+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse import langfuse as langfuse_module+from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.langfuse import (+ HOST_NOT_ALLOWED_ERROR,+ HTTP_NOT_ALLOWED_ERROR,+ LangfuseResumeConfig,+ LangfuseRetryableError,+ _from_filter_value,+ _parse_retry_after,+ _retry_wait,+ get_rows,+ langfuse_source,+ normalize_host,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.settings import LANGFUSE_ENDPOINTS+++def _response(+ *,+ status_code: int = 200,+ json_data: Any = None,+ text: str = "",+ headers: Any = None,+ body_chunks: Optional[list[bytes]] = None,+) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 400+ response.is_redirect = status_code in (302, 303, 307)+ response.is_permanent_redirect = status_code in (301, 308)+ response.text = text+ response.json.return_value = json_data+ response.headers = headers or {}+ # get_rows streams the body (stream=True) and JSON-decodes the bytes, so the body must flow+ # through iter_content rather than response.json(). body_chunks lets a test drip the body in+ # pieces (e.g. to exceed the size cap).+ if body_chunks is None:+ payload = json.dumps(json_data).encode() if json_data is not None else text.encode()+ body_chunks = [payload] if payload else []+ response.iter_content.return_value = body_chunks+ return response+++def _page(items: list[dict[str, Any]], *, page: int, total_pages: int) -> mock.MagicMock:+ return _response(json_data={"data": items, "meta": {"page": page, "limit": 50, "totalPages": total_pages}})+++def _cursor_page(items: list[dict[str, Any]], *, cursor: Optional[str]) -> mock.MagicMock:+ return _response(json_data={"data": items, "meta": {"cursor": cursor}})+++class TestNormalizeHost:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ (None, "https://cloud.langfuse.com"),+ ("", "https://cloud.langfuse.com"),+ ("us.cloud.langfuse.com", "https://us.cloud.langfuse.com"),+ ("https://cloud.langfuse.com/", "https://cloud.langfuse.com"),+ (" langfuse.example.com ", "https://langfuse.example.com"),+ ("http://langfuse.example.com:3000/", "http://langfuse.example.com:3000"),+ ],+ )+ def test_normalize_host(self, raw, expected):+ assert normalize_host(raw) == expected+++class TestFromFilterValue:+ def test_applies_lookback_and_formats_iso_z(self):+ # Traces declare a 1h lookback: a watermark of 12:00 must re-pull from 11:00 so+ # late-arriving rows (ingestion lag) aren't skipped forever.+ value = _from_filter_value(+ LANGFUSE_ENDPOINTS["traces"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 12, 0, 0, tzinfo=UTC),+ incremental_field="timestamp",+ )+ assert value == "2026-03-04T11:00:00Z"++ def test_date_value_is_supported(self):+ value = _from_filter_value(+ LANGFUSE_ENDPOINTS["traces"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 3, 4),+ incremental_field="timestamp",+ )+ assert value == "2026-03-03T23:00:00Z"++ @pytest.mark.parametrize(+ "should_use, last_value",+ [+ (False, datetime(2026, 3, 4, tzinfo=UTC)),+ (True, None),+ ],+ )+ def test_full_or_first_sync_has_no_filter(self, should_use, last_value):+ value = _from_filter_value(+ LANGFUSE_ENDPOINTS["traces"],+ should_use_incremental_field=should_use,+ db_incremental_field_last_value=last_value,+ incremental_field="timestamp",+ )+ assert value is None++ def test_unsupported_incremental_field_raises(self):+ with pytest.raises(ValueError):+ _from_filter_value(+ LANGFUSE_ENDPOINTS["traces"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ incremental_field="updatedAt",+ )++ def test_full_refresh_endpoint_never_filters(self):+ value = _from_filter_value(+ LANGFUSE_ENDPOINTS["datasets"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ incremental_field=None,+ )+ assert value is None+++class TestValidateCredentials:+ def _patch_session(self, response=None, raises=None):+ session = mock.MagicMock()+ if raises is not None:+ session.get.side_effect = raises+ else:+ session.get.return_value = response+ return mock.patch.object(langfuse_module, "make_tracked_session", return_value=session)++ @pytest.mark.parametrize(+ "status_code, expected_valid, expected_msg_substr",+ [+ (200, True, None),+ (401, False, "Invalid Langfuse API keys"),+ (403, False, "Invalid Langfuse API keys"),+ ],+ )+ def test_status_code_mapping(self, status_code, expected_valid, expected_msg_substr):+ with self._patch_session(_response(status_code=status_code)):+ valid, msg = validate_credentials("https://cloud.langfuse.com", "pk-lf-x", "sk-lf-x")+ assert valid is expected_valid+ if expected_msg_substr is None:+ assert msg is None+ else:+ assert expected_msg_substr in (msg or "")++ @pytest.mark.parametrize(+ "public_key, secret_key, expected_msg",+ [+ ("", "sk-lf-x", "Missing public key"),+ ("pk-lf-x", " ", "Missing secret key"),+ ],+ )+ def test_missing_keys_short_circuit(self, public_key, secret_key, expected_msg):+ valid, msg = validate_credentials("https://cloud.langfuse.com", public_key, secret_key)+ assert valid is False+ assert msg == expected_msg++ def test_uses_basic_auth_and_no_redirects(self):+ with self._patch_session(_response(status_code=200)) as patched:+ validate_credentials("https://cloud.langfuse.com", " pk-lf-x ", " sk-lf-x ", team_id=None)+ kwargs = patched.return_value.get.call_args.kwargs+ assert kwargs["auth"] == ("pk-lf-x", "sk-lf-x")+ assert kwargs["allow_redirects"] is False+ # Adapter-level retries must stay disabled: urllib3 honors Retry-After uncapped, so a+ # hostile host could park the worker before the bounded tenacity policy runs.+ assert patched.call_args.kwargs["retry"].total == 0++ def test_rejects_redirect_response(self):+ with self._patch_session(_response(status_code=302)):+ valid, msg = validate_credentials("https://cloud.langfuse.com", "pk-lf-x", "sk-lf-x")+ assert valid is False+ assert "unexpected redirect" in (msg or "")++ def test_rejects_plaintext_http(self):+ with self._patch_session(_response(status_code=200)) as patched:+ valid, msg = validate_credentials("http://langfuse.example.com", "pk-lf-x", "sk-lf-x")+ assert valid is False+ assert msg == HTTP_NOT_ALLOWED_ERROR+ patched.return_value.get.assert_not_called()++ def test_blocks_unsafe_host(self):+ with (+ mock.patch.object(langfuse_module, "_is_host_safe", return_value=(False, "internal address")),+ self._patch_session(_response(status_code=200)) as patched,+ ):+ valid, msg = validate_credentials("https://10.0.0.1", "pk-lf-x", "sk-lf-x", team_id=99)+ assert valid is False+ assert msg == "internal address"+ patched.return_value.get.assert_not_called()+++class TestLangfuseSourceResponse:+ @pytest.mark.parametrize(+ "endpoint, primary_keys, partition_key, sort_mode",+ [+ ("traces", ["id"], "timestamp", "asc"),+ ("observations", ["id"], "startTime", "desc"),+ ("scores", ["id"], "timestamp", "desc"),+ ("sessions", ["id"], "createdAt", "desc"),+ ("prompts", ["name"], None, "desc"),+ ("datasets", ["id"], None, "desc"),+ ("dataset_items", ["id"], "createdAt", "desc"),+ ("models", ["id"], None, "desc"),+ ],+ )+ def test_response_shape(self, endpoint, primary_keys, partition_key, sort_mode):+ response = langfuse_source(+ host="https://cloud.langfuse.com",+ public_key="pk-lf-x",+ secret_key="sk-lf-x",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ team_id=1,+ )+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.sort_mode == sort_mode+ if partition_key:+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestGetRows:+ def _run(self, manager, responses, endpoint="traces", **kwargs):+ session = mock.MagicMock()+ session.get.side_effect = responses+ with mock.patch.object(langfuse_module, "make_tracked_session", return_value=session):+ rows: list[dict[str, Any]] = []+ for batch in get_rows(+ host="https://cloud.langfuse.com",+ public_key="pk-lf-x",+ secret_key="sk-lf-x",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ **kwargs,+ ):+ rows.extend(batch)+ return rows, session++ def _manager(self, resume_state: Optional[LangfuseResumeConfig] = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager++ def test_page_pagination_walks_all_pages(self):+ manager = self._manager()+ rows, session = self._run(+ manager,+ [+ _page([{"id": "t1"}, {"id": "t2"}], page=1, total_pages=2),+ _page([{"id": "t3"}], page=2, total_pages=2),+ ],+ )+ assert [r["id"] for r in rows] == ["t1", "t2", "t3"]+ assert session.get.call_args_list[0].kwargs["params"]["page"] == 1+ assert session.get.call_args_list[1].kwargs["params"]["page"] == 2++ def test_page_pagination_saves_next_page_after_yield(self):+ manager = self._manager()+ self._run(+ manager,+ [+ _page([{"id": "t1"}], page=1, total_pages=2),+ _page([{"id": "t2"}], page=2, total_pages=2),+ ],+ )+ # Only the non-final page checkpoints (a crash re-yields the last page; merge dedupes),+ # and it points at the NEXT page to fetch.+ assert manager.save_state.call_count == 1+ saved = manager.save_state.call_args.args[0]+ assert isinstance(saved, LangfuseResumeConfig)+ assert saved.page == 2++ def test_traces_request_pins_ascending_order_and_incremental_filter(self):+ # The pipeline checkpoints the incremental watermark per batch for sort_mode="asc";+ # dropping the orderBy pin or the from-filter would corrupt it.+ manager = self._manager()+ _rows, session = self._run(+ manager,+ [_page([{"id": "t1"}], page=1, total_pages=1)],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 12, 0, 0, tzinfo=UTC),+ incremental_field="timestamp",+ )+ params = session.get.call_args.kwargs["params"]+ assert params["orderBy"] == "timestamp.asc"+ assert params["fromTimestamp"] == "2026-03-04T11:00:00Z"+ assert session.get.call_args.kwargs["auth"] == ("pk-lf-x", "sk-lf-x")+ assert session.get.call_args.kwargs["allow_redirects"] is False++ def test_cursor_pagination_follows_cursor_until_absent(self):+ manager = self._manager()+ rows, session = self._run(+ manager,+ [+ _cursor_page([{"id": "o1"}], cursor="abc"),+ _cursor_page([{"id": "o2"}], cursor=None),+ ],+ endpoint="observations",+ )+ assert [r["id"] for r in rows] == ["o1", "o2"]+ assert "cursor" not in session.get.call_args_list[0].kwargs["params"]+ assert session.get.call_args_list[1].kwargs["params"]["cursor"] == "abc"++ def test_cursor_request_keeps_field_selection_and_filter_on_every_page(self):+ manager = self._manager()+ _rows, session = self._run(+ manager,+ [+ _cursor_page([{"id": "o1"}], cursor="abc"),+ _cursor_page([{"id": "o2"}], cursor=None),+ ],+ endpoint="observations",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 12, 0, 0, tzinfo=UTC),+ incremental_field="startTime",+ )+ for call in session.get.call_args_list:+ assert call.kwargs["params"]["fromStartTime"] == "2026-03-04T11:00:00Z"+ assert "io" in call.kwargs["params"]["fields"]+ assert call.kwargs["params"]["limit"] == 1000++ def test_resume_reuses_saved_page_and_from_value(self):+ # The watermark can advance mid-run; the resumed query must reuse the ORIGINAL+ # from-filter or the saved page number points into a different result set.+ manager = self._manager(LangfuseResumeConfig(page=3, from_value="2026-01-01T00:00:00Z"))+ _rows, session = self._run(+ manager,+ [_page([{"id": "t9"}], page=3, total_pages=3)],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ incremental_field="timestamp",+ )+ params = session.get.call_args.kwargs["params"]+ assert params["page"] == 3+ assert params["fromTimestamp"] == "2026-01-01T00:00:00Z"++ def test_resume_from_saved_cursor(self):+ manager = self._manager(LangfuseResumeConfig(cursor="saved-cursor"))+ rows, session = self._run(+ manager,+ [_cursor_page([{"id": "o9"}], cursor=None)],+ endpoint="observations",+ )+ assert session.get.call_args.kwargs["params"]["cursor"] == "saved-cursor"+ assert [r["id"] for r in rows] == ["o9"]++ def test_empty_page_terminates(self):+ manager = self._manager()+ rows, session = self._run(manager, [_page([], page=1, total_pages=5)])+ assert rows == []+ assert session.get.call_count == 1+ manager.save_state.assert_not_called()++ def test_missing_total_pages_stops_instead_of_looping(self):+ manager = self._manager()+ rows, session = self._run(manager, [_response(json_data={"data": [{"id": "t1"}], "meta": {}})])+ assert [r["id"] for r in rows] == ["t1"]+ assert session.get.call_count == 1++ def test_rejects_plaintext_http_before_request(self):+ manager = self._manager()+ session = mock.MagicMock()+ with (+ mock.patch.object(langfuse_module, "make_tracked_session", return_value=session),+ pytest.raises(langfuse_module.LangfuseHostNotAllowedError) as exc,+ ):+ list(+ get_rows(+ host="http://langfuse.example.com",+ public_key="pk-lf-x",+ secret_key="sk-lf-x",+ endpoint="traces",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ )+ )+ assert HTTP_NOT_ALLOWED_ERROR in str(exc.value)+ session.get.assert_not_called()++ def test_unsafe_host_error_is_marked_non_retryable(self):+ manager = self._manager()+ with (+ mock.patch.object(langfuse_module, "_is_host_safe", return_value=(False, "internal address")),+ pytest.raises(langfuse_module.LangfuseHostNotAllowedError) as exc,+ ):+ self._run(manager, [_page([{"id": "t1"}], page=1, total_pages=1)])+ assert HOST_NOT_ALLOWED_ERROR in str(exc.value)++ def test_redirect_response_is_refused(self):+ manager = self._manager()+ with pytest.raises(langfuse_module.LangfuseHostNotAllowedError) as exc:+ self._run(manager, [_response(status_code=302)])+ assert HOST_NOT_ALLOWED_ERROR in str(exc.value)++ def test_disables_adapter_retries(self):+ # urllib3 honors Retry-After uncapped, so a hostile host could park the worker before the+ # bounded tenacity policy runs. The sync session must opt out of adapter-level retries.+ manager = self._manager()+ session = mock.MagicMock()+ session.get.side_effect = [_page([], page=1, total_pages=1)]+ with mock.patch.object(langfuse_module, "make_tracked_session", return_value=session) as mts:+ list(+ get_rows(+ host="https://cloud.langfuse.com",+ public_key="pk-lf-x",+ secret_key="sk-lf-x",+ endpoint="traces",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ )+ )+ assert mts.call_args.kwargs["retry"].total == 0++ @pytest.mark.parametrize(+ "attr, value, chunks",+ [+ ("MAX_RESPONSE_BYTES", 4, [b"aaaa", b"aaaa"]), # decoded body past the byte cap+ ("MAX_TRANSFER_SECONDS", -1, [b"a"]), # transfer past the wall-clock deadline+ ],+ )+ def test_response_over_limit_raises_non_retryable(self, attr, value, chunks):+ # A hostile/self-hosted host could stream an unbounded or slow-drip body and pin a shared+ # worker. The read must abort past either cap before parsing JSON, with a non-retryable+ # error (retrying can't shrink or speed up the body). A single queued response also proves+ # no retry happens: a retry would consume a second one and raise StopIteration instead.+ manager = self._manager()+ with (+ mock.patch.object(langfuse_module, attr, value),+ pytest.raises(langfuse_module.LangfuseResponseTooLargeError) as exc,+ ):+ self._run(manager, [_response(body_chunks=chunks)])+ assert langfuse_module.RESPONSE_LIMIT_ERROR in str(exc.value)++ def test_repeated_cursor_raises_without_checkpointing_it(self):+ # A hostile host that echoes back the cursor it was given would otherwise re-fetch the same+ # page until the activity timeout. The run must abort (non-retryable) and never checkpoint+ # the poisoned cursor — a saved checkpoint would make every retry loop on it too.+ manager = self._manager()+ with pytest.raises(langfuse_module.LangfusePaginationError) as exc:+ self._run(+ manager,+ [+ _cursor_page([{"id": "o1"}], cursor="loop"),+ _cursor_page([{"id": "o2"}], cursor="loop"),+ ],+ endpoint="observations",+ )+ assert langfuse_module.REPEATED_CURSOR_ERROR in str(exc.value)+ # Only the first page's (legitimate) continuation was saved.+ assert manager.save_state.call_count == 1++ def test_page_limit_raises_after_checkpointing_next_page(self):+ # A hostile host reporting ever-more totalPages would otherwise keep the loop alive until+ # the activity timeout. The run must abort at the cap — retryably, with the next page+ # already checkpointed, so a legitimately huge sync continues on the next attempt.+ manager = self._manager()+ with (+ mock.patch.object(langfuse_module, "MAX_PAGES_PER_RUN", 2),+ pytest.raises(langfuse_module.LangfusePaginationError) as exc,+ ):+ self._run(+ manager,+ [+ _page([{"id": "t1"}], page=1, total_pages=10),+ _page([{"id": "t2"}], page=2, total_pages=10),+ ],+ )+ assert langfuse_module.PAGE_LIMIT_ERROR in str(exc.value)+ assert manager.save_state.call_args.args[0].page == 3+++class TestRetryBehavior:+ @pytest.mark.parametrize(+ "headers, expected",+ [+ ({"Retry-After": "5"}, 5.0),+ ({"Retry-After": "100000"}, 120.0), # capped+ ({"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"}, None), # HTTP-date ignored+ ({}, None),+ ],+ )+ def test_parse_retry_after(self, headers, expected):+ assert _parse_retry_after(_response(headers=headers)) == expected++ def test_retry_wait_prefers_retry_after(self):+ state = mock.MagicMock()+ state.outcome.exception.return_value = LangfuseRetryableError("rate limited", retry_after=7.0)+ assert _retry_wait(state) == 7.0diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse_source.pynew file mode 100644index 000000000000..05b22c4bc8d5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse_source.py@@ -0,0 +1,146 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.langfuse import (+ RESPONSE_LIMIT_ERROR,+ LangfuseResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.source import LangfuseSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestLangfuseSource:+ def setup_method(self):+ self.source = LangfuseSource()+ self.team_id = 123+ self.config = mock.MagicMock()+ self.config.host = "https://cloud.langfuse.com"+ self.config.public_key = "pk-lf-key"+ self.config.secret_key = "sk-lf-key"++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.LANGFUSE++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Langfuse"+ assert config.label == "Langfuse"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/langfuse.svg"++ field_names = [f.name for f in config.fields]+ assert field_names == ["host", "public_key", "secret_key"]++ host_field, public_key_field, secret_key_field = config.fields+ assert isinstance(host_field, SourceFieldInputConfig)+ assert host_field.type == SourceFieldInputConfigType.TEXT+ assert host_field.required is False+ assert host_field.secret is False++ assert isinstance(public_key_field, SourceFieldInputConfig)+ assert public_key_field.required is True+ assert public_key_field.secret is False++ # The secret key must stay a secret password field: the serializer derives which config+ # keys are sensitive from these flags.+ assert isinstance(secret_key_field, SourceFieldInputConfig)+ assert secret_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_key_field.secret is True+ assert secret_key_field.required is True++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error", RESPONSE_LIMIT_ERROR])+ def test_non_retryable_errors(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "endpoint, incremental",+ [+ ("traces", True),+ ("observations", True),+ ("scores", True),+ ("sessions", True),+ ("prompts", True),+ ("datasets", False),+ ("dataset_items", False),+ ("models", False),+ ],+ )+ def test_schema_incremental_support(self, endpoint, incremental):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[endpoint].supports_incremental is incremental+ assert schemas[endpoint].supports_append is incremental++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["traces"])+ assert len(schemas) == 1+ assert schemas[0].name == "traces"++ @pytest.mark.parametrize(+ "mock_return",+ [+ (True, None),+ (False, "Invalid Langfuse API keys"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.source.validate_langfuse_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return):+ mock_validate.return_value = mock_return++ result = self.source.validate_credentials(self.config, self.team_id, schema_name="traces")++ assert result == mock_return+ mock_validate.assert_called_once_with(+ self.config.host, self.config.public_key, self.config.secret_key, self.team_id+ )++ def test_get_resumable_source_manager(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is LangfuseResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.source.langfuse_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_langfuse_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "traces"+ inputs.team_id = 42+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.incremental_field = "timestamp"++ manager = mock.MagicMock()+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_langfuse_source.call_args.kwargs+ assert kwargs["host"] == "https://cloud.langfuse.com"+ assert kwargs["public_key"] == "pk-lf-key"+ assert kwargs["secret_key"] == "sk-lf-key"+ assert kwargs["endpoint"] == "traces"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["team_id"] == 42+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"+ assert kwargs["incremental_field"] == "timestamp"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.source.langfuse_source")+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_langfuse_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "datasets"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "ignored"+ inputs.incremental_field = None++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_langfuse_source.call_args.kwargs["db_incremental_field_last_value"] is None