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): page langfuse traces by keyset, not offset (#105548)

posthog[bot]bcee8cf2add4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py
index 48549c8166d4..78a031f81763 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py
@@ -12,6 +12,7 @@ from structlog.types import FilteringBoundLogger
from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from urllib3.util.retry import Retry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -136,12 +137,39 @@ def _format_incremental_value(value: Any) -> str:
"""Langfuse timestamp filters want ISO 8601; we normalize to UTC with a literal Z."""
if isinstance(value, datetime):
dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
- return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+ return dt.isoformat().replace("+00:00", "Z")
if isinstance(value, date):
return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
return str(value)
+def _advance_from_value(
+ config: LangfuseEndpointConfig, items: list[dict[str, Any]], from_value: str | None
+) -> str | None:
+ """The from-filter value that lets the next request restart at page 1, or None to keep paging.
+
+ Only a strictly later value is returned. A page whose rows all sit on the current lower bound
+ would otherwise reset to page 1 on the same query and never reach the rows behind it.
+ """
+ if not config.keyset_pagination or not config.default_incremental_field:
+ return None
+
+ latest: datetime | None = None
+ for item in items:
+ parsed = parse_datetime_value(item.get(config.default_incremental_field))
+ if parsed is not None and (latest is None or parsed > latest):
+ latest = parsed
+ if latest is None:
+ return None
+
+ if from_value is not None:
+ current = parse_datetime_value(from_value)
+ if current is None or latest <= current:
+ return None
+
+ return _format_incremental_value(latest)
+
+
def _from_filter_value(
config: LangfuseEndpointConfig,
should_use_incremental_field: bool,
@@ -389,7 +417,8 @@ def get_rows(
# totalPages is documented as always present; stop rather than loop if it ever isn't.
total_pages = meta.get("totalPages")
has_next = bool(items) and total_pages is not None and page < total_pages
- next_state = LangfuseResumeConfig(page=page + 1, from_value=from_value)
+ advanced = _advance_from_value(config, items, from_value) if has_next else None
+ next_state = LangfuseResumeConfig(page=1 if advanced else page + 1, from_value=advanced or from_value)
else:
next_cursor = meta.get("cursor")
# A compliant server never hands back the cursor it was just given; looping on it would
@@ -418,7 +447,10 @@ def get_rows(
raise LangfusePaginationError(f"{PAGE_LIMIT_ERROR}: {pages_fetched} pages fetched from {endpoint}")
if config.pagination == "page":
- page += 1
+ page = next_state.page or 1
+ if next_state.from_value != from_value:
+ from_value = next_state.from_value
+ base_params = _build_params(config, from_value)
else:
cursor = meta.get("cursor")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/settings.py
index 5329a8fa34a5..9d03221e33cd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/settings.py
@@ -56,6 +56,11 @@ class LangfuseEndpointConfig:
# ascending backfill the first page is the oldest traffic, which is where costs are most often
# a flat 0. The table adopts int64, and every later fractional value then fails to cast.
float_fields: frozenset[str] = frozenset()
+ # Page the endpoint by keyset instead of by offset: after each page, move the from-filter up to
+ # the newest row seen and restart at page 1. Langfuse answers a deep offset with a 422 resource
+ # limit, which kills a backfill that walks far enough. Only safe on an endpoint that is pinned
+ # ascending on the field the from-filter applies to, so a later page never holds an earlier row.
+ keyset_pagination: bool = False
_DEFAULT_LOOKBACK = timedelta(hours=1)
@@ -86,6 +91,7 @@ LANGFUSE_ENDPOINTS: dict[str, LangfuseEndpointConfig] = {
sort_mode="asc",
incremental_lookback=_DEFAULT_LOOKBACK,
float_fields=frozenset({"totalCost", "latency"}),
+ keyset_pagination=True,
),
"observations": LangfuseEndpointConfig(
name="observations",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse.py
index bc4a1ffd13d2..b9c3d9bb0c7c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse.py
@@ -52,6 +52,10 @@ def _page(items: list[dict[str, Any]], *, page: int, total_pages: int) -> mock.M
return _response(json_data={"data": items, "meta": {"page": page, "limit": 50, "totalPages": total_pages}})
+def _trace(trace_id: str, timestamp: str) -> dict[str, Any]:
+ return {"id": trace_id, "timestamp": timestamp}
+
+
def _cursor_page(items: list[dict[str, Any]], *, cursor: Optional[str]) -> mock.MagicMock:
return _response(json_data={"data": items, "meta": {"cursor": cursor}})
@@ -533,6 +537,129 @@ class TestGetRows:
assert [r["id"] for r in rows] == ["t1"]
assert session.get.call_count == 2
+ def test_keyset_paging_advances_the_filter_and_resets_the_page(self):
+ # Offset depth is what kills a traces backfill: Langfuse answers a deep offset with a 422
+ # resource limit. Each page must move fromTimestamp past the newest row it saw and go back
+ # to page 1, so the offset never grows.
+ manager = self._manager()
+ rows, session = self._run(
+ manager,
+ [
+ _page(
+ [_trace("t1", "2026-03-04T10:00:00Z"), _trace("t2", "2026-03-04T10:05:00Z")],
+ page=1,
+ total_pages=900,
+ ),
+ _page(
+ [_trace("t2", "2026-03-04T10:05:00Z"), _trace("t3", "2026-03-04T10:09:00Z")],
+ page=1,
+ total_pages=400,
+ ),
+ _page([_trace("t3", "2026-03-04T10:09:00Z")], page=1, total_pages=1),
+ ],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 10, 0, 0, tzinfo=UTC),
+ incremental_field="timestamp",
+ )
+ assert [r["id"] for r in rows] == ["t1", "t2", "t2", "t3", "t3"]
+ pages = [call.kwargs["params"]["page"] for call in session.get.call_args_list]
+ bounds = [call.kwargs["params"]["fromTimestamp"] for call in session.get.call_args_list]
+ assert pages == [1, 1, 1]
+ assert bounds == ["2026-03-04T09:00:00Z", "2026-03-04T10:05:00Z", "2026-03-04T10:09:00Z"]
+
+ def test_keyset_paging_preserves_subsecond_progress(self):
+ manager = self._manager()
+ _rows, session = self._run(
+ manager,
+ [
+ _page(
+ [_trace("t1", "2026-03-04T10:00:00.100Z"), _trace("t2", "2026-03-04T10:00:00.200Z")],
+ page=1,
+ total_pages=900,
+ ),
+ _page(
+ [_trace("t2", "2026-03-04T10:00:00.200Z"), _trace("t3", "2026-03-04T10:00:00.300Z")],
+ page=1,
+ total_pages=400,
+ ),
+ _page([_trace("t3", "2026-03-04T10:00:00.300Z")], page=1, total_pages=1),
+ ],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 11, 0, 0, tzinfo=UTC),
+ incremental_field="timestamp",
+ )
+ assert [call.kwargs["params"]["page"] for call in session.get.call_args_list] == [1, 1, 1]
+ assert [call.kwargs["params"]["fromTimestamp"] for call in session.get.call_args_list] == [
+ "2026-03-04T10:00:00Z",
+ "2026-03-04T10:00:00.200000Z",
+ "2026-03-04T10:00:00.300000Z",
+ ]
+
+ def test_keyset_checkpoint_carries_the_advanced_filter(self):
+ # Resume reuses the saved from_value verbatim, so a checkpoint that kept the ORIGINAL bound
+ # next to page 1 would restart the whole walk on the next activity attempt.
+ manager = self._manager()
+ self._run(
+ manager,
+ [
+ _page([_trace("t1", "2026-03-04T10:05:00Z")], page=1, total_pages=900),
+ _page([_trace("t1", "2026-03-04T10:05:00Z")], page=1, total_pages=1),
+ ],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 10, 0, 0, tzinfo=UTC),
+ incremental_field="timestamp",
+ )
+ saved = manager.save_state.call_args.args[0]
+ assert saved.page == 1
+ assert saved.from_value == "2026-03-04T10:05:00Z"
+
+ def test_keyset_falls_back_to_offset_when_the_bound_cannot_move(self):
+ # Every row on the page sits on the current bound. Resetting to page 1 would re-issue the
+ # same query forever, so the walk must keep incrementing the offset to get past them.
+ manager = self._manager()
+ _rows, session = self._run(
+ manager,
+ [
+ _page([_trace("t1", "2026-03-04T11:00:00Z")], page=1, total_pages=3),
+ _page([_trace("t2", "2026-03-04T11:00:00Z")], page=2, total_pages=3),
+ _page([_trace("t3", "2026-03-04T11:00:00Z")], page=3, total_pages=3),
+ ],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 12, 0, 0, tzinfo=UTC),
+ incremental_field="timestamp",
+ )
+ assert [call.kwargs["params"]["page"] for call in session.get.call_args_list] == [1, 2, 3]
+
+ def test_keyset_advances_from_an_unfiltered_first_sync(self):
+ manager = self._manager()
+ _rows, session = self._run(
+ manager,
+ [
+ _page([_trace("t1", "2026-03-04T10:05:00Z")], page=1, total_pages=900),
+ _page([_trace("t1", "2026-03-04T10:05:00Z")], page=1, total_pages=1),
+ ],
+ )
+ assert "fromTimestamp" not in session.get.call_args_list[0].kwargs["params"]
+ assert session.get.call_args_list[1].kwargs["params"]["fromTimestamp"] == "2026-03-04T10:05:00Z"
+
+ def test_cursor_endpoint_keeps_offset_free_paging(self):
+ # Only traces is pinned ascending, so only traces may move its bound. A descending endpoint
+ # that did so would filter away the rows it has not read yet.
+ manager = self._manager()
+ _rows, session = self._run(
+ manager,
+ [
+ _cursor_page([{"id": "o1", "startTime": "2026-03-04T10:05:00Z"}], cursor="abc"),
+ _cursor_page([{"id": "o2", "startTime": "2026-03-04T09:00:00Z"}], cursor=None),
+ ],
+ endpoint="observations",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 8, 0, 0, tzinfo=UTC),
+ incremental_field="startTime",
+ )
+ for call in session.get.call_args_list:
+ assert call.kwargs["params"]["fromStartTime"] == "2026-03-04T07:00:00Z"
+
def test_page_limit_raises_after_checkpointing_next_page(self):
# A hostile host reporting ever-more totalPages would otherwise keep the loop alive until
# the activity timeout. The run must abort at the cap — retryably, with the next page