: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 langsmith import source (#70707)
Tom Owers2766c7a928ce
diff --git a/frontend/public/services/langsmith.svg b/frontend/public/services/langsmith.svgnew file mode 100644index 000000000000..26b5be57ea95--- /dev/null+++ b/frontend/public/services/langsmith.svg@@ -0,0 +1 @@+<svg fill="#1C3C3C" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>LangChain</title><path d="M7.53 15.975a7.53 7.53 0 0 0 2.206-5.325A7.54 7.54 0 0 0 7.53 5.325L2.205 0A7.54 7.54 0 0 0 0 5.325a7.54 7.54 0 0 0 2.205 5.325zm11.144.493a7.54 7.54 0 0 0-5.325-2.206 7.54 7.54 0 0 0-5.325 2.206l5.325 5.325a7.54 7.54 0 0 0 5.325 2.205A7.54 7.54 0 0 0 24 21.793zM2.219 21.78a7.54 7.54 0 0 0 5.325 2.205v-7.53H.014a7.54 7.54 0 0 0 2.205 5.325M20.73 8.595a7.53 7.53 0 0 0-5.327-2.206 7.53 7.53 0 0 0-5.325 2.207l5.325 5.325z"/></svg>\ No newline at end of filediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0fa437cb0d5f..a2f37859ce36 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -309,6 +309,7 @@ the row lists both.| lago | HTTP | requests | ✅ || lambda_labs | HTTP | requests | ✅ || langfuse | HTTP | requests | ✅ |+| langsmith | HTTP | requests | ✅ || launchdarkly | HTTP | requests | ✅ || kustomer | HTTP | requests | ✅ || lattice | HTTP | requests | ✅ |@@ -777,7 +778,6 @@ doesn't conflict with concurrent PRs.- koyeb- kyve- lambda_labs-- langsmith- leexi- lemon_squeezy- leverdiff --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 52721984e1ab..8b8ea6a47200 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@@ -2440,7 +2440,8 @@ class LambdaLabsSourceConfig(config.Config):@config.configclass LangSmithSourceConfig(config.Config):- pass+ api_key: str+ host: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/canonical_descriptions.pynew file mode 100644index 000000000000..528e021d235c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/canonical_descriptions.py@@ -0,0 +1,134 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "runs": {+ "description": (+ "Traces and their nested spans across every tracing project. Each row is one run — an LLM "+ "call, chain, tool call, retriever, or prompt execution — with its inputs, outputs, timing, "+ "token usage, and cost."+ ),+ "docs_url": "https://docs.smith.langchain.com/reference/data_formats/run_data_format",+ "columns": {+ "id": "Unique identifier (UUID) for the run.",+ "name": "Name of the run, e.g. the chain, model, or tool name.",+ "run_type": "Type of the run: llm, chain, tool, retriever, embedding, prompt, or parser.",+ "start_time": "When the run started.",+ "end_time": "When the run ended. Null while the run is still in progress.",+ "status": "Current status of the run, e.g. success or error.",+ "error": "Error message when the run failed.",+ "extra": "Additional metadata attached to the run, including runtime info and user metadata.",+ "inputs": "Input payload of the run, e.g. the prompt or chain inputs.",+ "outputs": "Output payload of the run, e.g. the model completion or chain outputs.",+ "parent_run_id": "Id of the parent run when this run is a nested span; null for root runs.",+ "session_id": "Id of the tracing project (session) the run belongs to.",+ "reference_example_id": "Id of the dataset example this run was evaluated against, if any.",+ "total_tokens": "Total number of tokens used by the run (prompt + completion).",+ "prompt_tokens": "Number of prompt (input) tokens used by the run.",+ "completion_tokens": "Number of completion (output) tokens generated by the run.",+ "total_cost": "Total estimated cost of the run in USD.",+ "prompt_cost": "Estimated cost of the prompt tokens in USD.",+ "completion_cost": "Estimated cost of the completion tokens in USD.",+ "first_token_time": "When the first output token was received (streaming runs).",+ "trace_id": "Id of the trace (root run) this run belongs to.",+ "dotted_order": "Sortable encoding of the run's position within its trace tree.",+ "tags": "Tags attached to the run.",+ "thread_id": "Id of the conversational thread the run belongs to, if any.",+ "feedback_stats": "Aggregated feedback scores attached to the run, keyed by feedback key.",+ },+ },+ "projects": {+ "description": (+ "Tracing projects (called sessions in the LangSmith API), with rolled-up run counts, token "+ "usage, cost, error rate, and latency percentiles."+ ),+ "docs_url": "https://docs.smith.langchain.com/observability/concepts#projects",+ "columns": {+ "id": "Unique identifier (UUID) for the project.",+ "name": "Name of the project.",+ "description": "Description of the project.",+ "start_time": "When the project was created.",+ "last_run_start_time": "Start time of the most recent run in the project.",+ "run_count": "Number of runs in the project.",+ "total_tokens": "Total tokens used across the project's runs.",+ "prompt_tokens": "Total prompt tokens used across the project's runs.",+ "completion_tokens": "Total completion tokens used across the project's runs.",+ "total_cost": "Total estimated cost of the project's runs in USD.",+ "error_rate": "Fraction of the project's runs that errored.",+ "latency_p50": "Median run latency in seconds.",+ "latency_p99": "99th-percentile run latency in seconds.",+ "reference_dataset_id": "Id of the dataset this project's experiment ran against, if any.",+ "tenant_id": "Id of the workspace the project belongs to.",+ },+ },+ "datasets": {+ "description": "Datasets used for testing and evaluating LLM applications: collections of example inputs and expected outputs.",+ "docs_url": "https://docs.smith.langchain.com/evaluation/concepts#datasets",+ "columns": {+ "id": "Unique identifier (UUID) for the dataset.",+ "name": "Name of the dataset.",+ "description": "Description of the dataset.",+ "data_type": "Data type of the dataset, e.g. kv, llm, or chat.",+ "created_at": "When the dataset was created.",+ "modified_at": "When the dataset was last modified.",+ "example_count": "Number of examples in the dataset.",+ "session_count": "Number of experiment sessions run against the dataset.",+ "last_session_start_time": "Start time of the most recent experiment against the dataset.",+ "inputs_schema_definition": "JSON schema constraining example inputs, if set.",+ "outputs_schema_definition": "JSON schema constraining example outputs, if set.",+ "tenant_id": "Id of the workspace the dataset belongs to.",+ },+ },+ "examples": {+ "description": "Examples (input/output pairs) belonging to datasets, used as test cases and evaluation ground truth.",+ "docs_url": "https://docs.smith.langchain.com/evaluation/concepts#examples",+ "columns": {+ "id": "Unique identifier (UUID) for the example.",+ "dataset_id": "Id of the dataset the example belongs to.",+ "name": "Name of the example.",+ "inputs": "Input payload of the example.",+ "outputs": "Expected output payload of the example.",+ "metadata": "Metadata attached to the example.",+ "created_at": "When the example was created.",+ "modified_at": "When the example was last modified.",+ "source_run_id": "Id of the run the example was created from, if any.",+ },+ },+ "feedback": {+ "description": "Human and programmatic feedback scores attached to runs, e.g. thumbs up/down, correctness scores, or evaluator results.",+ "docs_url": "https://docs.smith.langchain.com/evaluation/concepts#feedback",+ "columns": {+ "id": "Unique identifier (UUID) for the feedback.",+ "run_id": "Id of the run the feedback is attached to.",+ "session_id": "Id of the tracing project of the run the feedback is attached to.",+ "trace_id": "Id of the trace of the run the feedback is attached to.",+ "key": "Feedback key, e.g. correctness or user_score.",+ "score": "Numeric score of the feedback.",+ "value": "Categorical value of the feedback, if any.",+ "comment": "Free-text comment attached to the feedback.",+ "correction": "Suggested correction for the run's output, if any.",+ "created_at": "When the feedback was created.",+ "modified_at": "When the feedback was last modified.",+ "feedback_source": "Origin of the feedback: API, model (evaluator), or app (human).",+ "comparative_experiment_id": "Id of the comparative experiment the feedback belongs to, if any.",+ },+ },+ "annotation_queues": {+ "description": "Annotation queues used to collect human feedback on runs, with reviewer and reservation settings.",+ "docs_url": "https://docs.smith.langchain.com/evaluation/concepts#annotation-queues",+ "columns": {+ "id": "Unique identifier (UUID) for the annotation queue.",+ "name": "Name of the annotation queue.",+ "description": "Description of the annotation queue.",+ "created_at": "When the queue was created.",+ "updated_at": "When the queue was last updated.",+ "default_dataset": "Id of the dataset annotated runs are added to, if set.",+ "num_reviewers_per_item": "Number of reviewers required per queued run.",+ "enable_reservations": "Whether queued runs are reserved to a reviewer while being annotated.",+ "reservation_minutes": "How long a reservation holds a queued run for a reviewer.",+ "total_runs": "Number of runs currently in the queue.",+ "tenant_id": "Id of the workspace the queue belongs to.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/langsmith.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/langsmith.pynew file mode 100644index 000000000000..f2c464c1afab--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/langsmith.py@@ -0,0 +1,562 @@+import re+import json+import hashlib+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.cloud_utils import is_cloud++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher+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.langsmith.settings import (+ DEFAULT_BASE_URL,+ LANGSMITH_ENDPOINTS,+ RUNS_SELECT_FIELDS,+ LangSmithEndpointConfig,+)++# Returned when the resolved host resolves to a private/internal address on cloud (SSRF guard).+HOST_NOT_ALLOWED_ERROR = "LangSmith host is not allowed"++# Returned when a cloud connection would send the API key over plaintext HTTP.+INSECURE_SCHEME_ERROR = "LangSmith host must use https"++# Raised (and registered non-retryable) when the host loops the runs cursor. A host that returns a+# cursor we've already paged is stuck or hostile; retrying re-hits the same cursor, so fail for good.+REPEATED_CURSOR_ERROR = "LangSmith returned a repeated pagination cursor"++# Cap the decoded body of any single LangSmith response. `host` is user-controlled, so a hostile+# server could otherwise stream an unbounded body and exhaust a shared import worker's memory. Set+# well above any realistic page (runs pages carry full LLM inputs/outputs) so it only trips on a+# genuinely abnormal response.+MAX_RESPONSE_BYTES = 256 * 1024 * 1024++# How much of an error-response body to keep for the log line (bounded for the same reason).+MAX_ERROR_BODY_BYTES = 8 * 1024++# Encoded bytes read per streamed chunk while enforcing MAX_RESPONSE_BYTES. Kept small so a single+# decompressed chunk can't inflate far past the cap before we notice — a hostile host could otherwise+# hand back a small gzip bomb that a one-shot decoded read would expand into memory all at once.+READ_CHUNK_BYTES = 64 * 1024++# A real pagination cursor is a short opaque token. A host handing back anything larger is broken or+# hostile — reject it rather than echo it back in the next request body or hold it in memory.+MAX_CURSOR_BYTES = 8 * 1024++# Bound how many pages one activity attempt walks. A hostile host can otherwise return a full page+# with a fresh cursor/offset forever and hold a worker until the week-long activity timeout. On the+# cap we persist the resume checkpoint and raise, so the attempt ends but a legitimate oversized+# import continues from the checkpoint on the next attempt. Generous: the runs rate limits alone+# make hitting this in one attempt take days.+MAX_PAGES_PER_RUN = 50_000+++class LangSmithRetryableError(Exception):+ pass+++class LangSmithHostNotAllowedError(Exception):+ """The resolved host is blocked (SSRF guard) or tried to redirect the authenticated request."""++ pass+++class LangSmithResponseTooLargeError(Exception):+ """The host returned a body larger than `MAX_RESPONSE_BYTES` — refused before buffering it all."""++ pass+++class LangSmithPageLimitError(Exception):+ """One activity attempt walked `MAX_PAGES_PER_RUN` pages. Retryable: resume from the checkpoint."""++ pass+++class LangSmithRepeatedCursorError(Exception):+ """The host looped the runs cursor. Non-retryable (see REPEATED_CURSOR_ERROR) — retrying re-loops."""++ pass+++def _read_capped_body(response: requests.Response, cap: int = MAX_RESPONSE_BYTES) -> bytes:+ """Read at most `cap` decoded bytes from a streamed response, refusing an oversized body.++ Requests are made with `stream=True` so the body isn't materialised until this read. We stream the+ decompressed body in small chunks and stop the moment the running decoded total exceeds the cap.+ Reading the whole body in one shot with `decode_content=True` only bounds the encoded bytes: a+ hostile host could return a small gzip bomb that inflates past the cap in memory before we ever+ check its size. Streaming keeps the peak bounded to roughly one chunk's worth of inflation.+ """+ buffer = bytearray()+ for chunk in response.iter_content(chunk_size=READ_CHUNK_BYTES):+ buffer.extend(chunk)+ if len(buffer) > cap:+ raise LangSmithResponseTooLargeError(f"LangSmith API returned an oversized response (> {cap} bytes)")+ return bytes(buffer)+++class LangSmithResumeConfig:+ # runs/query body cursor for the page to fetch next; None for offset-paginated endpoints.+ cursor: str | None = None+ # Offset to resume paginating from on offset/limit endpoints; None for the runs endpoint.+ offset: int | None = None+ # The server-side time-window lower bound the interrupted run started with, pinned so a+ # resumed run keeps paging the same window (a recomputed bound would shift what each+ # cursor/offset points at).+ window_start: str | None = None+++def normalize_base_url(raw: str) -> str:+ """Reduce a host or URL to a clean `scheme://host[:port]` origin.++ Any path, query, or fragment is dropped so a crafted host value can't extend or retarget the+ fixed LangSmith API paths. A bare host gains an https scheme; an explicit http/https scheme is+ preserved (self-hosted instances may run plaintext on a private network)."""+ raw = raw.strip()+ if not re.match(r"^https?://", raw, flags=re.IGNORECASE):+ raw = f"https://{raw}"+ parsed = urlparse(raw)+ scheme = parsed.scheme.lower()+ scheme = scheme if scheme in ("http", "https") else "https"+ # Rebuild the authority from the parsed hostname/port only — never the raw `netloc`. Keeping+ # `netloc` verbatim lets a value like `https://127.0.0.1\@evil.com` pass the hostname allowlist as+ # `evil.com` (what `urlparse` sees) while `requests` connects to `127.0.0.1` (what its WHATWG-style+ # parser sees): a parser-mismatch SSRF. It also drops any `user:pass@` userinfo, which we never use+ # (auth is the X-API-Key header). Rebuilding guarantees the host we validate is the host we hit.+ host = parsed.hostname or ""+ if ":" in host: # IPv6 literal — hostname strips the brackets that the URL form needs back+ host = f"[{host}]"+ try:+ port = parsed.port+ except ValueError:+ port = None+ authority = host if port is None else f"{host}:{port}"+ return f"{scheme}://{authority}"+++def _host_from_url(base_url: str) -> str:+ return (urlparse(base_url).hostname or "").lower()+++def _is_scheme_safe(base_url: str) -> tuple[bool, str | None]:+ """On cloud, refuse to send the API key over plaintext HTTP.++ Self-hosted PostHog may reach a private LangSmith instance over http on a trusted network, so —+ as with the SSRF host check — this is only enforced on cloud, where a plaintext origin would+ leak the key in transit."""+ if urlparse(base_url).scheme == "https" or not is_cloud():+ return True, None+ return False, INSECURE_SCHEME_ERROR+++def _check_host(base_url: str, team_id: int) -> None:+ """SSRF/plaintext guard for the user-controlled host the API key is sent to. Raises on failure."""+ host_ok, host_err = _is_host_safe(_host_from_url(base_url), team_id)+ if not host_ok:+ raise LangSmithHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)++ scheme_ok, scheme_err = _is_scheme_safe(base_url)+ if not scheme_ok:+ raise LangSmithHostNotAllowedError(scheme_err or INSECURE_SCHEME_ERROR)+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "X-API-Key": api_key,+ "Accept": "application/json",+ }+++def _format_datetime(value: Any) -> str:+ """Format a datetime/date as an ISO 8601 UTC timestamp with a `Z` suffix."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ elif isinstance(value, date):+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ else:+ return str(value)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")+++def _to_datetime(value: Any) -> datetime | None:+ if isinstance(value, datetime):+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ return None+++def _resolve_window_start(+ config: LangSmithEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> datetime | None:+ """Compute the server-side time-window lower bound to send.++ - Incremental run with a watermark: the watermark, shifted back by the lookback overlap and+ capped at now (a future-dated cursor would make the API return nothing).+ - First incremental run (no watermark): floored to `default_lookback_days` so the backfill is+ bounded instead of crawling the whole retention window against the tight run-query limits.+ - Full refresh: no bound — the endpoint's retention window bounds real history anyway.+ """+ if config.window_param is None or not should_use_incremental_field:+ return None++ now = datetime.now(UTC)++ if db_incremental_field_last_value:+ watermark = _to_datetime(db_incremental_field_last_value) or now+ watermark = min(watermark, now)+ if config.incremental_lookback:+ watermark = watermark - config.incremental_lookback+ return watermark++ if config.default_lookback_days:+ return now - timedelta(days=config.default_lookback_days)++ return None+++def validate_credentials(api_key: str, host: str | None, team_id: int | None = None) -> tuple[bool, str | None]:+ """Probe the key by listing one tracing project — the cheapest workspace-scoped read with no+ required filters. A 200 confirms the key is genuine."""+ base_url = normalize_base_url(host or DEFAULT_BASE_URL)++ # The host is user-controlled and the API key is sent to it, so block hosts that resolve to+ # private/internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.+ if team_id is not None:+ try:+ _check_host(base_url, team_id)+ except LangSmithHostNotAllowedError as e:+ return False, str(e)++ url = f"{base_url}/api/v1/sessions?{urlencode({'limit': 1})}"+ try:+ # Redact the key, never follow a redirect off the validated host, and keep the response out+ # of HTTP sample capture — LangSmith payloads carry LLM prompts/outputs that can embed+ # secrets or personal data the name-based scrubber won't recognize. `stream=True` so a+ # hostile host can't make us buffer an unbounded body: we only read the status code, then+ # close the connection without ever pulling the body.+ response = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False).get(+ url, headers=_get_headers(api_key), timeout=10, stream=True+ )+ try:+ status_code = response.status_code+ finally:+ response.close()+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if status_code == 200:+ return True, None+ if status_code == 401:+ return False, "Invalid or revoked LangSmith API key"+ if status_code == 403:+ return False, "This LangSmith API key does not have access to the workspace"+ if status_code == 404:+ return False, "LangSmith API not found at this host. Check the host field."+ return False, f"LangSmith API returned status {status_code}"+++@retry(+ retry=retry_if_exception_type(+ (+ LangSmithRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ json_body: dict[str, Any] | None = None,+) -> Any:+ """GET the URL, or POST `json_body` to it when given (the runs/query endpoint).++ `stream=True` so the body isn't buffered until we read it under `MAX_RESPONSE_BYTES` — `host` is+ user-controlled, so an unbounded body could otherwise exhaust the worker's memory.+ """+ if json_body is not None:+ response = session.post(url, headers=headers, json=json_body, timeout=60, stream=True)+ else:+ response = session.get(url, headers=headers, timeout=60, stream=True)++ with response:+ # 429 and transient 5xx are retryable (runs/query rate limits are tight: 10 req/10s on+ # windows up to 7 days, 3 req/10s beyond); auth/permission errors below are not.+ if response.status_code == 429 or response.status_code >= 500:+ raise LangSmithRetryableError(f"LangSmith API error (retryable): status={response.status_code}, url={url}")++ # Redirects are disabled as an SSRF boundary; a 3xx means the host tried to bounce the+ # authenticated request elsewhere, so fail instead of parsing (or following) it.+ if 300 <= response.status_code < 400:+ raise LangSmithHostNotAllowedError(+ f"LangSmith API returned an unexpected redirect: status={response.status_code}, url={url}"+ )++ if not response.ok:+ # Truncate (don't cap-and-raise) so a large error body still surfaces the real HTTP error.+ body = response.raw.read(MAX_ERROR_BODY_BYTES, decode_content=True).decode("utf-8", errors="replace")+ logger.error(f"LangSmith API error: status={response.status_code}, body={body}, url={url}")+ response.raise_for_status()++ raw = _read_capped_body(response)+ return json.loads(raw) if raw else None+++def _get_runs_rows(+ session: requests.Session,+ headers: dict[str, str],+ base_url: str,+ config: LangSmithEndpointConfig,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[LangSmithResumeConfig],+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[Any]:+ """Page through POST /runs/query with the body cursor.++ The full body (including the start_time window) is re-sent with every cursor request, so every+ page stays bounded by the watermark — incremental syncs can't walk back through history."""+ url = f"{base_url}{config.path}"++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ cursor = resume.cursor+ window_start = resume.window_start+ logger.debug(f"LangSmith: resuming runs from cursor={cursor}")+ else:+ cursor = None+ start = _resolve_window_start(config, should_use_incremental_field, db_incremental_field_last_value)+ window_start = _format_datetime(start) if start is not None else None++ body: dict[str, Any] = {+ "limit": config.page_size,+ "select": RUNS_SELECT_FIELDS,+ # Ascending by start time so cursor pagination walks forward deterministically from the+ # window bound. The watermark still only persists at job end (sort_mode="desc") since we+ # can't verify the ordering guarantee across every LangSmith deployment.+ "order": "asc",+ }+ if window_start:+ body["start_time"] = window_start++ # Digests, not the cursors themselves: `next_cursor` is attacker-controlled and can be nearly as+ # large as a whole response, so retaining the raw values would let a stream of unique cursors+ # grow this set without bound. A fixed-size digest is all cycle detection needs.+ seen_cursors: set[bytes] = set()+ pages = 0+ while True:+ page_cursor = cursor+ page_body = {**body, "cursor": page_cursor} if page_cursor else dict(body)+ data = _fetch_page(session, url, headers, logger, json_body=page_body)++ runs = data.get("runs", []) if isinstance(data, dict) else []+ if not runs:+ break++ next_cursor = (data.get("cursors") or {}).get("next")++ for item in runs:+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding (and only when more pages remain) so a crash re-reads this+ # page rather than skipping it — merge dedupes on the primary key.+ if next_cursor:+ resumable_source_manager.save_state(+ LangSmithResumeConfig(cursor=page_cursor, window_start=window_start)+ )++ if not next_cursor:+ break++ # Reject an absurdly large cursor before it's echoed back or remembered.+ if len(next_cursor.encode()) > MAX_CURSOR_BYTES:+ raise LangSmithResponseTooLargeError(+ f"LangSmith returned an oversized pagination cursor (> {MAX_CURSOR_BYTES} bytes)"+ )++ # A host that hands back a cursor it already gave us (or the one we just sent) is looping;+ # retrying would re-hit it, so fail for good instead of spinning until the activity timeout.+ cursor_digest = hashlib.sha256(next_cursor.encode()).digest()+ if next_cursor == page_cursor or cursor_digest in seen_cursors:+ raise LangSmithRepeatedCursorError(REPEATED_CURSOR_ERROR)+ seen_cursors.add(cursor_digest)++ pages += 1+ if pages >= MAX_PAGES_PER_RUN:+ # Flush any batched-but-unyielded items from this page before checkpointing the next+ # page — resuming from next_cursor skips this page, so an unflushed partial batch is lost.+ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+ # Checkpoint the next page and end this attempt; the resume path picks it up so a+ # legitimate oversized import continues without one attempt monopolising a worker.+ resumable_source_manager.save_state(LangSmithResumeConfig(cursor=next_cursor, window_start=window_start))+ raise LangSmithPageLimitError(+ f"LangSmith runs import hit the {MAX_PAGES_PER_RUN}-page per-attempt limit; resuming from checkpoint"+ )++ cursor = next_cursor+++def _get_offset_rows(+ session: requests.Session,+ headers: dict[str, str],+ base_url: str,+ config: LangSmithEndpointConfig,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[LangSmithResumeConfig],+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[Any]:+ """Page through a GET list endpoint with offset/limit. Responses are bare JSON arrays; a page+ shorter than the limit is the last page."""+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ offset = resume.offset or 0+ window_start = resume.window_start+ logger.debug(f"LangSmith: resuming {config.name} from offset={offset}")+ else:+ offset = 0+ start = _resolve_window_start(config, should_use_incremental_field, db_incremental_field_last_value)+ window_start = _format_datetime(start) if start is not None else None++ params: dict[str, Any] = {"limit": config.page_size}+ if config.window_param and window_start:+ params[config.window_param] = window_start++ pages = 0+ while True:+ page_offset = offset+ url = f"{base_url}{config.path}?{urlencode({**params, 'offset': page_offset})}"+ data = _fetch_page(session, url, headers, logger)++ rows = data if isinstance(data, list) else []+ if not rows:+ break++ is_last_page = len(rows) < config.page_size++ for item in rows:+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding so a crash re-reads this page rather than skipping it.+ if not is_last_page:+ resumable_source_manager.save_state(+ LangSmithResumeConfig(offset=page_offset, window_start=window_start)+ )++ if is_last_page:+ break+ offset = page_offset + config.page_size++ pages += 1+ if pages >= MAX_PAGES_PER_RUN:+ # Flush any batched-but-unyielded items from this page before checkpointing the next+ # offset — resuming skips this page, so an unflushed partial batch is lost.+ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+ # A host that returns a full page at every offset forever would page without end;+ # checkpoint the next offset and end this attempt so the resume path continues a real+ # oversized import without one attempt holding a worker until the activity timeout.+ resumable_source_manager.save_state(LangSmithResumeConfig(offset=offset, window_start=window_start))+ raise LangSmithPageLimitError(+ f"LangSmith {config.name} import hit the {MAX_PAGES_PER_RUN}-page per-attempt limit; resuming from checkpoint"+ )+++def get_rows(+ api_key: str,+ base_url: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LangSmithResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[Any]:+ config = LANGSMITH_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)++ # Re-check at run time (not just at source-create): the host could have been edited or now+ # resolve to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ _check_host(base_url, team_id)++ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # Redact the key and never follow a redirect off the validated host. Keep response bodies out+ # of HTTP sample capture — run inputs/outputs are raw LLM prompts and completions that can+ # carry secrets or personal data the name-based scrubber won't recognize.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False)++ pager = _get_runs_rows if config.pagination == "cursor" else _get_offset_rows+ yield from pager(+ session,+ headers,+ base_url,+ config,+ batcher,+ resumable_source_manager,+ logger,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def langsmith_source(+ api_key: str,+ base_url: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LangSmithResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = LANGSMITH_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ base_url=base_url,+ 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,+ ),+ primary_keys=config.primary_keys,+ sort_mode=config.sort_mode,+ 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,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/settings.pynew file mode 100644index 000000000000..e26b641dfc02--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/settings.py@@ -0,0 +1,152 @@+from dataclasses import dataclass, field+from datetime import timedelta+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# US cloud host. EU-region accounts use https://eu.api.smith.langchain.com and self-hosted+# deployments use their own host — the user overrides via the source's `host` field.+DEFAULT_BASE_URL = "https://api.smith.langchain.com"++# Fields requested from POST /runs/query via `select`. The default select pulls heavyweight+# internals (manifest, serialized, events, S3 URL variants) that bloat every page and slow the+# tight run-query rate limits, so we ask only for the analytics-relevant columns.+RUNS_SELECT_FIELDS = [+ "id",+ "name",+ "run_type",+ "start_time",+ "end_time",+ "status",+ "error",+ "extra",+ "inputs",+ "outputs",+ "parent_run_id",+ "session_id",+ "reference_example_id",+ "total_tokens",+ "prompt_tokens",+ "completion_tokens",+ "total_cost",+ "prompt_cost",+ "completion_cost",+ "first_token_time",+ "trace_id",+ "dotted_order",+ "tags",+ "thread_id",+ "feedback_stats",+]+++@dataclass+class LangSmithEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField]+ # runs/query is a POST whose cursor lives in the JSON body; every other list endpoint is a+ # GET paginated with offset/limit query params.+ pagination: Literal["cursor", "offset"] = "offset"+ # Stable creation-style timestamp to partition by (never a mutable `modified_at` field).+ partition_key: Optional[str] = None+ page_size: int = 100+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Name of the server-side lower-bound time filter (`start_time` in the runs/query body,+ # `min_created_at` query param on feedback). None means no server-side window — full+ # refresh only.+ window_param: Optional[str] = None+ # Floor the first incremental backfill to the last N days instead of the entire retention+ # window, bounding the initial pull against the tight runs/query rate limits.+ default_lookback_days: Optional[int] = None+ # Trailing overlap re-subtracted from the watermark on every incremental run, re-pulling a+ # window of rows so runs whose fields mutate after creation (end_time, outputs, feedback+ # stats land when the run finishes) are re-read; the delta merge dedupes on the primary key.+ incremental_lookback: Optional[timedelta] = None+ # We request `order=asc` on runs/query, but we can't rely on response ordering across every+ # LangSmith deployment (offset endpoints document no ordering at all), so every incremental+ # endpoint declares `desc`: the pipeline then persists the watermark (max value seen) only at+ # successful job end instead of checkpointing per batch, which is correct under any actual+ # ordering. Mid-run recovery comes from the resumable cursor/offset state instead.+ sort_mode: Literal["asc", "desc"] = "asc"+++_START_TIME_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "start_time",+ "type": IncrementalFieldType.DateTime,+ "field": "start_time",+ "field_type": IncrementalFieldType.DateTime,+ },+]++_CREATED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++LANGSMITH_ENDPOINTS: dict[str, LangSmithEndpointConfig] = {+ # Traces and their nested spans (LLM calls, chains, tools, retrievers) across every tracing+ # project. The flagship table: one row per run, filtered server-side by start_time.+ "runs": LangSmithEndpointConfig(+ name="runs",+ path="/api/v1/runs/query",+ pagination="cursor",+ partition_key="start_time",+ incremental_fields=_START_TIME_INCREMENTAL_FIELDS,+ window_param="start_time",+ default_lookback_days=365,+ # end_time/outputs/feedback_stats land after the run starts; the start_time cursor alone+ # would freeze a run at its first-synced (possibly still-running) state.+ incremental_lookback=timedelta(hours=1),+ sort_mode="desc",+ ),+ # Tracing projects ("sessions" in the LangSmith API), with rolled-up run counts, costs, and+ # latency percentiles. Small list; no server-side time filter, so full refresh only.+ "projects": LangSmithEndpointConfig(+ name="projects",+ path="/api/v1/sessions",+ incremental_fields=[],+ ),+ "datasets": LangSmithEndpointConfig(+ name="datasets",+ path="/api/v1/datasets",+ incremental_fields=[],+ ),+ # Dataset examples across all datasets. The API versions examples via `as_of` snapshots+ # rather than a created/modified filter, so full refresh only.+ "examples": LangSmithEndpointConfig(+ name="examples",+ path="/api/v1/examples",+ incremental_fields=[],+ ),+ # Human and programmatic feedback scores attached to runs. `min_created_at` is a genuine+ # server-side filter; feedback edits move modified_at (not filterable), so the lookback+ # re-pulls a trailing window and merge dedupes on id.+ "feedback": LangSmithEndpointConfig(+ name="feedback",+ path="/api/v1/feedback",+ partition_key="created_at",+ incremental_fields=_CREATED_AT_INCREMENTAL_FIELDS,+ window_param="min_created_at",+ default_lookback_days=365,+ incremental_lookback=timedelta(hours=1),+ sort_mode="desc",+ ),+ "annotation_queues": LangSmithEndpointConfig(+ name="annotation_queues",+ path="/api/v1/annotation-queues",+ incremental_fields=[],+ ),+}++ENDPOINTS = tuple(LANGSMITH_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in LANGSMITH_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/source.pyindex 1d0c8739a710..6974e079eb61 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/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 LangSmithSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.langsmith import (+ DEFAULT_BASE_URL,+ REPEATED_CURSOR_ERROR,+ LangSmithResumeConfig,+ langsmith_source,+ normalize_base_url,+ validate_credentials as validate_langsmith_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ LANGSMITH_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class LangSmithSource(SimpleSource[LangSmithSourceConfig]):+class LangSmithSource(ResumableSource[LangSmithSourceConfig, LangSmithResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LANGSMITH@@ -24,8 +51,117 @@ class LangSmithSource(SimpleSource[LangSmithSourceConfig]):name=SchemaExternalDataSourceType.LANG_SMITH,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="LangSmith",- iconPath="/static/services/langsmith.png",- keywords=["llm", "observability", "tracing", "langchain"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter a LangSmith API key to sync your LLM traces, tracing projects, datasets, and feedback into the PostHog Data warehouse.++Create an API key in your [LangSmith settings](https://smith.langchain.com/settings) under **API Keys**.++Leave the **Host** field blank for the US cloud (`api.smith.langchain.com`). Set it to `https://eu.api.smith.langchain.com` for EU-region accounts, or to your own host for self-hosted deployments.""",+ iconPath="/static/services/langsmith.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/langsmith",+ keywords=["llm", "observability", "tracing", "langchain", "evals"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="lsv2_pt_...",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="host",+ label="Host",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://api.smith.langchain.com",+ secret=False,+ ),+ ],+ ),+ )++ @property+ def connection_host_fields(self) -> list[str]:+ # The API key is sent to `host`; retargeting it must re-require the key so a preserved+ # secret can't be redirected at a server the editor controls.+ return ["host"]++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your LangSmith API key is invalid or has been revoked. Create a new API key in your LangSmith settings, then reconnect.",+ "403 Client Error": "Your LangSmith API key does not have access to this workspace. Check the key's workspace scope, then reconnect.",+ REPEATED_CURSOR_ERROR: "LangSmith kept returning the same pagination cursor, so the import was stopped to avoid looping. This usually means the host is misconfigured — check the Host field, then reconnect.",+ }++ def get_schemas(+ self,+ config: LangSmithSourceConfig,+ 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 == "runs":+ return (+ "Traces and their nested spans (LLM calls, chains, tools) across every tracing "+ "project. The first incremental sync only pulls the last 365 days"+ )+ if endpoint == "projects":+ return "Tracing projects (called sessions in the LangSmith API)"+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = LANGSMITH_ENDPOINTS[endpoint]+ supports_incremental = endpoint_config.window_param is not None and bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=supports_incremental,+ supports_append=supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ detected_primary_keys=endpoint_config.primary_keys,+ description=_description(endpoint),+ )++ schemas = [_build_schema(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: LangSmithSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_langsmith_credentials(config.api_key, config.host or None, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LangSmithResumeConfig]:+ return ResumableSourceManager[LangSmithResumeConfig](inputs, LangSmithResumeConfig)++ def source_for_pipeline(+ self,+ config: LangSmithSourceConfig,+ resumable_source_manager: ResumableSourceManager[LangSmithResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return langsmith_source(+ api_key=config.api_key,+ base_url=normalize_base_url(config.host or DEFAULT_BASE_URL),+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/tests/test_langsmith.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/tests/test_langsmith.pynew file mode 100644index 000000000000..5ac8a8e06b5a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/tests/test_langsmith.py@@ -0,0 +1,422 @@+from datetime import UTC, datetime, timedelta+from typing import Any++import pytest+from unittest import mock++import structlog++from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.langsmith import (+ MAX_CURSOR_BYTES,+ LangSmithHostNotAllowedError,+ LangSmithPageLimitError,+ LangSmithRepeatedCursorError,+ LangSmithResponseTooLargeError,+ LangSmithResumeConfig,+ _fetch_page,+ _read_capped_body,+ _resolve_window_start,+ get_rows,+ normalize_base_url,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.settings import (+ LANGSMITH_ENDPOINTS,+ RUNS_SELECT_FIELDS,+)++logger = structlog.get_logger()++BASE_URL = "https://api.smith.langchain.com"++_FETCH_PAGE = "products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.langsmith._fetch_page"+_IS_HOST_SAFE = "products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.langsmith._is_host_safe"+_IS_CLOUD = "products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.langsmith.is_cloud"+_MAKE_SESSION = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.langsmith.make_tracked_session"+)+_MAX_PAGES = "products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.langsmith.MAX_PAGES_PER_RUN"+++class FakeManager:+ """Stand-in for ResumableSourceManager that records saved state and can replay a resume value."""++ def __init__(self, resume: LangSmithResumeConfig | None = None):+ self._resume = resume+ self.saved: list[LangSmithResumeConfig] = []++ def can_resume(self) -> bool:+ return self._resume is not None++ def load_state(self) -> LangSmithResumeConfig | None:+ return self._resume++ def save_state(self, data: LangSmithResumeConfig) -> None:+ self.saved.append(data)+++def _collect(tables) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for table in tables:+ rows.extend(table.to_pylist())+ return rows+++def _run(run_id: str) -> dict[str, Any]:+ return {"id": run_id, "start_time": "2026-06-01T00:00:00Z"}+++class TestNormalizeBaseUrl:+ @pytest.mark.parametrize(+ "raw,expected",+ [+ ("api.smith.langchain.com", "https://api.smith.langchain.com"),+ ("https://eu.api.smith.langchain.com/", "https://eu.api.smith.langchain.com"),+ # A crafted path/query must not extend or retarget the fixed API paths.+ ("https://evil.example/api/v1/steal?x=1#f", "https://evil.example"),+ # Self-hosted instances may run plaintext on a private network; the scheme is preserved+ # (and separately blocked on cloud by _is_scheme_safe).+ ("http://langsmith.internal:1984", "http://langsmith.internal:1984"),+ ("https://api.smith.langchain.com:8443", "https://api.smith.langchain.com:8443"),+ ("https://[::1]:8080", "https://[::1]:8080"),+ # Authority is rebuilt from the parsed hostname/port only — never the raw netloc — so a+ # backslash or userinfo can't make the validated host differ from the connected one. Keeping+ # netloc verbatim would let `https://127.0.0.1\@evil.com` pass the allowlist as `evil.com`+ # while requests connects to `127.0.0.1` (a parser-mismatch SSRF).+ ("https://127.0.0.1\\@evil.com", "https://evil.com"),+ ("https://user:[email protected]@evil.com", "https://evil.com"),+ ],+ )+ def test_reduces_to_clean_origin(self, raw, expected):+ assert normalize_base_url(raw) == expected+++class TestResolveWindowStart:+ def test_incremental_with_watermark_subtracts_lookback(self):+ config = LANGSMITH_ENDPOINTS["runs"]+ watermark = datetime(2026, 6, 1, 12, 0, 0, tzinfo=UTC)++ start = _resolve_window_start(+ config, should_use_incremental_field=True, db_incremental_field_last_value=watermark+ )++ lookback = config.incremental_lookback+ assert lookback is not None+ assert start == watermark - lookback++ def test_future_watermark_capped_to_now(self):+ config = LANGSMITH_ENDPOINTS["runs"]+ future = datetime.now(UTC) + timedelta(days=30)++ start = _resolve_window_start(config, should_use_incremental_field=True, db_incremental_field_last_value=future)++ # A future cursor would make the API return nothing forever; it's capped at ~now.+ assert start is not None and start <= datetime.now(UTC)++ def test_first_incremental_sync_floors_to_lookback_days(self):+ config = LANGSMITH_ENDPOINTS["runs"]++ start = _resolve_window_start(config, should_use_incremental_field=True, db_incremental_field_last_value=None)++ assert start is not None+ assert (datetime.now(UTC) - start).days == pytest.approx(config.default_lookback_days, abs=1)++ @pytest.mark.parametrize("endpoint", ["runs", "projects"])+ def test_full_refresh_sends_no_window(self, endpoint):+ config = LANGSMITH_ENDPOINTS[endpoint]++ start = _resolve_window_start(config, should_use_incremental_field=False, db_incremental_field_last_value=None)++ assert start is None+++class TestRunsPagination:+ def test_cursor_walk_keeps_window_on_every_page(self):+ # If the start_time window were dropped from cursor requests, every incremental sync would+ # walk back through the full run history — an API-cost and memory bug.+ manager = FakeManager()+ watermark = datetime(2026, 6, 1, tzinfo=UTC)+ bodies: list[dict[str, Any]] = []+ pages = [+ {"runs": [_run("a")], "cursors": {"next": "c2"}},+ {"runs": [_run("b")], "cursors": {"next": None}},+ ]++ def fake_fetch(session, url, headers, log, json_body=None):+ bodies.append(json_body)+ return pages[len(bodies) - 1]++ with mock.patch(_FETCH_PAGE, side_effect=fake_fetch):+ rows = _collect(+ get_rows("key", BASE_URL, "runs", logger, manager, 1, True, watermark) # type: ignore[arg-type]+ )++ assert [r["id"] for r in rows] == ["a", "b"]+ assert len(bodies) == 2+ assert "cursor" not in bodies[0]+ assert bodies[1]["cursor"] == "c2"+ for body in bodies:+ assert body["start_time"] # the watermark window rides every page+ assert body["order"] == "asc"+ assert body["limit"] == 100+ assert body["select"] == RUNS_SELECT_FIELDS++ def test_terminates_on_empty_page_and_missing_cursors(self):+ manager = FakeManager()++ with mock.patch(_FETCH_PAGE, return_value={"runs": [], "cursors": {"next": "dangling"}}) as fetch:+ rows = _collect(get_rows("key", BASE_URL, "runs", logger, manager, 1)) # type: ignore[arg-type]++ assert rows == []+ assert fetch.call_count == 1++ def test_resume_pins_cursor_and_window(self):+ manager = FakeManager(resume=LangSmithResumeConfig(cursor="c9", window_start="2026-01-01T00:00:00.000000Z"))+ bodies: list[dict[str, Any]] = []++ def fake_fetch(session, url, headers, log, json_body=None):+ bodies.append(json_body)+ return {"runs": [_run("x")], "cursors": {"next": None}}++ with mock.patch(_FETCH_PAGE, side_effect=fake_fetch):+ _collect(get_rows("key", BASE_URL, "runs", logger, manager, 1, True, datetime.now(UTC))) # type: ignore[arg-type]++ # The interrupted run's window is replayed, not recomputed from the new watermark — a+ # recomputed bound would shift what the saved cursor points at.+ assert bodies[0]["cursor"] == "c9"+ assert bodies[0]["start_time"] == "2026-01-01T00:00:00.000000Z"++ def test_state_saved_after_yield_with_current_page_cursor(self):+ # A crash after a yield must re-read the yielded page (merge dedupes), never skip past it —+ # so the checkpoint is the cursor of the page being read, saved only after a batch yields.+ manager = FakeManager()+ big_page = {"runs": [_run(f"r{i}") for i in range(2500)], "cursors": {"next": "c2"}}+ last_page = {"runs": [_run("tail")], "cursors": {"next": None}}++ with mock.patch(_FETCH_PAGE, side_effect=[big_page, last_page]):+ rows = _collect(get_rows("key", BASE_URL, "runs", logger, manager, 1)) # type: ignore[arg-type]++ assert len(rows) == 2501+ assert manager.saved == [LangSmithResumeConfig(cursor=None, window_start=None)]+++class TestOffsetPagination:+ def test_walks_offsets_until_short_page(self):+ manager = FakeManager()+ pages = [[{"id": f"p1-{i}"} for i in range(100)], [{"id": "p2-0"}]]+ urls: list[str] = []++ def fake_fetch(session, url, headers, log, json_body=None):+ urls.append(url)+ return pages[len(urls) - 1]++ with mock.patch(_FETCH_PAGE, side_effect=fake_fetch):+ rows = _collect(get_rows("key", BASE_URL, "projects", logger, manager, 1)) # type: ignore[arg-type]++ assert len(rows) == 101+ assert "offset=0" in urls[0]+ assert "offset=100" in urls[1]+ assert manager.saved == []++ def test_feedback_incremental_sends_min_created_at(self):+ manager = FakeManager()+ watermark = datetime(2026, 6, 1, tzinfo=UTC)+ urls: list[str] = []++ def fake_fetch(session, url, headers, log, json_body=None):+ urls.append(url)+ return []++ with mock.patch(_FETCH_PAGE, side_effect=fake_fetch):+ _collect(get_rows("key", BASE_URL, "feedback", logger, manager, 1, True, watermark)) # type: ignore[arg-type]++ assert "min_created_at=" in urls[0]++ def test_resume_starts_from_saved_offset_and_pins_window(self):+ manager = FakeManager(resume=LangSmithResumeConfig(offset=200, window_start="2026-01-01T00:00:00.000000Z"))+ urls: list[str] = []++ def fake_fetch(session, url, headers, log, json_body=None):+ urls.append(url)+ return [{"id": "x"}]++ with mock.patch(_FETCH_PAGE, side_effect=fake_fetch):+ _collect(get_rows("key", BASE_URL, "feedback", logger, manager, 1, True, datetime.now(UTC))) # type: ignore[arg-type]++ assert "offset=200" in urls[0]+ assert "min_created_at=2026-01-01T00%3A00%3A00.000000Z" in urls[0]+++class TestPaginationAbuseGuards:+ def test_repeated_runs_cursor_raises(self):+ # A host that hands back a cursor it already gave us would loop forever; the walk must bail+ # instead of spinning until the week-long activity timeout.+ manager = FakeManager()++ def fake_fetch(session, url, headers, log, json_body=None):+ return {"runs": [_run("a")], "cursors": {"next": "loop"}}++ with mock.patch(_FETCH_PAGE, side_effect=fake_fetch):+ with pytest.raises(LangSmithRepeatedCursorError):+ _collect(get_rows("key", BASE_URL, "runs", logger, manager, 1)) # type: ignore[arg-type]++ def test_oversized_runs_cursor_raises(self):+ # An attacker-controlled cursor near the response-size limit must never be echoed back or+ # retained; a cursor beyond MAX_CURSOR_BYTES is rejected outright.+ manager = FakeManager()+ big_cursor = "x" * (MAX_CURSOR_BYTES + 1)++ def fake_fetch(session, url, headers, log, json_body=None):+ return {"runs": [_run("a")], "cursors": {"next": big_cursor}}++ with mock.patch(_FETCH_PAGE, side_effect=fake_fetch):+ with pytest.raises(LangSmithResponseTooLargeError):+ _collect(get_rows("key", BASE_URL, "runs", logger, manager, 1)) # type: ignore[arg-type]++ def test_runs_page_limit_checkpoints_and_raises(self):+ # A host returning an endless stream of full pages with fresh cursors must not monopolise a+ # worker: the attempt ends at the cap after checkpointing so the resume path continues it.+ # Rows read before the cap but never large enough to fill a batch must be flushed before+ # raising — the checkpoint points at the *next* page, so an unflushed partial batch is lost.+ manager = FakeManager()+ counter = {"n": 0}++ def fake_fetch(session, url, headers, log, json_body=None):+ counter["n"] += 1+ return {"runs": [_run(f"r{counter['n']}")], "cursors": {"next": f"c{counter['n']}"}}++ rows: list[dict[str, Any]] = []+ with mock.patch(_MAX_PAGES, 3), mock.patch(_FETCH_PAGE, side_effect=fake_fetch):+ with pytest.raises(LangSmithPageLimitError):+ for table in get_rows("key", BASE_URL, "runs", logger, manager, 1): # type: ignore[arg-type]+ rows.extend(table.to_pylist())++ assert manager.saved[-1].cursor is not None+ assert [r["id"] for r in rows] == ["r1", "r2", "r3"]++ def test_offset_page_limit_checkpoints_and_raises(self):+ # Same guard on offset endpoints, where a host can return exactly page_size rows forever.+ # The rows read before the cap must be flushed rather than dropped on the way out.+ manager = FakeManager()+ page_size = LANGSMITH_ENDPOINTS["projects"].page_size++ def fake_fetch(session, url, headers, log, json_body=None):+ return [{"id": f"x{i}"} for i in range(page_size)]++ rows: list[dict[str, Any]] = []+ with mock.patch(_MAX_PAGES, 3), mock.patch(_FETCH_PAGE, side_effect=fake_fetch):+ with pytest.raises(LangSmithPageLimitError):+ for table in get_rows("key", BASE_URL, "projects", logger, manager, 1): # type: ignore[arg-type]+ rows.extend(table.to_pylist())++ assert manager.saved[-1].offset is not None+ assert len(rows) == 3 * page_size+++class TestResponseSizeCap:+ def test_read_capped_body_aborts_before_consuming_whole_body(self):+ # The body is streamed and rejected the moment the running total passes the cap, so a hostile+ # host can't inflate a small gzip bomb into memory before we notice. A one-shot decoded read+ # would pull (and decompress) everything first, so this asserts we stop mid-stream.+ consumed: list[int] = []++ def chunks():+ consumed.append(1)+ yield b"x" * 6+ consumed.append(2)+ yield b"x" * 6+ consumed.append(3) # must never run — the cap is already blown after the second chunk+ yield b"x" * 6++ response = mock.MagicMock()+ response.iter_content.return_value = chunks()+ with pytest.raises(LangSmithResponseTooLargeError):+ _read_capped_body(response, cap=10)+ assert consumed == [1, 2]++ def test_read_capped_body_returns_body_within_cap(self):+ response = mock.MagicMock()+ response.iter_content.return_value = [b'{"ok":', b" true}"]+ assert _read_capped_body(response, cap=1024) == b'{"ok": true}'++ def test_fetch_page_streams_and_parses_body(self):+ # The body must be pulled through the streamed/capped reader, never buffered eagerly by+ # requests — dropping stream=True would reintroduce the unbounded-buffering vector.+ response = mock.MagicMock()+ response.status_code = 200+ response.ok = True+ response.__enter__.return_value = response+ response.__exit__.return_value = False+ response.iter_content.return_value = [b'{"runs": [{"id": "a"}]}']+ session = mock.MagicMock()+ session.post.return_value = response++ result = _fetch_page(session, f"{BASE_URL}/api/v1/runs/query", {}, logger, json_body={"limit": 1})++ assert result == {"runs": [{"id": "a"}]}+ assert session.post.call_args.kwargs["stream"] is True+++class TestHostSafety:+ def test_unsafe_host_raises_before_any_fetch(self):+ with (+ mock.patch(_IS_HOST_SAFE, return_value=(False, "Hosts with internal IP addresses are not allowed")),+ mock.patch(_FETCH_PAGE) as fetch,+ ):+ with pytest.raises(LangSmithHostNotAllowedError):+ _collect(get_rows("key", "https://10.0.0.1", "runs", logger, FakeManager(), 99)) # type: ignore[arg-type]++ fetch.assert_not_called()++ def test_plaintext_http_host_raises_on_cloud(self):+ with (+ mock.patch(_IS_HOST_SAFE, return_value=(True, None)),+ mock.patch(_IS_CLOUD, return_value=True),+ mock.patch(_FETCH_PAGE) as fetch,+ ):+ with pytest.raises(LangSmithHostNotAllowedError):+ _collect(get_rows("key", "http://langsmith.example", "runs", logger, FakeManager(), 1)) # type: ignore[arg-type]++ fetch.assert_not_called()++ def test_session_disables_redirects_redacts_key_and_skips_capture(self):+ # The key goes to a user-controlled host, so the session must never follow a redirect off+ # it; run payloads are raw LLM prompts/outputs, so bodies must stay out of sample capture.+ with (+ mock.patch(_MAKE_SESSION) as session,+ mock.patch(_FETCH_PAGE, return_value={"runs": [], "cursors": {}}),+ ):+ _collect(get_rows("key", BASE_URL, "runs", logger, FakeManager(), 1)) # type: ignore[arg-type]++ assert session.call_args.kwargs["allow_redirects"] is False+ assert session.call_args.kwargs["redact_values"] == ("key",)+ assert session.call_args.kwargs["capture"] is False+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code,expected_valid",+ [(200, True), (401, False), (403, False), (404, False), (500, False)],+ )+ def test_status_mapping(self, status_code, expected_valid):+ response = mock.MagicMock()+ response.status_code = status_code++ with mock.patch(_MAKE_SESSION) as session:+ session.return_value.get.return_value = response+ valid, message = validate_credentials("key", None)++ assert valid is expected_valid+ if not expected_valid:+ assert message++ def test_unsafe_host_fails_before_network_call(self):+ with (+ mock.patch(_IS_HOST_SAFE, return_value=(False, "Hosts with internal IP addresses are not allowed")),+ mock.patch(_MAKE_SESSION) as session,+ ):+ valid, message = validate_credentials("key", "https://10.0.0.1", team_id=99)++ assert valid is False+ assert message+ session.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/tests/test_langsmith_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/tests/test_langsmith_source.pynew file mode 100644index 000000000000..d588a71a8148--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/tests/test_langsmith_source.py@@ -0,0 +1,130 @@+import pytest+from unittest import mock++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LangSmithSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.langsmith import (+ REPEATED_CURSOR_ERROR,+ LangSmithResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.source import LangSmithSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestLangSmithSource:+ def setup_method(self):+ self.source = LangSmithSource()+ self.team_id = 123+ self.config = LangSmithSourceConfig(api_key="key", host=None)++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.LANGSMITH++ def test_config_fields(self):+ field_names = {f.name for f in self.source.get_source_config.fields}+ assert field_names == {"api_key", "host"}++ api_key = next(f for f in self.source.get_source_config.fields if f.name == "api_key")+ # The key is a secret; the wizard must render it as a password input.+ assert isinstance(api_key, SourceFieldInputConfig)+ assert api_key.required is True+ assert api_key.type == SourceFieldInputConfigType.PASSWORD++ def test_host_is_a_connection_host_field(self):+ # The key is sent to `host`; retargeting it must force re-entry of the key secret.+ assert self.source.connection_host_fields == ["host"]++ @pytest.mark.parametrize(+ "endpoint,expected_incremental",+ [+ ("runs", True),+ ("projects", False),+ ("datasets", False),+ ("examples", False),+ ("feedback", True),+ ("annotation_queues", False),+ ],+ )+ def test_get_schemas(self, endpoint, expected_incremental):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ assert endpoint in schemas+ schema = schemas[endpoint]+ assert schema.supports_incremental is expected_incremental+ assert schema.supports_append is expected_incremental+ assert schema.detected_primary_keys == ["id"]++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error", REPEATED_CURSOR_ERROR])+ def test_auth_errors_are_non_retryable(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert manager._data_class is LangSmithResumeConfig++ def test_validate_credentials_collapses_blank_host_and_forwards_team_id(self):+ config = LangSmithSourceConfig(api_key="key", host="")++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.source.validate_langsmith_credentials",+ return_value=(True, None),+ ) as validate:+ result = self.source.validate_credentials(config, self.team_id)++ assert result == (True, None)+ # An empty host override collapses to None so the US-cloud default is used; team_id is+ # forwarded so the credential probe can SSRF-check the resolved host.+ validate.assert_called_once_with("key", None, self.team_id)++ @pytest.mark.parametrize(+ "host,expected_base_url",+ [+ (None, "https://api.smith.langchain.com"),+ ("https://eu.api.smith.langchain.com/", "https://eu.api.smith.langchain.com"),+ ],+ )+ def test_source_for_pipeline_resolves_base_url(self, host, expected_base_url):+ inputs = mock.MagicMock()+ inputs.schema_name = "runs"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-06-01T00:00:00Z"+ config = LangSmithSourceConfig(api_key="key", host=host)++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.source.langsmith_source"+ ) as langsmith_source:+ self.source.source_for_pipeline(config, mock.MagicMock(), inputs)++ _, kwargs = langsmith_source.call_args+ assert kwargs["endpoint"] == "runs"+ assert kwargs["base_url"] == expected_base_url+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-06-01T00:00:00Z"++ def test_source_for_pipeline_drops_incremental_value_on_full_refresh(self):+ inputs = mock.MagicMock()+ inputs.schema_name = "runs"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-06-01T00:00:00Z"++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.source.langsmith_source"+ ) as langsmith_source:+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ _, kwargs = langsmith_source.call_args+ # A stale watermark must not leak into a full-refresh run.+ assert kwargs["db_incremental_field_last_value"] is None++ def test_documented_tables_render_from_static_catalog(self):+ # lists_tables_without_credentials must expose the table catalog (+ canonical descriptions)+ # for the public docs <SourceTables /> component without needing credentials.+ assert self.source.lists_tables_without_credentials is True++ tables = {t["name"]: t for t in self.source.get_documented_tables()}++ assert set(tables) == {"runs", "projects", "datasets", "examples", "feedback", "annotation_queues"}+ assert all(t["description"] for t in tables.values())+ assert "Incremental" in tables["runs"]["sync_methods"]+ assert tables["datasets"]["sync_methods"] == ["Full refresh"]