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): shrink LangSmith runs page on oversized response (#90879)

posthog[bot]c7d680937534
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 d023691d87b6..d6d8ce8f3fca 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
@@ -39,6 +39,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 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.
+RUNS_PAGE_TOO_LARGE_ERROR = "LangSmith runs page too large even at the minimum page size"
+
# 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
@@ -57,6 +62,11 @@ READ_CHUNK_BYTES = 64 * 1024
# hostile — reject it rather than echo it back in the next request body or hold it in memory.
MAX_CURSOR_BYTES = 8 * 1024
+# Smallest runs page we shrink to when a full page exceeds MAX_RESPONSE_BYTES. A single run still
+# carries full inputs/outputs, so one run per request is the floor; below it there is nothing left to
+# halve. See _fetch_runs_page.
+MIN_RUNS_PAGE_SIZE = 1
+
# 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
@@ -104,6 +114,13 @@ class LangSmithRepeatedCursorError(Exception):
pass
+class LangSmithRunsPageTooLargeError(Exception):
+ """A single runs page stayed over the cap at the minimum page size. Non-retryable — see
+ RUNS_PAGE_TOO_LARGE_ERROR."""
+
+ 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.
@@ -341,6 +358,35 @@ def _fetch_page(
return json.loads(raw) if raw else None
+def _fetch_runs_page(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ body: dict[str, Any],
+ page_cursor: str | None,
+ limit: int,
+) -> tuple[Any, int]:
+ """POST one runs page, halving `limit` and re-requesting the same cursor when the page is oversized.
+
+ 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.
+ """
+ while True:
+ page_body = {**body, "limit": limit}
+ if page_cursor:
+ page_body["cursor"] = page_cursor
+ try:
+ return _fetch_page(session, url, headers, logger, json_body=page_body), limit
+ except LangSmithResponseTooLargeError:
+ if limit <= MIN_RUNS_PAGE_SIZE:
+ 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}")
+
+
def _list_session_ids(
session: requests.Session,
headers: dict[str, str],
@@ -467,7 +513,6 @@ def _get_runs_rows(
return
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
@@ -483,10 +528,11 @@ def _get_runs_rows(
# grow this set without bound. A fixed-size digest is all cycle detection needs.
seen_cursors: set[bytes] = set()
pages = 0
+ # Shrinks (and stays shrunk) when a page trips MAX_RESPONSE_BYTES — see _fetch_runs_page.
+ limit = config.page_size
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)
+ data, limit = _fetch_runs_page(session, url, headers, logger, body, page_cursor, limit)
runs = data.get("runs", []) if isinstance(data, dict) else []
if not runs:
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 b9e48d612de0..4610c19c512d 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
@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.
DEFAULT_BASE_URL,
REPEATED_CURSOR_ERROR,
RESPONSE_TOO_LARGE_ERROR,
+ RUNS_PAGE_TOO_LARGE_ERROR,
LangSmithResumeConfig,
langsmith_source,
normalize_base_url,
@@ -100,8 +101,9 @@ Leave the **Host** field blank for the US cloud (`api.smith.langchain.com`). Set
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.",
- RESPONSE_TOO_LARGE_ERROR: "A page of runs data from the LangSmith API exceeded 256 MB. This usually means individual traces contain very large inputs or outputs. Contact PostHog support for next steps.",
+ 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.",
+ 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.",
}
def get_schemas(
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 ca82a968f8f8..f0271a9d6850 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
@@ -13,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.langsmith.
LangSmithRepeatedCursorError,
LangSmithResponseTooLargeError,
LangSmithResumeConfig,
+ LangSmithRunsPageTooLargeError,
_fetch_page,
_read_capped_body,
_resolve_window_start,
@@ -248,6 +249,39 @@ class TestRunsPagination:
assert manager.saved == [LangSmithResumeConfig(cursor=None, window_start=None)]
+class TestRunsPageShrinking:
+ def test_oversized_page_halves_limit_and_retries_same_cursor(self):
+ # A legitimate host with large prompt payloads can trip MAX_RESPONSE_BYTES on a full page.
+ # The walk must halve the limit and re-request the same cursor (skipping no runs), not fail.
+ manager = FakeManager()
+ limits: list[int] = []
+
+ def fake_fetch(session, url, headers, log, json_body=None):
+ limit = json_body["limit"]
+ limits.append(limit)
+ if limit > 25:
+ raise LangSmithResponseTooLargeError("oversized")
+ return {"runs": [_run("a")], "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] == ["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.
+ manager = FakeManager()
+
+ def fake_fetch(session, url, headers, log, json_body=None):
+ 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]
+
+
class TestOffsetPagination:
def test_walks_offsets_until_short_page(self):
manager = FakeManager()