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.

chore(warehouse-sources): share langsmith pagination helpers (#95828)

posthog[bot]8164c9440982
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
index e1e988b995a2..56e0f31ee7fe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
@@ -48,6 +48,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
FRESHNESS_WINDOW_SECONDS,
TAKEOVER_STALE_THRESHOLD_SECONDS,
BatchQueue,
+ FailedRunRef,
PendingBatch,
_Unset,
)
@@ -407,52 +408,8 @@ class DeltaBatchConsumerAdapter:
limit=limit,
)
for ref in refs:
- # A producer can enqueue a batch into a run after fail_run swept it (the
- # extraction is still in flight when a sibling batch exhausts retries).
- # Such stragglers stay 'pending' forever — unclaimable, but counted by the
- # freshness gauge and the CDC backpressure probe — so re-sweep the run here.
- # No-op (one indexed statement) when the run has no non-terminal batches.
- try:
- stragglers = await BatchQueue.fail_run(
- conn,
- run_uuid=ref.run_uuid,
- team_id=ref.team_id,
- schema_id=ref.schema_id,
- reason="enqueued into an already-failed run (reconcile sweep)",
- )
- except Exception as e:
- logger.exception("reconcile_straggler_sweep_failed", run_uuid=ref.run_uuid)
- capture_exception(e)
- else:
- if stragglers:
- logger.warning(
- "reconcile_swept_straggler_batches",
- run_uuid=ref.run_uuid,
- team_id=ref.team_id,
- external_data_schema_id=ref.schema_id,
- batch_count=stragglers,
- )
-
- try:
- reconciled = await sync_to_async(mark_job_failed_if_not_terminal)(
- job_id=ref.job_id,
- team_id=ref.team_id,
- error=ref.reason or "run failed (reconciled from queue)",
- )
- except Exception as e:
- if is_transient_db_error(e):
- logger.warning(
- "reconcile_job_status_update_app_db_not_ready",
- job_id=ref.job_id,
- run_uuid=ref.run_uuid,
- error=str(e),
- )
- else:
- logger.exception("reconcile_job_status_update_failed", job_id=ref.job_id, run_uuid=ref.run_uuid)
- capture_exception(e)
- reconciled = False
-
- if reconciled:
+ await self._sweep_straggler_batches(conn, ref)
+ if await self._mark_run_job_failed(ref):
RUNS_RECONCILED_TOTAL.inc()
logger.warning(
"run_reconciled_to_failed",
@@ -461,31 +418,7 @@ class DeltaBatchConsumerAdapter:
team_id=ref.team_id,
external_data_schema_id=ref.schema_id,
)
-
- # Attempted for every ref: this sweep is the retry for a fail_run whose own release
- # failed silently. Safe to repeat, since the release compare-and-deletes on the token.
- if ref.workflow_run_id:
- try:
- await sync_to_async(release_v3_pipeline_lock)(
- team_id=ref.team_id,
- schema_id=ref.schema_id,
- token=ref.workflow_run_id,
- )
- except Exception as e:
- logger.error(
- "failed_to_release_v3_pipeline_lock",
- job_id=ref.job_id,
- schema_id=ref.schema_id,
- exc_info=True,
- )
- capture_exception(e)
- else:
- logger.info(
- "v3_pipeline_lock_release_skipped_no_workflow_run_id",
- job_id=ref.job_id,
- run_uuid=ref.run_uuid,
- external_data_schema_id=ref.schema_id,
- )
+ await self._release_run_lock(ref)
# Runs the loader abandoned leave no 'failed' batch for get_failed_runs to key on, so sweep
# them on the same cadence and connection. Isolated so its failure can't take the sweep down.
@@ -503,6 +436,88 @@ class DeltaBatchConsumerAdapter:
logger.exception("stranded_run_reconcile_sweep_failed")
capture_exception(e)
+ async def _sweep_straggler_batches(self, conn: psycopg.AsyncConnection[Any], ref: FailedRunRef) -> None:
+ """Terminalize batches enqueued into a run that ``fail_run`` had already swept.
+
+ A producer can enqueue a batch into a run after fail_run swept it (the
+ extraction is still in flight when a sibling batch exhausts retries).
+ Such stragglers stay 'pending' forever — unclaimable, but counted by the
+ freshness gauge and the CDC backpressure probe — so re-sweep the run here.
+ No-op (one indexed statement) when the run has no non-terminal batches.
+ """
+ try:
+ stragglers = await BatchQueue.fail_run(
+ conn,
+ run_uuid=ref.run_uuid,
+ team_id=ref.team_id,
+ schema_id=ref.schema_id,
+ reason="enqueued into an already-failed run (reconcile sweep)",
+ )
+ except Exception as e:
+ logger.exception("reconcile_straggler_sweep_failed", run_uuid=ref.run_uuid)
+ capture_exception(e)
+ return
+
+ if stragglers:
+ logger.warning(
+ "reconcile_swept_straggler_batches",
+ run_uuid=ref.run_uuid,
+ team_id=ref.team_id,
+ external_data_schema_id=ref.schema_id,
+ batch_count=stragglers,
+ )
+
+ async def _mark_run_job_failed(self, ref: FailedRunRef) -> bool:
+ """Write the run's failure to the app DB. Returns whether this call moved the job to Failed."""
+ try:
+ return await sync_to_async(mark_job_failed_if_not_terminal)(
+ job_id=ref.job_id,
+ team_id=ref.team_id,
+ error=ref.reason or "run failed (reconciled from queue)",
+ )
+ except Exception as e:
+ if is_transient_db_error(e):
+ logger.warning(
+ "reconcile_job_status_update_app_db_not_ready",
+ job_id=ref.job_id,
+ run_uuid=ref.run_uuid,
+ error=str(e),
+ )
+ else:
+ logger.exception("reconcile_job_status_update_failed", job_id=ref.job_id, run_uuid=ref.run_uuid)
+ capture_exception(e)
+ return False
+
+ async def _release_run_lock(self, ref: FailedRunRef) -> None:
+ """Release the pipeline lock the failed run still holds.
+
+ Attempted for every ref: this sweep is the retry for a fail_run whose own release
+ failed silently. Safe to repeat, since the release compare-and-deletes on the token.
+ """
+ if not ref.workflow_run_id:
+ logger.info(
+ "v3_pipeline_lock_release_skipped_no_workflow_run_id",
+ job_id=ref.job_id,
+ run_uuid=ref.run_uuid,
+ external_data_schema_id=ref.schema_id,
+ )
+ return
+
+ try:
+ await sync_to_async(release_v3_pipeline_lock)(
+ team_id=ref.team_id,
+ schema_id=ref.schema_id,
+ token=ref.workflow_run_id,
+ )
+ except Exception as e:
+ logger.error(
+ "failed_to_release_v3_pipeline_lock",
+ job_id=ref.job_id,
+ schema_id=ref.schema_id,
+ exc_info=True,
+ )
+ capture_exception(e)
+
async def _reconcile_stale_stranded_runs(
self,
conn: psycopg.AsyncConnection[Any],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py
index 4264ea8d3366..dd64a5f968e0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py
@@ -278,6 +278,39 @@ def get_resource(
}
+def _paginator_state_from_checkpoint(resume_config: Optional[DubResumeConfig]) -> Optional[dict[str, Any]]:
+ """Translate a saved checkpoint into the paginator state to start the resource on."""
+ if resume_config is None:
+ return None
+ if resume_config.page is not None:
+ return {"page": resume_config.page}
+ if resume_config.scope_index is not None:
+ return {"scope_index": resume_config.scope_index, "starting_after": resume_config.starting_after}
+ if resume_config.starting_after is not None:
+ return {"starting_after": resume_config.starting_after}
+ return None
+
+
+def _checkpoint_from_paginator_state(state: Optional[dict[str, Any]]) -> Optional[DubResumeConfig]:
+ """Translate paginator state into the checkpoint to persist.
+
+ Returns None when there's no next page to resume to; the Redis TTL handles cleanup on completion.
+ """
+ if not state:
+ return None
+ if state.get("page") is not None:
+ return DubResumeConfig(page=int(state["page"]))
+ if state.get("scope_index") is not None:
+ starting_after = state.get("starting_after")
+ return DubResumeConfig(
+ scope_index=int(state["scope_index"]),
+ starting_after=None if starting_after is None else str(starting_after),
+ )
+ if state.get("starting_after") is not None:
+ return DubResumeConfig(starting_after=str(state["starting_after"]))
+ return None
+
+
def dub_source(
api_key: str,
endpoint: str,
@@ -313,35 +346,12 @@ def dub_source(
initial_paginator_state: Optional[dict[str, Any]] = None
if use_paginator_resume and resumable_source_manager.can_resume():
- resume_config = resumable_source_manager.load_state()
- if resume_config is not None:
- if resume_config.page is not None:
- initial_paginator_state = {"page": resume_config.page}
- elif resume_config.scope_index is not None:
- initial_paginator_state = {
- "scope_index": resume_config.scope_index,
- "starting_after": resume_config.starting_after,
- }
- elif resume_config.starting_after is not None:
- initial_paginator_state = {"starting_after": resume_config.starting_after}
+ initial_paginator_state = _paginator_state_from_checkpoint(resumable_source_manager.load_state())
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
- # Only persist when there's a next page to resume to; the Redis TTL handles
- # cleanup on completion.
- if not state:
- return
- if state.get("page") is not None:
- resumable_source_manager.save_state(DubResumeConfig(page=int(state["page"])))
- elif state.get("scope_index") is not None:
- starting_after = state.get("starting_after")
- resumable_source_manager.save_state(
- DubResumeConfig(
- scope_index=int(state["scope_index"]),
- starting_after=None if starting_after is None else str(starting_after),
- )
- )
- elif state.get("starting_after") is not None:
- resumable_source_manager.save_state(DubResumeConfig(starting_after=str(state["starting_after"])))
+ resume_config = _checkpoint_from_paginator_state(state)
+ if resume_config is not None:
+ resumable_source_manager.save_state(resume_config)
resource = rest_api_resource(
config,
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 d6d8ce8f3fca..eb235c7804fe 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
@@ -478,6 +478,46 @@ def _list_dataset_ids(
return ids
+def _emit_batches(
+ batcher: Batcher,
+ rows: list[Any],
+ resumable_source_manager: ResumableSourceManager[LangSmithResumeConfig],
+ resume_state: LangSmithResumeConfig,
+ *,
+ is_final_page: bool,
+) -> Iterator[Any]:
+ """Batch one page of rows, yielding a table each time one fills.
+
+ `resume_state` is saved AFTER yielding so a crash re-reads this page rather than skipping it,
+ because merge dedupes on the primary key. Nothing is saved on the final page, where the run is
+ finishing and there is no next page to resume to.
+ """
+ for item in rows:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ if not is_final_page:
+ resumable_source_manager.save_state(resume_state)
+
+
+def _stop_at_page_limit(
+ batcher: Batcher,
+ resumable_source_manager: ResumableSourceManager[LangSmithResumeConfig],
+ resume_state: LangSmithResumeConfig,
+ message: str,
+) -> Iterator[Any]:
+ """End this attempt at MAX_PAGES_PER_RUN, checkpointing where the next attempt picks up.
+
+ Flushes any batched-but-unyielded items first: resuming from `resume_state` skips the page they
+ came from, so an unflushed partial batch is lost. The raise ends the attempt without one
+ attempt monopolising a worker, and a legitimate oversized import continues from the checkpoint.
+ """
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+ resumable_source_manager.save_state(resume_state)
+ raise LangSmithPageLimitError(message)
+
+
def _get_runs_rows(
session: requests.Session,
headers: dict[str, str],
@@ -540,16 +580,13 @@ def _get_runs_rows(
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)
- )
+ yield from _emit_batches(
+ batcher,
+ runs,
+ resumable_source_manager,
+ LangSmithResumeConfig(cursor=page_cursor, window_start=window_start),
+ is_final_page=not next_cursor,
+ )
if not next_cursor:
break
@@ -569,15 +606,11 @@ def _get_runs_rows(
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"
+ yield from _stop_at_page_limit(
+ batcher,
+ resumable_source_manager,
+ LangSmithResumeConfig(cursor=next_cursor, window_start=window_start),
+ f"LangSmith runs import hit the {MAX_PAGES_PER_RUN}-page per-attempt limit; resuming from checkpoint",
)
cursor = next_cursor
@@ -622,15 +655,13 @@ def _get_offset_rows(
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)
- )
+ yield from _emit_batches(
+ batcher,
+ rows,
+ resumable_source_manager,
+ LangSmithResumeConfig(offset=page_offset, window_start=window_start),
+ is_final_page=is_last_page,
+ )
if is_last_page:
break
@@ -638,19 +669,46 @@ def _get_offset_rows(
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"
+ # A host that returns a full page at every offset forever would page without end.
+ yield from _stop_at_page_limit(
+ batcher,
+ resumable_source_manager,
+ LangSmithResumeConfig(offset=offset, window_start=window_start),
+ f"LangSmith {config.name} import hit the {MAX_PAGES_PER_RUN}-page per-attempt limit; resuming from checkpoint",
)
+def _examples_start_position(
+ resumable_source_manager: ResumableSourceManager[LangSmithResumeConfig],
+ dataset_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.
+ """
+ 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:
+ 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
+
+
+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 _get_examples_rows(
session: requests.Session,
headers: dict[str, str],
@@ -674,21 +732,14 @@ def _get_examples_rows(
logger.debug("LangSmith: no datasets in workspace, nothing to sync for examples")
return
- 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.
- resume_into_dataset = resume.dataset_id if resume is not None and resume.dataset_id in dataset_ids else None
- resume_offset = resume.offset if resume is not None else None
- start_index = dataset_ids.index(resume_into_dataset) if resume_into_dataset is not None else 0
- if resume_into_dataset is not None:
- logger.debug(f"LangSmith: resuming examples from dataset={resume_into_dataset} offset={resume_offset}")
+ start_index, resume_offset = _examples_start_position(resumable_source_manager, dataset_ids, logger)
pages = 0
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_into_dataset is not None:
- offset = resume_offset or 0
+ if index == start_index and resume_offset is not None:
+ offset = resume_offset
else:
offset = 0
# Checkpoint the dataset boundary before reading it, so a crash resumes at this dataset
@@ -708,33 +759,23 @@ def _get_examples_rows(
rows = data if isinstance(data, list) else []
is_last_page = not rows or 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.
- # Skip only on the final page of the final dataset — the run is finishing.
- if not (is_last_page and is_last_dataset):
- resumable_source_manager.save_state(
- LangSmithResumeConfig(dataset_id=dataset_id, offset=page_offset)
- )
-
run_is_finished = is_last_page and is_last_dataset
+ yield from _emit_batches(
+ batcher,
+ rows,
+ resumable_source_manager,
+ LangSmithResumeConfig(dataset_id=dataset_id, offset=page_offset),
+ is_final_page=run_is_finished,
+ )
+
if pages >= MAX_PAGES_PER_RUN and not run_is_finished:
- # Flush any batched-but-unyielded items before checkpointing where to resume —
- # resuming skips this page, so an unflushed partial batch is lost.
- if batcher.should_yield(include_incomplete_chunk=True):
- yield batcher.get_table()
- if is_last_page:
- # This dataset is exhausted; resume picks up at the start of the next one.
- next_dataset_id = dataset_ids[index + 1]
- resumable_source_manager.save_state(LangSmithResumeConfig(dataset_id=next_dataset_id, offset=0))
- else:
- resumable_source_manager.save_state(
- LangSmithResumeConfig(dataset_id=dataset_id, offset=page_offset + config.page_size)
- )
- raise LangSmithPageLimitError(
- f"LangSmith examples import hit the {MAX_PAGES_PER_RUN}-page per-attempt limit; resuming from checkpoint"
+ 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",
)
if is_last_page: