Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(warehouse-sources): keep one oversized LangSmith run from stopping the table (#98633)

Daniel RC63fbb950d4a8
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.py
index 0872d82d670f..266cc9758f8f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/langsmith.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/langsmith.py
@@ -2,8 +2,9 @@ import re
import json
import hashlib
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime, timedelta
+from functools import partial
from typing import Any, Optional
from urllib.parse import urlencode, urlparse
@@ -21,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.settings import (
DEFAULT_BASE_URL,
LANGSMITH_ENDPOINTS,
+ RUNS_HEAVY_SELECT_FIELDS,
RUNS_SELECT_FIELDS,
LangSmithEndpointConfig,
)
@@ -43,6 +45,11 @@ REPEATED_CURSOR_ERROR = "LangSmith returned a repeated pagination cursor"
# is re-requested on every retry, so the cap is hit again deterministically — stop immediately.
RESPONSE_TOO_LARGE_ERROR = "LangSmith API returned an oversized response"
+# Raised (and registered non-retryable) when the host returns oversized pagination data: a cursor
+# past MAX_CURSOR_BYTES, or an id set past MAX_SESSION_IDS_BYTES / MAX_DATASET_IDS_BYTES while
+# scoping a query. Every retry walks the same pages and collects the same oversized data.
+PAGINATION_TOO_LARGE_ERROR = "LangSmith returned oversized pagination data"
+
# Raised (and registered non-retryable) when a single runs page stays over MAX_RESPONSE_BYTES even at
# the minimum limit. A page that big has runs with very large inputs/outputs; halving the page can't
# help below one run, so fail with guidance instead of retrying the same wall.
@@ -89,6 +96,11 @@ MAX_SESSION_IDS_BYTES = 2 * 1024 * 1024
# scope the examples query. A user-controlled host could otherwise stream unbounded dataset ids.
MAX_DATASET_IDS_BYTES = 2 * 1024 * 1024
+# Bound what one log line can carry out of a page. The host chooses how many runs it returns and
+# how long each id is, so an unbounded line lets it turn a warning into an oversized log event.
+MAX_LOGGED_RUN_IDS = 5
+MAX_LOGGED_RUN_ID_CHARS = 64
+
class LangSmithRetryableError(Exception):
pass
@@ -101,9 +113,25 @@ class LangSmithHostNotAllowedError(Exception):
class LangSmithResponseTooLargeError(Exception):
- """The host returned a body larger than `MAX_RESPONSE_BYTES` — refused before buffering it all."""
+ """The host returned a body larger than `MAX_RESPONSE_BYTES` — refused before buffering it all.
+
+ `get_non_retryable_errors` matches on message text, so the sentinel is prefixed here rather than
+ at the raise site: a message without it is retried for the whole activity budget.
+ """
+
+ def __init__(self, detail: str) -> None:
+ super().__init__(f"{RESPONSE_TOO_LARGE_ERROR}: {detail}")
- pass
+
+class LangSmithPaginationTooLargeError(Exception):
+ """The host returned oversized pagination data: a cursor, or the ids collected to scope a query.
+
+ Separate from `LangSmithResponseTooLargeError` because the runs page shrinker catches that one,
+ and shrinking a page cannot fix either of these limits. Same sentinel prefixing as above.
+ """
+
+ def __init__(self, detail: str) -> None:
+ super().__init__(f"{PAGINATION_TOO_LARGE_ERROR}: {detail}")
class LangSmithPageLimitError(Exception):
@@ -138,7 +166,7 @@ def _read_capped_body(response: requests.Response, cap: int = MAX_RESPONSE_BYTES
for chunk in response.iter_content(chunk_size=READ_CHUNK_BYTES):
buffer.extend(chunk)
if len(buffer) > cap:
- raise LangSmithResponseTooLargeError(f"{RESPONSE_TOO_LARGE_ERROR} (> {cap} bytes)")
+ raise LangSmithResponseTooLargeError(f"body over {cap} bytes")
return bytes(buffer)
@@ -362,6 +390,26 @@ def _fetch_page(
return json.loads(raw) if raw else None
+def _runs_select_fields(config: LangSmithEndpointConfig, enabled_columns: list[str] | None) -> list[str]:
+ """The `select` to send to runs/query for the columns the schema keeps.
+
+ MAX_RESPONSE_BYTES is enforced while the body is read, so a column the pipeline drops after the
+ fetch still costs its bytes on the wire. The primary key and the partition key are kept whatever
+ the user picked, because the merge and the Delta layout need them. `None` and an empty list mean
+ what they mean to `apply_enabled_columns_projection`: every column, and only the required ones.
+ """
+ if enabled_columns is None:
+ return list(RUNS_SELECT_FIELDS)
+ required = {*config.primary_keys, *([config.partition_key] if config.partition_key else [])}
+ wanted = {*enabled_columns} | required
+ return [name for name in RUNS_SELECT_FIELDS if name in wanted]
+
+
+def _bounded_run_ids(runs: list[Any]) -> list[str]:
+ """A sample of run ids, capped in count and length, for a log line."""
+ return [str(run.get("id"))[:MAX_LOGGED_RUN_ID_CHARS] for run in runs[:MAX_LOGGED_RUN_IDS] if isinstance(run, dict)]
+
+
def _fetch_runs_page(
session: requests.Session,
url: str,
@@ -376,19 +424,45 @@ def _fetch_runs_page(
A legitimate workspace with large prompt payloads can push a full page past MAX_RESPONSE_BYTES.
Halving the page and retrying the same cursor lets the sync move forward without skipping runs.
Returns the page data and the limit that fetched it, so the caller keeps the shrunk size for the
- next pages. Raises LangSmithRunsPageTooLargeError when even a single-run page is oversized.
+ next pages.
+
+ One run over the cap on its own cannot be halved further, so the last attempt re-requests it
+ without the heavy fields: the row lands with null inputs/outputs instead of ending the table.
+ That narrowed response is also the only way to learn the run id, because an oversized body is
+ refused before it can be parsed. Raises LangSmithRunsPageTooLargeError when it is oversized too.
"""
+ heavy_fields_dropped = False
while True:
page_body = {**body, "limit": limit}
+ if heavy_fields_dropped:
+ page_body["select"] = [name for name in body["select"] if name not in RUNS_HEAVY_SELECT_FIELDS]
if page_cursor:
page_body["cursor"] = page_cursor
try:
- return _fetch_page(session, url, headers, logger, json_body=page_body), limit
+ data = _fetch_page(session, url, headers, logger, json_body=page_body)
except LangSmithResponseTooLargeError:
- if limit <= MIN_RUNS_PAGE_SIZE:
+ if limit > MIN_RUNS_PAGE_SIZE:
+ limit = max(MIN_RUNS_PAGE_SIZE, limit // 2)
+ logger.warning(
+ f"LangSmith runs page exceeded the response cap; retrying same cursor with limit={limit}"
+ )
+ continue
+ if heavy_fields_dropped or not any(name in body["select"] for name in RUNS_HEAVY_SELECT_FIELDS):
raise LangSmithRunsPageTooLargeError(RUNS_PAGE_TOO_LARGE_ERROR)
- limit = max(MIN_RUNS_PAGE_SIZE, limit // 2)
- logger.warning(f"LangSmith runs page exceeded the response cap; retrying same cursor with limit={limit}")
+ heavy_fields_dropped = True
+ logger.warning(
+ "LangSmith run exceeded the response cap at the minimum page size; retrying the same cursor without "
+ f"{', '.join(RUNS_HEAVY_SELECT_FIELDS)}"
+ )
+ continue
+
+ if heavy_fields_dropped:
+ runs = data.get("runs", []) if isinstance(data, dict) else []
+ logger.warning(
+ f"LangSmith imported {len(runs)} run(s) without {', '.join(RUNS_HEAVY_SELECT_FIELDS)} because they "
+ f"exceeded the response cap: run_ids={_bounded_run_ids(runs)}"
+ )
+ return data, limit
def _list_session_ids(
@@ -421,9 +495,9 @@ def _list_session_ids(
ids.append(row_id)
ids_bytes += len(row_id.encode())
if ids_bytes > MAX_SESSION_IDS_BYTES:
- raise LangSmithResponseTooLargeError(
- f"LangSmith returned an oversized set of tracing-project ids "
- f"(> {MAX_SESSION_IDS_BYTES} bytes) while scoping the runs query"
+ raise LangSmithPaginationTooLargeError(
+ f"the set of tracing-project ids went over {MAX_SESSION_IDS_BYTES} bytes "
+ f"while scoping the runs query"
)
if len(rows) < config.page_size:
break
@@ -467,9 +541,8 @@ def _list_dataset_ids(
ids.append(row_id)
ids_bytes += len(row_id.encode())
if ids_bytes > MAX_DATASET_IDS_BYTES:
- raise LangSmithResponseTooLargeError(
- f"LangSmith returned an oversized set of dataset ids "
- f"(> {MAX_DATASET_IDS_BYTES} bytes) while scoping the examples query"
+ raise LangSmithPaginationTooLargeError(
+ f"the set of dataset ids went over {MAX_DATASET_IDS_BYTES} bytes while scoping the examples query"
)
if len(rows) < config.page_size:
break
@@ -532,6 +605,7 @@ def _get_runs_rows(
logger: FilteringBoundLogger,
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
+ select_fields: list[str],
) -> Iterator[Any]:
"""Page through POST /runs/query with the body cursor.
@@ -557,7 +631,7 @@ def _get_runs_rows(
return
body: dict[str, Any] = {
- "select": RUNS_SELECT_FIELDS,
+ "select": 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.
@@ -597,9 +671,7 @@ def _get_runs_rows(
# 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)"
- )
+ raise LangSmithPaginationTooLargeError(f"the runs cursor went over {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.
@@ -796,6 +868,7 @@ def get_rows(
team_id: int,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
+ enabled_columns: list[str] | None = None,
) -> Iterator[Any]:
config = LANGSMITH_ENDPOINTS[endpoint]
headers = _get_headers(api_key)
@@ -810,10 +883,12 @@ def get_rows(
# 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: Callable[..., Iterator[Any]]
if config.scoped_by_dataset:
pager = _get_examples_rows
elif config.pagination == "cursor":
- pager = _get_runs_rows
+ # Bound here because only runs has a server-side select to narrow.
+ pager = partial(_get_runs_rows, select_fields=_runs_select_fields(config, enabled_columns))
else:
pager = _get_offset_rows
yield from pager(
@@ -841,6 +916,7 @@ def langsmith_source(
team_id: int,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
+ enabled_columns: Optional[list[str]] = None,
) -> SourceResponse:
config = LANGSMITH_ENDPOINTS[endpoint]
@@ -855,6 +931,7 @@ def langsmith_source(
team_id=team_id,
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
+ enabled_columns=enabled_columns,
),
primary_keys=config.primary_keys,
sort_mode=config.sort_mode,
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.py
index 61b0396c4153..25d3f3a3f94c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langsmith/settings.py
@@ -39,6 +39,10 @@ RUNS_SELECT_FIELDS = [
"feedback_stats",
]
+# The fields holding a run's raw prompt and completion. They carry nearly all of a run's size, so
+# `_fetch_runs_page` gives them up as a last resort when one run stays over the response cap.
+RUNS_HEAVY_SELECT_FIELDS = ("inputs", "outputs")
+
@dataclass(frozen=False) # mutability is unused (always constructed fresh); explicit per house convention
class LangSmithEndpointConfig:
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.py
index 6c79a95c220c..b93b4e3954e5 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,4 +1,4 @@
-from typing import Optional, cast
+from typing import Any, Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.langsmith import (
DEFAULT_BASE_URL,
+ PAGINATION_TOO_LARGE_ERROR,
REPEATED_CURSOR_ERROR,
RESPONSE_TOO_LARGE_ERROR,
RETRYABLE_API_ERROR,
@@ -35,6 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.
ENDPOINTS,
INCREMENTAL_FIELDS,
LANGSMITH_ENDPOINTS,
+ RUNS_SELECT_FIELDS,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -109,6 +111,7 @@ Leave the **Host** field blank for the US cloud (`api.smith.langchain.com`). Set
"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.",
RESPONSE_TOO_LARGE_ERROR: "A page of data from the LangSmith API exceeded 256 MB. This usually means individual records contain very large inputs or outputs. Contact PostHog support for next steps.",
+ PAGINATION_TOO_LARGE_ERROR: "The LangSmith API returned more pagination data than PostHog can accept, so the import was stopped. This usually means the host is misconfigured. Check the Host field, then reconnect.",
RUNS_PAGE_TOO_LARGE_ERROR: "A single LangSmith trace was too large to import, so the runs sync stopped. This usually means one trace has an unusually large input or output. Contact support so we can help unblock the sync.",
}
@@ -152,6 +155,13 @@ Leave the **Host** field blank for the US cloud (`api.smith.langchain.com`). Set
return "Tracing projects (called sessions in the LangSmith API)"
return None
+ def _schema_metadata(endpoint: str) -> dict[str, Any] | None:
+ # Only runs has a fixed field list, so only runs can fill the column picker before it
+ # has ever synced. Every other endpoint returns whatever fields the API sends.
+ if endpoint != "runs":
+ return None
+ return {"columns": [{"name": name} for name in RUNS_SELECT_FIELDS]}
+
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))
@@ -162,6 +172,7 @@ Leave the **Host** field blank for the US cloud (`api.smith.langchain.com`). Set
incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
detected_primary_keys=endpoint_config.primary_keys,
description=_description(endpoint),
+ schema_metadata=_schema_metadata(endpoint),
)
schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
@@ -199,4 +210,7 @@ Leave the **Host** field blank for the US cloud (`api.smith.langchain.com`). Set
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
else None,
+ # The generic projection drops unselected columns after the fetch, which is too late for
+ # the response cap, so the runs endpoint also narrows its server-side `select`.
+ enabled_columns=inputs.enabled_columns,
)
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.py
index f0271a9d6850..4ff1bd1d0513 100644
--- 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.py
@@ -8,21 +8,27 @@ import structlog
from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.langsmith import (
MAX_CURSOR_BYTES,
+ MAX_LOGGED_RUN_ID_CHARS,
+ MAX_LOGGED_RUN_IDS,
LangSmithHostNotAllowedError,
LangSmithPageLimitError,
+ LangSmithPaginationTooLargeError,
LangSmithRepeatedCursorError,
LangSmithResponseTooLargeError,
LangSmithResumeConfig,
LangSmithRunsPageTooLargeError,
+ _bounded_run_ids,
_fetch_page,
_read_capped_body,
_resolve_window_start,
+ _runs_select_fields,
get_rows,
normalize_base_url,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.settings import (
LANGSMITH_ENDPOINTS,
+ RUNS_HEAVY_SELECT_FIELDS,
RUNS_SELECT_FIELDS,
)
@@ -269,18 +275,79 @@ class TestRunsPageShrinking:
assert [r["id"] for r in rows] == ["a"]
assert limits == [100, 50, 25] # halved on the same cursorless first page until it fits
- def test_single_run_page_still_oversized_raises(self):
- # If even a one-run page exceeds the cap, halving can't help; fail with the non-retryable
- # error instead of re-hitting the same wall until the activity timeout.
+ def test_single_oversized_run_is_imported_without_its_heavy_fields(self):
manager = FakeManager()
+ selects: list[list[str]] = []
def fake_fetch(session, url, headers, log, json_body=None):
+ selects.append(json_body["select"])
+ if any(name in json_body["select"] for name in RUNS_HEAVY_SELECT_FIELDS):
+ raise LangSmithResponseTooLargeError("oversized")
+ return {"runs": [_run("huge")], "cursors": {"next": None}}
+
+ with mock.patch(_FETCH_PAGE, side_effect=_with_session_page(fake_fetch)):
+ rows = _collect(get_rows("key", BASE_URL, "runs", logger, manager, 1)) # type: ignore[arg-type]
+
+ assert [r["id"] for r in rows] == ["huge"]
+ assert selects[-1] == [name for name in RUNS_SELECT_FIELDS if name not in RUNS_HEAVY_SELECT_FIELDS]
+
+ def test_logged_run_ids_are_bounded_in_count_and_length(self):
+ # The host chooses how many runs a page holds and how long each id is, so the warning that
+ # names them must not grow with the response.
+ runs = [{"id": "x" * 1_000} for _ in range(100)]
+
+ ids = _bounded_run_ids(runs)
+
+ assert len(ids) == MAX_LOGGED_RUN_IDS
+ assert all(len(run_id) == MAX_LOGGED_RUN_ID_CHARS for run_id in ids)
+
+ def test_single_run_page_oversized_without_heavy_fields_raises(self):
+ manager = FakeManager()
+ attempts = 0
+
+ def fake_fetch(session, url, headers, log, json_body=None):
+ nonlocal attempts
+ attempts += 1
raise LangSmithResponseTooLargeError("oversized")
with mock.patch(_FETCH_PAGE, side_effect=_with_session_page(fake_fetch)):
with pytest.raises(LangSmithRunsPageTooLargeError):
_collect(get_rows("key", BASE_URL, "runs", logger, manager, 1)) # type: ignore[arg-type]
+ # 100 -> 50 -> 25 -> 12 -> 6 -> 3 -> 1, then one narrowed attempt.
+ assert attempts == 8
+
+
+class TestRunsColumnSelection:
+ @pytest.mark.parametrize(
+ "enabled_columns,expected",
+ [
+ (None, RUNS_SELECT_FIELDS),
+ # An empty selection means what it means downstream: the required columns only, never
+ # everything. Otherwise deselecting every column still downloads inputs and outputs.
+ ([], ["id", "start_time"]),
+ # The primary key and the partition key ride along whatever the user picked.
+ (["outputs"], ["id", "start_time", "outputs"]),
+ (["id", "name"], ["id", "name", "start_time"]),
+ (["not_a_run_field"], ["id", "start_time"]),
+ ],
+ )
+ def test_select_keeps_the_columns_the_load_needs(self, enabled_columns, expected):
+ assert _runs_select_fields(LANGSMITH_ENDPOINTS["runs"], enabled_columns) == expected
+
+ def test_enabled_columns_narrow_the_request_body(self):
+ manager = FakeManager()
+ bodies: list[dict[str, Any]] = []
+
+ def fake_fetch(session, url, headers, log, json_body=None):
+ bodies.append(json_body)
+ return {"runs": [_run("a")], "cursors": {"next": None}}
+
+ with mock.patch(_FETCH_PAGE, side_effect=_with_session_page(fake_fetch)):
+ _collect(get_rows("key", BASE_URL, "runs", logger, manager, 1, enabled_columns=["name"])) # type: ignore[arg-type]
+
+ assert bodies[0]["select"] == ["id", "name", "start_time"]
+
class TestOffsetPagination:
def test_walks_offsets_until_short_page(self):
@@ -422,7 +489,7 @@ class TestPaginationAbuseGuards:
page_size = LANGSMITH_ENDPOINTS["projects"].page_size
with mock.patch(_FETCH_PAGE, return_value=[{"id": huge_id} for _ in range(page_size)]):
- with pytest.raises(LangSmithResponseTooLargeError):
+ with pytest.raises(LangSmithPaginationTooLargeError):
_collect(get_rows("key", BASE_URL, "runs", logger, manager, 1)) # type: ignore[arg-type]
def test_repeated_runs_cursor_raises(self):
@@ -447,7 +514,7 @@ class TestPaginationAbuseGuards:
return {"runs": [_run("a")], "cursors": {"next": big_cursor}}
with mock.patch(_FETCH_PAGE, side_effect=_with_session_page(fake_fetch)):
- with pytest.raises(LangSmithResponseTooLargeError):
+ with pytest.raises(LangSmithPaginationTooLargeError):
_collect(get_rows("key", BASE_URL, "runs", logger, manager, 1)) # type: ignore[arg-type]
def test_runs_page_limit_checkpoints_and_raises(self):
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.py
index 9a3de93212aa..e18664849b69 100644
--- 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.py
@@ -7,9 +7,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
LangSmithSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.langsmith import (
- RESPONSE_TOO_LARGE_ERROR,
RETRYABLE_API_ERROR,
+ LangSmithPaginationTooLargeError,
+ LangSmithResponseTooLargeError,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.settings import RUNS_SELECT_FIELDS
from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.source import LangSmithSource
@@ -52,6 +54,8 @@ class TestLangSmithSource:
assert schema.supports_incremental is expected_incremental
assert schema.supports_append is expected_incremental
assert schema.detected_primary_keys == ["id"]
+ expected_columns = [{"name": name} for name in RUNS_SELECT_FIELDS] if endpoint == "runs" else None
+ assert (schema.schema_metadata or {}).get("columns") == expected_columns
def test_validate_credentials_collapses_blank_host_and_forwards_team_id(self):
config = LangSmithSourceConfig(api_key="key", host="")
@@ -79,6 +83,7 @@ class TestLangSmithSource:
inputs.schema_name = "runs"
inputs.should_use_incremental_field = True
inputs.db_incremental_field_last_value = "2026-06-01T00:00:00Z"
+ inputs.enabled_columns = ["id", "start_time"]
config = LangSmithSourceConfig(api_key="key", host=host)
with mock.patch(
@@ -91,6 +96,7 @@ class TestLangSmithSource:
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"
+ assert kwargs["enabled_columns"] == ["id", "start_time"]
def test_source_for_pipeline_drops_incremental_value_on_full_refresh(self):
inputs = mock.MagicMock()
@@ -107,11 +113,17 @@ class TestLangSmithSource:
# A stale watermark must not leak into a full-refresh run.
assert kwargs["db_incremental_field_last_value"] is None
- def test_oversized_response_is_non_retryable(self):
- # Retrying an oversized page re-requests the same data and hits the same cap every time,
- # so the error must be registered as non-retryable to stop immediately.
- non_retryable = self.source.get_non_retryable_errors()
- assert any(RESPONSE_TOO_LARGE_ERROR in key for key in non_retryable)
+ @pytest.mark.parametrize(
+ "error",
+ [
+ LangSmithResponseTooLargeError("body over 100 bytes"),
+ LangSmithPaginationTooLargeError("the runs cursor went over 100 bytes"),
+ ],
+ )
+ def test_oversized_errors_are_classified_non_retryable(self, error):
+ # Classification matches on message text, so a raise site that adds its own detail must
+ # still carry the sentinel.
+ assert any(key in str(error) for key in self.source.get_non_retryable_errors())
def test_rejected_request_is_non_retryable(self):
# A 4xx means LangSmith rejected the request we built, so every retry re-sends the same