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.

feat(warehouse-sources): add langsmith threads, workspaces and queue runs tables (#113907)

Tom Owers7790d5aee63e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 9fcd13ada01f..4a47eb4a1e5d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -4989,10 +4989,10 @@ Today (6): `annotation_queues`, `datasets`, `examples`, `feedback`, `projects`,
Diffed against: <https://api.smith.langchain.com/openapi.json>
-- [ ] `POST /v2/threads/query (and /v2/threads/{thread_id}/stats)` — thread-level grouping of runs, the unit conversational agent quality is measured on (high)
-- [ ] `GET /api/v1/workspaces (and /api/v1/tenants)` — lookup resolving the tenant/workspace id carried on every session, dataset and run (high)
-- [ ] `GET /api/v1/annotation-queues/{queue_id}/runs` — the membership junction between annotation_queues and runs; queues are synced but their contents are not (high)
-- [ ] `GET /v2/datasets/{dataset_id}/experiment-runs` — experiment results per dataset, the core evaluation output (high)
+- [x] `POST /v2/threads/query (and /v2/threads/{thread_id}/stats)` — thread-level grouping of runs, the unit conversational agent quality is measured on (high) — synced as `threads`; the query already returns each thread's stats, so the per-thread stats call is not used
+- [x] `GET /api/v1/workspaces (and /api/v1/tenants)` — lookup resolving the tenant/workspace id carried on every session, dataset and run (high) — synced as `workspaces`; `/tenants` returns the same list and can create a personal workspace when called, so it is not used
+- [x] `GET /api/v1/annotation-queues/{queue_id}/runs` — the membership junction between annotation_queues and runs; queues are synced but their contents are not (high) — synced as `annotation_queue_runs`
+- ~~`GET /v2/datasets/{dataset_id}/experiment-runs`~~ — not a separate table: it is a POST that needs the experiment ids up front and returns each dataset example with its experiment runs nested inside. Experiments are tracing projects, so their runs already land in `runs` (with `session_id` and `reference_example_id`) and their examples in `examples`; this endpoint only joins the two (high)
- [ ] `GET /api/v1/model-price-map` — lookup mapping model names on runs to token prices, so run cost can be recomputed (medium)
- [ ] `GET /api/v1/datasets/{dataset_id}/versions and /splits` — dataset version history and split assignment, needed to compare experiments fairly (medium)
- [ ] `GET /api/v1/orgs/current/members and /api/v1/workspaces/current/members` — membership tables resolving the user ids that appear on feedback and annotations (medium)
diff --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.py
index 528e021d235c..8f5df918a679 100644
--- 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.py
@@ -131,4 +131,58 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"tenant_id": "Id of the workspace the queue belongs to.",
},
},
+ "annotation_queue_runs": {
+ "description": "Runs added to each annotation queue, with the queue item's review state. Joins annotation_queues to runs.",
+ "docs_url": "https://docs.smith.langchain.com/evaluation/how_to_guides/annotation_queues",
+ "columns": {
+ "queue_id": "Id of the annotation queue the run is in.",
+ "queue_run_id": "Unique identifier (UUID) for the run's item in the queue.",
+ "id": "Id of the queued run.",
+ "added_at": "When the run was added to the queue.",
+ "last_reviewed_time": "When a reviewer last reviewed the queued run.",
+ "reserved_by": "Reviewers currently holding a reservation on the queued run.",
+ "completed_by": "Reviewers who completed their review of the queued run.",
+ "session_id": "Id of the tracing project (session) the run belongs to.",
+ "trace_id": "Id of the trace (root run) the run belongs to.",
+ },
+ },
+ "threads": {
+ "description": (
+ "Conversation threads in each tracing project. Each row is one thread, with turn counts, token "
+ "usage, cost, latency, and errors rolled up over the traces that started in the last 365 days."
+ ),
+ "docs_url": "https://docs.smith.langchain.com/observability/how_to_guides/threads",
+ "columns": {
+ "project_id": "Id of the tracing project (session) the thread belongs to.",
+ "thread_id": "Id of the thread within its tracing project.",
+ "count": "Number of root traces (conversation turns) in the thread within the window.",
+ "min_start_time": "Start time of the earliest trace in the thread within the window.",
+ "max_start_time": "Start time of the latest trace in the thread within the window.",
+ "first_trace_id": "Id of the first trace in the thread within the window.",
+ "last_trace_id": "Id of the last trace in the thread within the window.",
+ "first_inputs": "Truncated preview of the inputs of the first trace in the thread.",
+ "last_outputs": "Truncated preview of the outputs of the last trace in the thread.",
+ "last_error": "Short summary of the most recent error in the thread, if any.",
+ "num_errored_turns": "Number of root traces in the thread that ended in an error.",
+ "total_tokens": "Total tokens used across the thread's traces.",
+ "total_cost": "Total estimated cost of the thread's traces in USD.",
+ "latency_p50": "Approximate median end-to-end latency of the thread's traces, in seconds.",
+ "latency_p99": "Approximate 99th percentile end-to-end latency of the thread's traces, in seconds.",
+ "feedback_stats": "Aggregated feedback across the thread's traces, keyed by feedback key.",
+ },
+ },
+ "workspaces": {
+ "description": "Workspaces (called tenants in the LangSmith API) the API key can access. Resolves the tenant_id on other tables.",
+ "docs_url": "https://docs.smith.langchain.com/administration/concepts#workspaces",
+ "columns": {
+ "id": "Unique identifier (UUID) for the workspace. Matches tenant_id on other tables.",
+ "organization_id": "Id of the organization the workspace belongs to.",
+ "created_at": "When the workspace was created.",
+ "display_name": "Name of the workspace.",
+ "is_personal": "Whether this is a personal workspace.",
+ "is_deleted": "Whether the workspace is deleted.",
+ "tenant_handle": "Short handle of the workspace, if set.",
+ "role_name": "Role the API key's identity holds in the workspace.",
+ },
+ },
}
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 b2aff6fbdf6b..2bb0b2cc0e55 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
@@ -6,7 +6,7 @@ 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
+from urllib.parse import quote, urlencode, urlparse
import requests
from structlog.types import FilteringBoundLogger
@@ -49,8 +49,7 @@ REPEATED_CURSOR_ERROR = "LangSmith returned a repeated pagination cursor"
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.
+# past MAX_CURSOR_BYTES, or an id set past MAX_PARENT_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
@@ -88,16 +87,12 @@ MIN_RUNS_PAGE_SIZE = 1
# make hitting this in one attempt take days.
MAX_PAGES_PER_RUN = 50_000
-# Cap the total bytes of session ids accumulated while scoping the runs query. `host` is
-# user-controlled and returns arbitrary `id` strings on every project page, so without a cumulative
-# cap a host could return unboundedly many (or oversized) ids across thousands of pages — well
-# before MAX_PAGES_PER_RUN trips — and exhaust a shared import worker's memory. ~58k real UUIDs'
-# worth, far beyond any legitimate workspace's tracing-project count.
-MAX_SESSION_IDS_BYTES = 2 * 1024 * 1024
-
-# Same cumulative-memory guard as MAX_SESSION_IDS_BYTES, applied to the dataset ids collected to
-# scope the examples query. A user-controlled host could otherwise stream unbounded dataset ids.
-MAX_DATASET_IDS_BYTES = 2 * 1024 * 1024
+# Cap the total bytes of parent ids (projects, datasets, annotation queues) accumulated while scoping
+# a query. `host` is user-controlled and returns arbitrary `id` strings on every listing page, so
+# without a cumulative cap a host could return unboundedly many (or oversized) ids across thousands
+# of pages — well before MAX_PAGES_PER_RUN trips — and exhaust a shared import worker's memory. ~58k
+# real UUIDs' worth, far beyond any legitimate workspace's count.
+MAX_PARENT_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.
@@ -183,9 +178,10 @@ class LangSmithResumeConfig:
# resumed run keeps paging the same window (a recomputed bound would shift what each
# cursor/offset points at).
window_start: str | None = None
- # Dataset being paged when an examples run was interrupted; examples are fetched per dataset,
- # so the resume needs both which dataset and the offset within it. None for every other endpoint.
- dataset_id: str | None = None
+ # Parent (dataset, annotation queue, or project) being paged when a parent-scoped run was
+ # interrupted, so the resume needs both which parent and the offset or cursor within it. None for
+ # every other endpoint.
+ parent_id: str | None = None
def normalize_base_url(raw: str) -> str:
@@ -492,25 +488,28 @@ def _fetch_runs_page(
return data, limit
-def _list_session_ids(
+def _list_parent_ids(
session: requests.Session,
headers: dict[str, str],
base_url: str,
logger: FilteringBoundLogger,
+ parent_name: str,
+ child_name: str,
+ params: dict[str, Any] | None = None,
) -> list[str]:
- """Collect every tracing-project (session) id in the workspace.
+ """Collect every id of the `parent_name` endpoint in the workspace.
- runs/query rejects a request that doesn't scope to at least one of session/id/parent_run/
- trace/reference_example; this sync pulls runs across every project, so it scopes by every
- session id in the workspace instead of narrowing to one.
+ runs/query rejects a request that doesn't scope to at least one session, GET /examples one that
+ doesn't scope to a dataset, and threads and annotation-queue runs are listed per project or per
+ queue. These syncs cover the whole workspace, so they scope by every parent id instead.
"""
- config = LANGSMITH_ENDPOINTS["projects"]
+ parent = LANGSMITH_ENDPOINTS[parent_name]
ids: list[str] = []
ids_bytes = 0
offset = 0
pages = 0
while True:
- url = f"{base_url}{config.path}?{urlencode({'limit': config.page_size, 'offset': offset})}"
+ url = f"{base_url}{parent.path}?{urlencode({**(params or {}), 'limit': parent.page_size, 'offset': offset})}"
data = _fetch_page(session, url, headers, logger)
rows = data if isinstance(data, list) else []
if not rows:
@@ -521,65 +520,54 @@ def _list_session_ids(
continue
ids.append(row_id)
ids_bytes += len(row_id.encode())
- if ids_bytes > MAX_SESSION_IDS_BYTES:
+ if ids_bytes > MAX_PARENT_IDS_BYTES:
raise LangSmithPaginationTooLargeError(
- f"the set of tracing-project ids went over {MAX_SESSION_IDS_BYTES} bytes "
- f"while scoping the runs query"
+ f"the set of {parent_name} ids went over {MAX_PARENT_IDS_BYTES} bytes "
+ f"while scoping the {child_name} query"
)
- if len(rows) < config.page_size:
+ if len(rows) < parent.page_size:
break
- offset += config.page_size
+ offset += parent.page_size
# Same hostile-host guard as the other paginators: a host returning a full page forever
# must not hold the worker until the activity timeout.
pages += 1
if pages >= MAX_PAGES_PER_RUN:
raise LangSmithPageLimitError(
- f"LangSmith session listing hit the {MAX_PAGES_PER_RUN}-page limit while scoping the runs query"
+ f"LangSmith {parent_name} listing hit the {MAX_PAGES_PER_RUN}-page limit while scoping the {child_name} query"
)
return ids
-def _list_dataset_ids(
- session: requests.Session,
- headers: dict[str, str],
- base_url: str,
- logger: FilteringBoundLogger,
-) -> list[str]:
- """Collect every dataset id in the workspace.
+def _check_next_cursor(next_cursor: str, page_cursor: str | None, seen_cursors: set[bytes], endpoint: str) -> None:
+ """Reject a cursor that is absurdly large or that loops, before it's echoed back or remembered.
- GET /examples requires a `dataset` filter (a 400 otherwise); this sync pulls examples across
- every dataset, so it lists dataset ids and pages each dataset's examples in turn.
+ `seen_cursors` holds 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 the set without bound. A fixed-size digest is all cycle detection needs.
"""
- config = LANGSMITH_ENDPOINTS["datasets"]
- ids: list[str] = []
- ids_bytes = 0
- offset = 0
- pages = 0
- while True:
- url = f"{base_url}{config.path}?{urlencode({'limit': config.page_size, 'offset': offset})}"
- data = _fetch_page(session, url, headers, logger)
- rows = data if isinstance(data, list) else []
- if not rows:
- break
- for row in rows:
- row_id = row.get("id")
- if not row_id:
- continue
- ids.append(row_id)
- ids_bytes += len(row_id.encode())
- if ids_bytes > MAX_DATASET_IDS_BYTES:
- 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
- offset += config.page_size
- pages += 1
- if pages >= MAX_PAGES_PER_RUN:
- raise LangSmithPageLimitError(
- f"LangSmith dataset listing hit the {MAX_PAGES_PER_RUN}-page limit while scoping the examples query"
- )
- return ids
+ if len(next_cursor.encode()) > MAX_CURSOR_BYTES:
+ raise LangSmithPaginationTooLargeError(f"the {endpoint} 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.
+ 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)
+
+
+def _shape_rows(config: LangSmithEndpointConfig, rows: list[Any], parent_id: str) -> list[Any]:
+ if not config.parent_id_field and not config.dropped_fields:
+ return rows
+ shaped: list[Any] = []
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ shaped_row = {key: value for key, value in row.items() if key not in config.dropped_fields}
+ if config.parent_id_field:
+ shaped_row[config.parent_id_field] = parent_id
+ shaped.append(shaped_row)
+ return shaped
def _emit_batches(
@@ -654,7 +642,7 @@ def _get_runs_rows(
# runs/query requires at least one of session/id/parent_run/trace/reference_example in the
# body (a 400 otherwise) — there's no such thing as an unscoped query across a workspace.
- session_ids = _list_session_ids(session, headers, base_url, logger)
+ session_ids = _list_parent_ids(session, headers, base_url, logger, "projects", config.name)
if not session_ids:
logger.debug("LangSmith: no tracing projects in workspace, nothing to sync for runs")
return
@@ -670,9 +658,6 @@ def _get_runs_rows(
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
# Shrinks (and stays shrunk) when a page trips MAX_RESPONSE_BYTES — see _fetch_runs_page.
@@ -698,16 +683,7 @@ def _get_runs_rows(
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 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.
- 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)
+ _check_next_cursor(next_cursor, page_cursor, seen_cursors, config.name)
pages += 1
if pages >= MAX_PAGES_PER_RUN:
@@ -783,38 +759,30 @@ def _get_offset_rows(
)
-def _examples_start_position(
+def _parent_start_position(
resumable_source_manager: ResumableSourceManager[LangSmithResumeConfig],
- dataset_ids: list[str],
+ parent_ids: list[str],
logger: FilteringBoundLogger,
-) -> tuple[int, int | None]:
- """Return the dataset index an interrupted examples run picks back up at, and the offset within
- that dataset. The offset is None when there is no usable checkpoint and the sweep starts over.
+) -> tuple[int, LangSmithResumeConfig | None]:
+ """Return the parent index an interrupted parent-scoped run picks back up at, and the saved state
+ holding the position within that parent. The state is None when there is no usable checkpoint
+ and the sweep starts over.
"""
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- # Only resume into a dataset that still exists; a deleted one restarts the sweep from the top
- # so no dataset is silently skipped.
- if resume is None or resume.dataset_id not in dataset_ids:
+ # Only resume into a parent that still exists; a deleted one restarts the sweep from the top
+ # so no parent is silently skipped.
+ if resume is None or resume.parent_id not in parent_ids:
return 0, None
- logger.debug(f"LangSmith: resuming examples from dataset={resume.dataset_id} offset={resume.offset}")
- return dataset_ids.index(resume.dataset_id), resume.offset or 0
+ logger.debug(f"LangSmith: resuming from parent={resume.parent_id} offset={resume.offset} cursor={resume.cursor}")
+ return parent_ids.index(resume.parent_id), resume
-def _examples_resume_state(
- dataset_ids: list[str],
- index: int,
- next_offset: int,
- *,
- is_last_page: bool,
-) -> LangSmithResumeConfig:
- """Where an examples run resumes from once it hits the per-attempt page cap."""
- if is_last_page:
- # This dataset is exhausted; resume picks up at the start of the next one.
- return LangSmithResumeConfig(dataset_id=dataset_ids[index + 1], offset=0)
- return LangSmithResumeConfig(dataset_id=dataset_ids[index], offset=next_offset)
+def _parent_url(base_url: str, config: LangSmithEndpointConfig, parent_id: str) -> str:
+ # Parent ids come from the user-controlled host, so encode them before they enter the path.
+ return f"{base_url}{config.path.replace('{parent_id}', quote(parent_id, safe=''))}"
-def _get_examples_rows(
+def _get_parent_scoped_rows(
session: requests.Session,
headers: dict[str, str],
base_url: str,
@@ -825,64 +793,73 @@ def _get_examples_rows(
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
) -> Iterator[Any]:
- """Page GET /examples for every dataset in the workspace.
-
- Examples belong to a dataset, and GET /examples rejects a request that doesn't scope to one
- (a 400 otherwise), so this walks each dataset id and pages that dataset's examples with a
- `dataset` filter. Examples are full-refresh only (no server-side window), so there's no
- incremental watermark to pin — the resume tracks which dataset and offset an interrupted run
- was on."""
- dataset_ids = _list_dataset_ids(session, headers, base_url, logger)
- if not dataset_ids:
- logger.debug("LangSmith: no datasets in workspace, nothing to sync for examples")
+ """Page an offset/limit GET endpoint once for every parent id in the workspace.
+
+ GET /examples rejects a request that doesn't scope to a dataset (a 400 otherwise), and
+ annotation-queue runs are only listed per queue, so this walks each parent id and pages its rows.
+ These endpoints are full-refresh only (no server-side window), so there's no incremental
+ watermark to pin — the resume tracks which parent and offset an interrupted run was on."""
+ assert config.parent is not None
+ parent_ids = _list_parent_ids(
+ session, headers, base_url, logger, config.parent, config.name, config.parent_list_params
+ )
+ if not parent_ids:
+ logger.debug(f"LangSmith: no {config.parent} in workspace, nothing to sync for {config.name}")
return
- start_index, resume_offset = _examples_start_position(resumable_source_manager, dataset_ids, logger)
+ start_index, resume = _parent_start_position(resumable_source_manager, parent_ids, logger)
pages = 0
- dataset_checkpoint = BoundaryCheckpoint(batcher, resumable_source_manager)
- for index in range(start_index, len(dataset_ids)):
- dataset_id = dataset_ids[index]
- is_last_dataset = index == len(dataset_ids) - 1
- if index == start_index and resume_offset is not None:
- offset = resume_offset
+ parent_checkpoint = BoundaryCheckpoint(batcher, resumable_source_manager)
+ for index in range(start_index, len(parent_ids)):
+ parent_id = parent_ids[index]
+ is_last_parent = index == len(parent_ids) - 1
+ if index == start_index and resume is not None:
+ offset = resume.offset or 0
else:
offset = 0
- # Checkpoint the dataset boundary before reading it, so a crash resumes at this dataset
- # rather than re-reading the previous one. The batcher can hold examples of the previous
- # dataset, and a checkpoint at this dataset skips them.
- yield from dataset_checkpoint.save(LangSmithResumeConfig(dataset_id=dataset_id, offset=0))
+ # Checkpoint the parent boundary before reading it, so a crash resumes at this parent
+ # rather than re-reading the previous one. The batcher can hold rows of the previous
+ # parent, and a checkpoint at this parent skips them.
+ yield from parent_checkpoint.save(LangSmithResumeConfig(parent_id=parent_id, offset=0))
while True:
page_offset = offset
- url = f"{base_url}{config.path}?{urlencode({'dataset': dataset_id, 'limit': config.page_size, 'offset': page_offset})}"
+ params: dict[str, Any] = {"limit": config.page_size, "offset": page_offset}
+ if config.parent_query_param:
+ params = {config.parent_query_param: parent_id, **params}
+ url = f"{_parent_url(base_url, config, parent_id)}?{urlencode(params)}"
data = _fetch_page(session, url, headers, logger)
# Count every request, including a short first page, against the per-run limit. A
- # dataset whose examples fit on one page must still cost one request — otherwise a
- # host serving many datasets (bounded only by MAX_DATASET_IDS_BYTES) each with a
- # single short page pages forever without ever tripping MAX_PAGES_PER_RUN.
+ # parent whose rows fit on one page must still cost one request — otherwise a host
+ # serving many parents (bounded only by MAX_PARENT_IDS_BYTES) each with a single short
+ # page pages forever without ever tripping MAX_PAGES_PER_RUN.
pages += 1
rows = data if isinstance(data, list) else []
is_last_page = not rows or len(rows) < config.page_size
- run_is_finished = is_last_page and is_last_dataset
+ run_is_finished = is_last_page and is_last_parent
yield from _emit_batches(
batcher,
- rows,
+ _shape_rows(config, rows, parent_id),
resumable_source_manager,
- LangSmithResumeConfig(dataset_id=dataset_id, offset=page_offset),
+ LangSmithResumeConfig(parent_id=parent_id, offset=page_offset),
is_final_page=run_is_finished,
)
if pages >= MAX_PAGES_PER_RUN and not run_is_finished:
+ next_state = (
+ # This parent is exhausted; resume picks up at the start of the next one.
+ LangSmithResumeConfig(parent_id=parent_ids[index + 1], offset=0)
+ if is_last_page
+ else LangSmithResumeConfig(parent_id=parent_id, offset=page_offset + config.page_size)
+ )
yield from _stop_at_page_limit(
batcher,
resumable_source_manager,
- _examples_resume_state(
- dataset_ids, index, page_offset + config.page_size, is_last_page=is_last_page
- ),
- f"LangSmith examples import hit the {MAX_PAGES_PER_RUN}-page per-attempt limit; resuming from checkpoint",
+ next_state,
+ f"LangSmith {config.name} import hit the {MAX_PAGES_PER_RUN}-page per-attempt limit; resuming from checkpoint",
)
if is_last_page:
@@ -890,6 +867,114 @@ def _get_examples_rows(
offset = page_offset + config.page_size
+def _get_threads_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 POST /v2/threads/query with the body cursor, once for every tracing project.
+
+ The query takes a single `project_id`, so this walks each project. The API defaults
+ `min_start_time` to one day ago, so the lookback is always sent, and a resume keeps the window
+ the interrupted run started with so its cursor still points into the same result set."""
+ assert config.parent is not None
+ project_ids = _list_parent_ids(
+ session, headers, base_url, logger, config.parent, config.name, config.parent_list_params
+ )
+ if not project_ids:
+ logger.debug(f"LangSmith: no tracing projects in workspace, nothing to sync for {config.name}")
+ return
+
+ start_index, resume = _parent_start_position(resumable_source_manager, project_ids, logger)
+ if resume is not None and resume.window_start:
+ window_start: str | None = resume.window_start
+ elif config.default_lookback_days:
+ window_start = _format_datetime(datetime.now(UTC) - timedelta(days=config.default_lookback_days))
+ else:
+ window_start = None
+
+ url = f"{base_url}{config.path}"
+ pages = 0
+ project_checkpoint = BoundaryCheckpoint(batcher, resumable_source_manager)
+ for index in range(start_index, len(project_ids)):
+ project_id = project_ids[index]
+ is_last_project = index == len(project_ids) - 1
+ if index == start_index and resume is not None:
+ cursor = resume.cursor
+ else:
+ cursor = None
+ yield from project_checkpoint.save(LangSmithResumeConfig(parent_id=project_id, window_start=window_start))
+
+ seen_cursors: set[bytes] = set()
+ while True:
+ page_cursor = cursor
+ body: dict[str, Any] = {"project_id": project_id, "page_size": config.page_size}
+ if window_start:
+ body["min_start_time"] = window_start
+ if page_cursor:
+ body["cursor"] = page_cursor
+ data = _fetch_page(session, url, headers, logger, json_body=body)
+ pages += 1
+
+ page = data if isinstance(data, dict) else {}
+ rows = page.get("items") if isinstance(page.get("items"), list) else []
+ next_cursor = page.get("next_cursor") or None
+ if next_cursor is not None:
+ _check_next_cursor(str(next_cursor), page_cursor, seen_cursors, config.name)
+ # A page can hold fewer threads than `page_size`, even none, before the last one, so only
+ # a missing cursor ends the project.
+ is_last_page = next_cursor is None
+
+ run_is_finished = is_last_page and is_last_project
+ yield from _emit_batches(
+ batcher,
+ _shape_rows(config, rows or [], project_id),
+ resumable_source_manager,
+ LangSmithResumeConfig(parent_id=project_id, cursor=page_cursor, window_start=window_start),
+ is_final_page=run_is_finished,
+ )
+
+ if pages >= MAX_PAGES_PER_RUN and not run_is_finished:
+ next_state = (
+ LangSmithResumeConfig(parent_id=project_ids[index + 1], window_start=window_start)
+ if is_last_page
+ else LangSmithResumeConfig(parent_id=project_id, cursor=str(next_cursor), window_start=window_start)
+ )
+ yield from _stop_at_page_limit(
+ batcher,
+ resumable_source_manager,
+ next_state,
+ f"LangSmith {config.name} import hit the {MAX_PAGES_PER_RUN}-page per-attempt limit; resuming from checkpoint",
+ )
+
+ if is_last_page:
+ break
+ cursor = str(next_cursor)
+
+
+def _get_single_page_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]:
+ """GET a list endpoint that returns every row in one unpaginated JSON array."""
+ data = _fetch_page(session, f"{base_url}{config.path}", headers, logger)
+ rows = data if isinstance(data, list) else []
+ yield from _emit_batches(batcher, rows, resumable_source_manager, LangSmithResumeConfig(), is_final_page=True)
+
+
def get_rows(
api_key: str,
base_url: str,
@@ -915,8 +1000,12 @@ def get_rows(
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
+ if config.pagination == "none":
+ pager = _get_single_page_rows
+ elif config.pagination == "cursor" and config.parent:
+ pager = _get_threads_rows
+ elif config.parent:
+ pager = _get_parent_scoped_rows
elif config.pagination == "cursor":
# 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))
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 25d3f3a3f94c..96994d3d09a5 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
@@ -1,6 +1,6 @@
from dataclasses import dataclass, field
from datetime import timedelta
-from typing import Literal, Optional
+from typing import Any, Literal, Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -39,6 +39,18 @@ RUNS_SELECT_FIELDS = [
"feedback_stats",
]
+# Run internals the annotation-queue runs listing returns but `RUNS_SELECT_FIELDS` leaves out of the
+# runs table: serialized manifests, event streams, and pre-signed S3 URLs that expire anyway.
+ANNOTATION_QUEUE_RUNS_DROPPED_FIELDS = (
+ "serialized",
+ "manifest_id",
+ "manifest_s3_id",
+ "events",
+ "inputs_s3_urls",
+ "outputs_s3_urls",
+ "s3_urls",
+)
+
# 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")
@@ -49,9 +61,9 @@ 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"
+ # runs/query and threads/query are POSTs whose cursor lives in the JSON body, workspaces is one
+ # unpaginated GET, and every other list endpoint is a GET paginated with offset/limit params.
+ pagination: Literal["cursor", "offset", "none"] = "offset"
# Stable creation-style timestamp to partition by (never a mutable `modified_at` field).
partition_key: Optional[str] = None
page_size: int = 100
@@ -61,7 +73,8 @@ class LangSmithEndpointConfig:
# 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.
+ # window, bounding the initial pull against the tight runs/query rate limits. On threads it is
+ # the fixed window of every full refresh, because the API otherwise defaults to the last day.
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
@@ -73,9 +86,17 @@ class LangSmithEndpointConfig:
# 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"
- # GET /examples rejects an unscoped request — examples belong to a dataset — so it's paged per
- # dataset with a `dataset` filter instead of the plain offset paginator. Only examples sets this.
- scoped_by_dataset: bool = False
+ # Endpoint whose ids scope this one. Examples and annotation-queue runs can only be listed per
+ # dataset or per queue, and threads only per tracing project, so they are paged once per parent.
+ parent: Optional[str] = None
+ # Query param that carries the parent id. None puts it in the `{parent_id}` placeholder of `path`.
+ parent_query_param: Optional[str] = None
+ # Row field the parent id is written to, for endpoints whose rows don't carry it themselves.
+ parent_id_field: Optional[str] = None
+ # Extra query params for listing the parent ids.
+ parent_list_params: dict[str, Any] = field(default_factory=dict)
+ # Fields removed from every row before it is yielded.
+ dropped_fields: tuple[str, ...] = ()
_START_TIME_INCREMENTAL_FIELDS: list[IncrementalField] = [
@@ -126,13 +147,14 @@ LANGSMITH_ENDPOINTS: dict[str, LangSmithEndpointConfig] = {
incremental_fields=[],
),
# Dataset examples across all datasets. GET /examples must be scoped to a dataset, so this is
- # paged per dataset (see `scoped_by_dataset`). The API versions examples via `as_of` snapshots
+ # paged per dataset (see `parent`). 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=[],
- scoped_by_dataset=True,
+ parent="datasets",
+ parent_query_param="dataset",
),
# 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
@@ -152,6 +174,40 @@ LANGSMITH_ENDPOINTS: dict[str, LangSmithEndpointConfig] = {
path="/api/v1/annotation-queues",
incremental_fields=[],
),
+ # Which runs sit in which annotation queue, with each item's review state. The listing has no
+ # time filter, so full refresh only.
+ "annotation_queue_runs": LangSmithEndpointConfig(
+ name="annotation_queue_runs",
+ path="/api/v1/annotation-queues/{parent_id}/runs",
+ incremental_fields=[],
+ parent="annotation_queues",
+ parent_id_field="queue_id",
+ primary_keys=["queue_id", "queue_run_id"],
+ dropped_fields=ANNOTATION_QUEUE_RUNS_DROPPED_FIELDS,
+ ),
+ # Conversation threads per tracing project, with turn counts, token, cost, and latency rolled
+ # up over the query window. The rollups only cover the window sent, so an incremental window
+ # would overwrite a thread's totals with partial ones: full refresh over a fixed lookback.
+ "threads": LangSmithEndpointConfig(
+ name="threads",
+ path="/api/v2/threads/query",
+ pagination="cursor",
+ incremental_fields=[],
+ parent="projects",
+ parent_id_field="project_id",
+ # Experiments are tracing projects too, but hold evaluation runs, not conversations.
+ parent_list_params={"reference_free": "true"},
+ primary_keys=["project_id", "thread_id"],
+ default_lookback_days=365,
+ ),
+ # Workspaces the API key can see. Resolves the `tenant_id` carried on queues, datasets, and
+ # projects. GET /workspaces returns them all in one unpaginated list.
+ "workspaces": LangSmithEndpointConfig(
+ name="workspaces",
+ path="/api/v1/workspaces",
+ pagination="none",
+ incremental_fields=[],
+ ),
}
ENDPOINTS = tuple(LANGSMITH_ENDPOINTS.keys())
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 3ec8f87fc8d5..94496d1c95d5 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
@@ -151,6 +151,8 @@ Leave the **Host** field blank for the US cloud (`api.smith.langchain.com`). Set
)
if endpoint == "projects":
return "Tracing projects (called sessions in the LangSmith API)"
+ if endpoint == "threads":
+ return "Conversation threads in each tracing project, with stats over the last 365 days"
return None
def _schema_metadata(endpoint: str) -> dict[str, Any] | 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.py
index a147e1827bc1..add1d95ebdfd 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
@@ -296,7 +296,7 @@ class TestExamplesPagination:
def test_resume_continues_from_saved_dataset_and_offset(self):
# A resumed run skips datasets already fully read, picks the interrupted dataset up at its
# saved offset, and reads the remaining datasets from the start.
- manager = FakeManager(resume=LangSmithResumeConfig(dataset_id="ds-2", offset=100))
+ manager = FakeManager(resume=LangSmithResumeConfig(parent_id="ds-2", offset=100))
dataset_ids = ["ds-1", "ds-2", "ds-3"]
example_urls: list[str] = []
@@ -317,7 +317,7 @@ class TestExamplesPagination:
def test_many_short_pages_still_hit_the_page_limit(self):
# A dataset whose examples fit on a single short page must still cost one request against
# MAX_PAGES_PER_RUN. Otherwise a host serving many datasets (bounded only by
- # MAX_DATASET_IDS_BYTES), each with one short page, could page forever without ever
+ # MAX_PARENT_IDS_BYTES), each with one short page, could page forever without ever
# tripping the per-run limit.
manager = FakeManager()
dataset_ids = [f"ds-{i}" for i in range(10)]
@@ -334,10 +334,95 @@ class TestExamplesPagination:
_collect(get_rows("key", BASE_URL, "examples", logger, manager, 1)) # type: ignore[arg-type]
assert len(example_urls) == 3
- assert manager.saved[-1].dataset_id == "ds-3"
+ assert manager.saved[-1].parent_id == "ds-3"
assert manager.saved[-1].offset == 0
+class TestAnnotationQueueRunsPagination:
+ def test_pages_each_queue_and_tags_rows_with_the_queue(self):
+ manager = FakeManager()
+ urls: list[str] = []
+
+ def fake_fetch(session, url, headers, log, json_body=None):
+ urls.append(url)
+ if "/runs" in url:
+ return [{"id": "run-1", "queue_run_id": "qr-1", "name": "chain", "s3_urls": {"a": "signed"}}]
+ return [{"id": "queue/1"}]
+
+ with mock.patch(_FETCH_PAGE, side_effect=fake_fetch):
+ rows = _collect(get_rows("key", BASE_URL, "annotation_queue_runs", logger, manager, 1)) # type: ignore[arg-type]
+
+ # The queue id comes from the host, so it must be encoded rather than extend the path.
+ assert urls[1].startswith(f"{BASE_URL}/api/v1/annotation-queues/queue%2F1/runs?")
+ assert rows == [{"id": "run-1", "queue_run_id": "qr-1", "name": "chain", "queue_id": "queue/1"}]
+
+
+class TestThreadsPagination:
+ def test_walks_every_project_with_cursor_and_fixed_window(self):
+ manager = FakeManager()
+ list_urls: list[str] = []
+ bodies: list[dict[str, Any]] = []
+ pages = {
+ ("p-1", None): {"items": [{"thread_id": "t-1"}], "next_cursor": "c-1"},
+ # A page can be empty before the last one; only a missing cursor ends the project.
+ ("p-1", "c-1"): {"items": [], "next_cursor": "c-2"},
+ ("p-1", "c-2"): {"items": [{"thread_id": "t-2"}], "next_cursor": None},
+ ("p-2", None): {"items": [{"thread_id": "t-1"}]},
+ }
+
+ def fake_fetch(session, url, headers, log, json_body=None):
+ if json_body is None:
+ list_urls.append(url)
+ return [{"id": "p-1"}, {"id": "p-2"}]
+ bodies.append(json_body)
+ return pages[(json_body["project_id"], json_body.get("cursor"))]
+
+ with mock.patch(_FETCH_PAGE, side_effect=fake_fetch):
+ rows = _collect(get_rows("key", BASE_URL, "threads", logger, manager, 1)) # type: ignore[arg-type]
+
+ assert "reference_free=true" in list_urls[0]
+ assert [(r["project_id"], r["thread_id"]) for r in rows] == [("p-1", "t-1"), ("p-1", "t-2"), ("p-2", "t-1")]
+ assert len(bodies) == 4
+ window_start = bodies[0]["min_start_time"]
+ assert all(body["min_start_time"] == window_start for body in bodies)
+ lookback = datetime.now(UTC) - datetime.fromisoformat(window_start.replace("Z", "+00:00"))
+ assert lookback.days == pytest.approx(LANGSMITH_ENDPOINTS["threads"].default_lookback_days, abs=1)
+
+ def test_resume_continues_from_saved_project_cursor_and_window(self):
+ window_start = "2026-01-01T00:00:00.000000Z"
+ manager = FakeManager(resume=LangSmithResumeConfig(parent_id="p-2", cursor="c-5", window_start=window_start))
+ bodies: list[dict[str, Any]] = []
+
+ def fake_fetch(session, url, headers, log, json_body=None):
+ if json_body is None:
+ return [{"id": "p-1"}, {"id": "p-2"}, {"id": "p-3"}]
+ bodies.append(json_body)
+ return {"items": [{"thread_id": "t"}]}
+
+ with mock.patch(_FETCH_PAGE, side_effect=fake_fetch):
+ _collect(get_rows("key", BASE_URL, "threads", logger, manager, 1)) # type: ignore[arg-type]
+
+ assert [(b["project_id"], b.get("cursor"), b["min_start_time"]) for b in bodies] == [
+ ("p-2", "c-5", window_start),
+ ("p-3", None, window_start),
+ ]
+
+
+class TestWorkspaces:
+ def test_full_list_is_fetched_once(self):
+ # GET /workspaces ignores limit/offset, so treating a full list as a full offset page would
+ # fetch the same workspaces again and again.
+ manager = FakeManager()
+ workspaces = [{"id": f"w{i}"} for i in range(LANGSMITH_ENDPOINTS["projects"].page_size)]
+
+ with mock.patch(_FETCH_PAGE, return_value=workspaces) as fetch:
+ rows = _collect(get_rows("key", BASE_URL, "workspaces", logger, manager, 1)) # type: ignore[arg-type]
+
+ assert fetch.call_count == 1
+ assert fetch.call_args.args[1] == f"{BASE_URL}/api/v1/workspaces"
+ assert len(rows) == len(workspaces)
+
+
class TestPaginationAbuseGuards:
def test_oversized_session_id_accumulation_raises(self):
# A host controls both the count and size of session ids returned while scoping the runs