Skip to content

The platform for continuously improving AI agents.

Support every Langfuse version (#288)

Freyam Mehta577eed08eddc
diff --git a/overbae/services/connectors/langfuse/adapter.py b/overbae/services/connectors/langfuse/adapter.py
index f7ef3723..fe01b953 100644
--- a/overbae/services/connectors/langfuse/adapter.py
+++ b/overbae/services/connectors/langfuse/adapter.py
@@ -34,6 +34,9 @@ LANGFUSE_CAPABILITIES = Capabilities(
)
+_LIVE_INGESTION_OVERLAP = timedelta(minutes=30)
+
+
def _parse_iso(value: str | None) -> datetime | None:
if not value:
return None
@@ -97,6 +100,8 @@ class LangfuseAdapter:
window_from: datetime | None = None,
window_to: datetime | None = None,
) -> int | None:
+ if self._client.api_version != "v2":
+ return None
end = window_to or timezone.now()
start = window_from or (
end - timedelta(days=int(lookback_days))
@@ -125,29 +130,19 @@ class LangfuseAdapter:
# request through minutes of worker-style retries.
self._client.retry_attempts = 1
units: list[Any] = []
- if self._client.api_version == "v2":
- cursor = None
- seen: set[str] = set()
- while len(units) < limit:
- groups, cursor = self._client.fetch_v2_trace_page(
- window,
- cursor=cursor,
- limit=min(limit - len(units), 1000),
- expand_metadata=self._expanded_metadata_key(),
- )
- for group in groups:
- trace_id = group[0].trace_id or group[0].id
- if trace_id not in seen:
- units.append(group)
- seen.add(trace_id)
- if not cursor:
- break
- return units[:limit]
- for obs_list in self._client.iter_ingest_units(windows=[window]):
- units.append(obs_list)
- if len(units) >= limit:
+ cursor = None
+ seen: set[str] = set()
+ while len(units) < limit:
+ before = len(units)
+ groups, cursor = self._trace_page(window, cursor=cursor, limit=limit - len(units))
+ for group in groups:
+ trace_id = group[0].trace_id or group[0].id
+ if trace_id not in seen:
+ units.append(group)
+ seen.add(trace_id)
+ if not cursor or len(units) == before:
break
- return units
+ return units[:limit]
def fetch_page(self, state: dict[str, Any]) -> Page:
page = self._fetch_page(state)
@@ -189,16 +184,12 @@ class LangfuseAdapter:
)
window = all_windows[0]
- if self._client.api_version == "v2":
- units, next_cursor = self._collect_v2_page(
- window.start,
- window.end,
- cursor=state.get("next_cursor"),
- )
- newest = max((unit.newest_ts for unit in units if unit.newest_ts), default=None)
- else:
- units, newest = self._collect_window(window.start, window.end)
- next_cursor = None
+ units, next_cursor = self._collect_page(
+ window.start,
+ window.end,
+ cursor=state.get("next_cursor"),
+ )
+ newest = max((unit.newest_ts for unit in units if unit.newest_ts), default=None)
newest = _within_bound(
max((ts for ts in (newest, watermark) if ts), key=_parse_iso, default=None), anchor
)
@@ -248,8 +239,11 @@ class LangfuseAdapter:
window_from = _parse_iso(state.get("live_window_from"))
window_to = _parse_iso(state.get("live_window_to"))
else:
- window_from = _parse_iso(state.get("watermark")) or (
- timezone.now() - timedelta(hours=1)
+ watermark = _parse_iso(state.get("watermark"))
+ window_from = (
+ watermark - _LIVE_INGESTION_OVERLAP
+ if watermark
+ else timezone.now() - timedelta(hours=1)
)
window_to = timezone.now()
@@ -258,29 +252,26 @@ class LangfuseAdapter:
window_to = timezone.now()
cursor = None
- if self._client.api_version == "v2":
- units, next_cursor = self._collect_v2_page(
- window_from,
- window_to,
- cursor=cursor,
+ units, next_cursor = self._collect_page(
+ window_from,
+ window_to,
+ cursor=cursor,
+ )
+ if next_cursor:
+ return Page(
+ units=units,
+ next_state={
+ "mode": "live",
+ "watermark": state.get("watermark"),
+ "next_cursor": next_cursor,
+ "live_window_from": window_from.isoformat(),
+ "live_window_to": window_to.isoformat(),
+ },
+ done=False,
+ window_from=window_from,
+ window_to=window_to,
+ mode="live",
)
- if next_cursor:
- return Page(
- units=units,
- next_state={
- "mode": "live",
- "watermark": state.get("watermark"),
- "next_cursor": next_cursor,
- "live_window_from": window_from.isoformat(),
- "live_window_to": window_to.isoformat(),
- },
- done=False,
- window_from=window_from,
- window_to=window_to,
- mode="live",
- )
- else:
- units, _ = self._collect_window(window_from, window_to)
self._persist_api_version()
return Page(
@@ -292,23 +283,31 @@ class LangfuseAdapter:
mode="live",
)
- def _collect_window(
- self, window_from: datetime, window_to: datetime
- ) -> tuple[list[IngestUnit], str | None]:
- single = TimeWindow(start=window_from, end=window_to)
- return self._units_from_observation_groups(self._client.iter_ingest_units(windows=[single]))
+ def _trace_page(
+ self,
+ window: TimeWindow,
+ *,
+ cursor: str | None = None,
+ limit: int = 1000,
+ ) -> tuple[list[list[Any]], str | None]:
+ if self._client.api_version == "v2":
+ return self._client.fetch_v2_trace_page(
+ window,
+ cursor=cursor,
+ limit=limit,
+ expand_metadata=self._expanded_metadata_key(),
+ )
+ return self._client.fetch_v1_trace_page(window, cursor=cursor, limit=limit)
- def _collect_v2_page(
+ def _collect_page(
self,
window_from: datetime,
window_to: datetime,
*,
cursor: str | None,
) -> tuple[list[IngestUnit], str | None]:
- groups, next_cursor = self._client.fetch_v2_trace_page(
- TimeWindow(start=window_from, end=window_to),
- cursor=cursor,
- expand_metadata=self._expanded_metadata_key(),
+ groups, next_cursor = self._trace_page(
+ TimeWindow(start=window_from, end=window_to), cursor=cursor
)
units, _ = self._units_from_observation_groups(iter(groups))
return units, next_cursor
diff --git a/overbae/services/connectors/langfuse/client.py b/overbae/services/connectors/langfuse/client.py
index 7339f0c8..4bbe5e00 100644
--- a/overbae/services/connectors/langfuse/client.py
+++ b/overbae/services/connectors/langfuse/client.py
@@ -3,18 +3,18 @@
from __future__ import annotations
import json
-import threading
import time
from collections.abc import Iterator
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from math import isfinite
from typing import Any, Literal
+from urllib.parse import quote
import httpx
from overbae.services.connectors.records import LangFuseObservation
-from overbae.services.connectors.windows import TimeWindow, plan_windows
+from overbae.services.connectors.windows import TimeWindow
ApiVersion = Literal["v1", "v2", "unknown"]
@@ -22,14 +22,12 @@ _DEFAULT_HOST = "https://cloud.langfuse.com"
_V2_FIELDS = "core,basic,time,io,metadata,model,usage,prompt,metrics,trace_context"
_V2_PAGE_SIZE = 1000
_TRACE_FILTER_BATCH_SIZE = 150
-_DEPRECATED_READ_PREFIXES = ("/api/public/traces", "/api/public/observations")
-_DEPRECATED_MIN_INTERVAL = 24.0 # Hobby deprecated-read bucket is 150/hour
+_TRACE_FILTER_MAX_URL_CHARS = 12_000
+_V1_PAGE_SIZE = 100
+_DEFAULT_RETRY_AFTER = 24.0
_429_ATTEMPTS = 4
_429_WAIT_CAP = 60.0
-_deprecated_gate = threading.Lock()
-_deprecated_next = 0.0
-
class LangFuseError(Exception):
def __init__(
@@ -75,10 +73,8 @@ class LangFuseClient:
clean = {k: v for k, v in params.items() if v is not None}
url = f"{self.base_url}{path}"
last_429 = ""
- last_retry_after = _DEPRECATED_MIN_INTERVAL
+ last_retry_after = _DEFAULT_RETRY_AFTER
for attempt in range(self.retry_attempts):
- if _is_deprecated_read(path):
- _pace_deprecated_read()
try:
resp = httpx.get(url, auth=self._auth, params=clean, timeout=60)
except httpx.RequestError as exc:
@@ -120,15 +116,17 @@ class LangFuseClient:
def probe_capabilities(self) -> ApiVersion:
"""Detect v2 observations support; cache on the client instance."""
+ now = datetime.now(UTC)
+ day = TimeWindow(start=now - timedelta(days=1), end=now)
try:
self._get(
"/api/public/v2/observations",
limit=1,
fields="core",
- fromStartTime=_iso(datetime.now(UTC) - timedelta(days=1)),
- toStartTime=_iso(datetime.now(UTC)),
+ fromStartTime=_iso(day.start),
+ toStartTime=_iso(day.end),
)
- self._api_version = "v2"
+ self._api_version = "v2" if self._v2_reads_data(day) else "v1"
except LangFuseError as exc:
msg = str(exc).lower()
# 404 / "not found" / beta gate → fall back to v1 traces.
@@ -139,6 +137,16 @@ class LangFuseClient:
raise
return self._api_version
+ def _v2_reads_data(self, window: TimeWindow) -> bool:
+ attempts, self.retry_attempts = self.retry_attempts, 1
+ try:
+ self.volume(window)
+ except LangFuseError as exc:
+ return exc.status_code != 404
+ finally:
+ self.retry_attempts = attempts
+ return True
+
def count(
self,
*,
@@ -186,32 +194,6 @@ class LangFuseClient:
roots += int(value)
return {"roots": roots, "observations": observations}
- def iter_ingest_units(
- self,
- *,
- window_from: datetime | None = None,
- window_to: datetime | None = None,
- lookback_days: int | None = None,
- windows: list[TimeWindow] | None = None,
- ) -> Iterator[list[LangFuseObservation]]:
- """Yield observation trees (one list per trace), newest windows first.
-
- Pass *windows* to skip re-planning (used by the chunk task which already
- selected the next TimeWindow).
- """
- if self._api_version == "unknown":
- self.probe_capabilities()
-
- if windows is None:
- max_lookback = timedelta(days=lookback_days) if lookback_days else None
- windows = plan_windows(window_from, window_to, max_lookback=max_lookback)
-
- for window in windows:
- if self._api_version == "v2":
- yield from self._iter_v2_traces(window)
- else:
- yield from self._iter_v1_traces(window)
-
def _iter_v2_observations(self, **filters) -> Iterator[LangFuseObservation]:
"""Page the v2 observations endpoint, following the meta cursor."""
cursor: str | None = None
@@ -251,7 +233,7 @@ class LangFuseClient:
raise LangFuseError(
"Langfuse returned a stalled pagination cursor; the page was not imported."
)
- return [_observation_from_v2(raw) for raw in rows], next_cursor
+ return [_observation_from_row(raw) for raw in rows], next_cursor
def fetch_trace_observations(
self, trace_id: str, *, expand_metadata: str | None = None
@@ -283,8 +265,7 @@ class LangFuseClient:
# parents and siblings can fall outside the discovery page's window.
trace_ids = [tid for tid, group in by_trace.items() if all(o.trace_id for o in group)]
complete: dict[str, list[LangFuseObservation]] = {}
- for offset in range(0, len(trace_ids), _TRACE_FILTER_BATCH_SIZE):
- batch = trace_ids[offset : offset + _TRACE_FILTER_BATCH_SIZE]
+ for batch in _trace_batches(trace_ids):
if len(batch) == 1:
observations = self.fetch_trace_observations(
batch[0], expand_metadata=expand_metadata
@@ -316,37 +297,49 @@ class LangFuseClient:
trees = [complete.get(tid, group) for tid, group in by_trace.items()]
return trees, next_cursor
- def _iter_v2_traces(
+ def fetch_v1_trace_page(
self,
window: TimeWindow,
- ) -> Iterator[list[LangFuseObservation]]:
- """Page v2 observations, group by traceId, yield complete trees."""
- yield from self._group_observations(
- self._iter_v2_observations(
- fromStartTime=_iso(window.start) if window.start.year > 1 else None,
- toStartTime=_iso(window.end),
- )
+ *,
+ cursor: str | None = None,
+ limit: int = _V1_PAGE_SIZE,
+ ) -> tuple[list[list[LangFuseObservation]], str | None]:
+ page = int(cursor or 1)
+ data = self._get(
+ "/api/public/observations",
+ page=page,
+ limit=min(limit, _V1_PAGE_SIZE),
+ fromStartTime=_iso(window.start) if window.start.year > 1 else None,
+ toStartTime=_iso(window.end),
)
-
- def _group_observations(
- self, observations: Iterator[LangFuseObservation]
- ) -> Iterator[list[LangFuseObservation]]:
- by_trace: dict[str, list[LangFuseObservation]] = {}
- for obs in observations:
- by_trace.setdefault(obs.trace_id or obs.id, []).append(obs)
-
- def _trace_ts(obs_list: list[LangFuseObservation]) -> str:
- return max((o.start_time or "") for o in obs_list)
-
- for tid in sorted(by_trace, key=lambda t: _trace_ts(by_trace[t]), reverse=True):
- group = by_trace[tid]
- # A trace straddling the window arrives in pieces, and the missing
- # parents would make its children look like roots. Span ids are
- # stable and the writer never revisits them, so a half tree would
- # stay wrong forever — refetch the whole trace instead.
- if _is_partial_tree(group):
- group = self.fetch_trace_observations(tid) or group
- yield group
+ rows = data.get("data")
+ if not isinstance(rows, list):
+ raise LangFuseError("Langfuse did not return a valid observations page.")
+ trace_ids = dict.fromkeys(row["traceId"] for row in rows if row.get("traceId"))
+ trees = [tree for trace_id in trace_ids if (tree := self._v1_trace_tree(trace_id))]
+ trees += [[_observation_from_v1_row(row, {})] for row in rows if not row.get("traceId")]
+ pages = (data.get("meta") or {}).get("totalPages") or page
+ return trees, str(page + 1) if page < pages else None
+
+ def _v1_trace_tree(self, trace_id: str) -> list[LangFuseObservation]:
+ trace = self._get(f"/api/public/traces/{quote(trace_id, safe='')}")
+ return [_observation_from_v1_row(row, trace) for row in trace.get("observations") or []]
+
+
+def _trace_batches(trace_ids: list[str]) -> Iterator[list[str]]:
+ batch: list[str] = []
+ size = 0
+ for trace_id in trace_ids:
+ length = len(quote(json.dumps(trace_id), safe="")) + 4
+ if batch and (
+ len(batch) == _TRACE_FILTER_BATCH_SIZE or size + length > _TRACE_FILTER_MAX_URL_CHARS
+ ):
+ yield batch
+ batch, size = [], 0
+ batch.append(trace_id)
+ size += length
+ if batch:
+ yield batch
def _iso(dt: datetime) -> str:
@@ -355,20 +348,6 @@ def _iso(dt: datetime) -> str:
return dt.isoformat().replace("+00:00", "Z")
-def _is_deprecated_read(path: str) -> bool:
- return path.startswith(_DEPRECATED_READ_PREFIXES)
-
-
-def _pace_deprecated_read() -> None:
- global _deprecated_next
- with _deprecated_gate:
- now = time.monotonic()
- wait = _deprecated_next - now
- if wait > 0:
- time.sleep(wait)
- _deprecated_next = time.monotonic() + _DEPRECATED_MIN_INTERVAL
-
-
def _retry_after_seconds(resp: httpx.Response) -> float:
header = resp.headers.get("Retry-After")
if header:
@@ -389,19 +368,27 @@ def _retry_after_seconds(resp: httpx.Response) -> float:
return seconds
except (TypeError, ValueError, json.JSONDecodeError):
pass
- return _DEPRECATED_MIN_INTERVAL
-
-
-def _is_partial_tree(observations: list[LangFuseObservation]) -> bool:
- """True when this group cannot be the whole trace: a parent is missing, or
- nothing in it is a root."""
- ids = {o.id for o in observations}
- if any(o.parent_observation_id and o.parent_observation_id not in ids for o in observations):
- return True
- return not any(o.is_root_observation or o.parent_observation_id is None for o in observations)
+ return _DEFAULT_RETRY_AFTER
+
+
+def _observation_from_v1_row(row: dict[str, Any], trace: dict[str, Any]) -> LangFuseObservation:
+ return _observation_from_row(
+ {
+ **row,
+ "traceName": trace.get("name"),
+ "tags": trace.get("tags"),
+ "sessionId": trace.get("sessionId"),
+ "userId": trace.get("userId"),
+ "release": row.get("release") or trace.get("release"),
+ "totalCost": row.get("totalCost", row.get("calculatedTotalCost")),
+ "usageDetails": row.get("usageDetails")
+ or {k: v for k, v in (row.get("usage") or {}).items() if k != "unit"},
+ "isRootObservation": row.get("parentObservationId") is None,
+ }
+ )
-def _observation_from_v2(raw: dict[str, Any]) -> LangFuseObservation:
+def _observation_from_row(raw: dict[str, Any]) -> LangFuseObservation:
return LangFuseObservation(
id=raw["id"],
trace_id=raw.get("traceId"),
diff --git a/tests/test_connector_poll.py b/tests/test_connector_poll.py
index e0449466..28b13843 100644
--- a/tests/test_connector_poll.py
+++ b/tests/test_connector_poll.py
@@ -110,6 +110,19 @@ def test_live_polling_pulls_only_what_arrived_since_the_watermark(credential, la
assert credential.sync_cursor["watermark"] > watermark_before
+def test_a_trace_that_appears_after_its_poll_window_is_still_imported(credential, langfuse):
+ credential = sync_until_live(credential)
+ watermark = timezone.now()
+ ConnectorCredential.objects.filter(pk=credential.pk).update(
+ sync_cursor={"mode": "live", "watermark": watermark.isoformat()}
+ )
+ start = watermark - timedelta(minutes=10)
+ late = Step("late", "span", None, start=start, end=start + timedelta(seconds=1))
+ langfuse.record(uuid.uuid4().hex, [late])
+ _chunk(credential)
+ assert Span.objects.filter(project=credential.project, name="late").count() == 1
+
+
def test_a_paged_live_poll_queues_the_next_chunk(credential, langfuse, continuations):
_traces(langfuse, 3)
sync_until_live(credential)
diff --git a/tests/test_langfuse_adapter.py b/tests/test_langfuse_adapter.py
index ae7e3ae8..0d6c67b6 100644
--- a/tests/test_langfuse_adapter.py
+++ b/tests/test_langfuse_adapter.py
@@ -119,7 +119,7 @@ def test_live_pagination_pins_its_window_and_resumes(api, clock):
assert second.next_state == {"mode": "live", "watermark": first.window_to.isoformat()}
pages = [c.params for c in api.calls if "traceId" not in c.params]
assert {(p["fromStartTime"], p["toStartTime"]) for p in pages} == {
- ("2026-08-19T12:00:00Z", "2026-08-19T12:01:00Z")
+ ("2026-08-19T11:30:00Z", "2026-08-19T12:01:00Z")
}
assert pages[1]["cursor"] == "cursor-1"
assert all(c.params["expandMetadata"] == "capability" for c in api.calls)
@@ -198,3 +198,32 @@ def test_backfill_watermark_compares_instants_across_formats(api, clock):
api.reply(json_body={"data": [observation], "meta": {}})
page = _adapter().fetch_page({"mode": "backfill", "watermark": later})
assert page.next_state["watermark"] == later
+
+
+def test_a_server_without_v2_imports_through_v1_with_no_estimate(scripted, slept, clock):
+ api = scripted("https://cloud.langfuse.com")
+ missing = {"status": 404, "text": "not found"}
+ row = {"id": "o1", "traceId": "t1", "type": "SPAN", "startTime": "2026-08-19T11:00:00Z"}
+ api.reply(**missing)
+ api.reply(**missing)
+ api.reply(json_body={"data": [row], "meta": {"page": 1, "totalPages": 2}})
+ api.reply(json_body={"name": "n", "observations": [row]})
+ credential = make_connector("langfuse", source_project_id="src", api_secret="sk")
+ credential.api_version = "unknown"
+ adapter = LangfuseAdapter(credential)
+ assert adapter.count(lookback_days=1) is None
+ page = adapter.fetch_page({})
+ assert [unit.external_trace_id for unit in page.units] == ["t1"]
+ assert page.next_state["next_cursor"] == "2"
+ assert page.next_state["progress"]["total"] is None
+
+
+def test_preview_stops_when_a_page_adds_no_new_trace(scripted, slept):
+ api = scripted("https://cloud.langfuse.com")
+ row = {"id": "o1", "traceId": "t1", "type": "SPAN", "startTime": "2026-08-19T11:00:00Z"}
+ api.reply(json_body={"data": [row], "meta": {"cursor": "a"}})
+ api.reply(json_body={"data": [row], "meta": {}})
+ api.reply(json_body={"data": [row], "meta": {"cursor": "b"}})
+ api.reply(json_body={"data": [row], "meta": {}})
+ assert len(_adapter().sample_units(lookback_days=1, limit=10)) == 1
+ assert len(api.calls) == 4
diff --git a/tests/test_langfuse_client.py b/tests/test_langfuse_client.py
index 93add173..37bae102 100644
--- a/tests/test_langfuse_client.py
+++ b/tests/test_langfuse_client.py
@@ -44,6 +44,21 @@ def test_probe_falls_back_to_v1_on_v2_404_without_probing_v1(api):
assert len(api.calls) == 1
+ "metrics,version",
+ [
+ ({"status": 404, "text": "The metrics v2 API is only available in a v4 write mode"}, "v1"),
+ ({"status": 429, "text": "quota"}, "v2"),
+ ({"status": 500, "text": "v2 not found upstream"}, "v2"),
+ ],
+)
+def test_probe_reads_empty_v2_observations_through_their_metrics(api, slept, metrics, version):
+ api.reply(json_body={"data": []})
+ api.reply(**metrics)
+ assert LangFuseClient("pk", "sk").probe_capabilities() == version
+ assert len(api.calls) == 2
+
+
def test_probe_raises_on_v2_auth_error(api):
api.reply(401, text="unauthorized")
with pytest.raises(LangFuseError, match="401"):
@@ -105,58 +120,6 @@ def _obs(oid, parent=None, *, root=False, minute=0):
}
-def _groups(api, *pages) -> list:
- api.reply(json_body={"data": []})
- for page in pages:
- api.reply(json_body=page)
- client = LangFuseClient("pk", "sk")
- assert client.probe_capabilities() == "v2"
- groups = list(client.iter_ingest_units(windows=[_WINDOW]))
- del api.calls[0]
- return groups
-
-
-def test_an_orphaned_child_triggers_a_whole_trace_refetch(api):
- (group,) = _groups(
- api,
- {"data": [_obs("child", parent="root", minute=5)], "meta": {}},
- {"data": [_obs("root", root=True), _obs("child", parent="root")], "meta": {}},
- )
-
- assert sorted(o.id for o in group) == ["child", "root"]
- assert [c.params.get("traceId") for c in api.calls] == [None, "t1"]
-
-
-def test_a_group_without_its_root_is_refetched(api):
- (group,) = _groups(
- api,
- {"data": [_obs("b", parent="a"), _obs("a", parent="root")], "meta": {}},
- {
- "data": [_obs("root", root=True), _obs("a", parent="root"), _obs("b", parent="a")],
- "meta": {},
- },
- )
-
- assert len(group) == 3
- assert api.calls[-1].params["traceId"] == "t1"
-
-
-def test_a_complete_trace_is_not_refetched(api):
- (group,) = _groups(
- api, {"data": [_obs("root", root=True), _obs("child", parent="root")], "meta": {}}
- )
-
- assert len(group) == 2
- assert all("traceId" not in c.params for c in api.calls)
-
-
-def test_window_paging_stops_when_the_cursor_repeats(api):
- with pytest.raises(LangFuseError, match="cursor"):
- _groups(api, {"data": [_obs("root", root=True)], "meta": {"cursor": "stuck"}})
-
- assert len(api.calls) <= 3
-
-
def test_batched_trace_completion_keeps_children_across_provider_pages(api):
first = {"id": "a", "traceId": "t1", "type": "SPAN", "isRootObservation": True}
second = {"id": "b", "traceId": "t2", "type": "SPAN", "isRootObservation": True}
@@ -170,6 +133,20 @@ def test_batched_trace_completion_keeps_children_across_provider_pages(api):
assert len(api.calls) == 3
+def test_long_trace_ids_split_the_batch_below_the_server_url_limit(api):
+ rows = [
+ {"id": f"o{n}", "traceId": f"{n:0100d}", "type": "SPAN", "isRootObservation": True}
+ for n in range(150)
+ ]
+ api.reply(json_body={"data": rows, "meta": {}})
+ api.reply(json_body={"data": rows[:109], "meta": {}})
+ api.reply(json_body={"data": rows[109:], "meta": {}})
+ groups, _ = LangFuseClient("pk", "sk").fetch_v2_trace_page(_WINDOW)
+ assert len(groups) == 150
+ assert len(api.calls) == 3
+ assert all(len(call.url) < 16_000 for call in api.calls)
+
+
@pytest.mark.parametrize("returned", [[], [{"id": "unexpected", "traceId": "other"}]])
def test_incomplete_or_unfiltered_batch_responses_are_not_imported(api, returned):
api.reply(json_body={"data": [{"id": "root", "traceId": "wanted"}], "meta": {}})
@@ -212,3 +189,53 @@ def test_long_rate_limit_wait_is_deferred_without_shortening_it(api, headers, bo
LangFuseClient("pk", "sk").list_projects()
assert caught.value.retry_after == 3600
assert len(api.calls) == 1
+
+
+def test_v1_page_builds_trees_with_trace_fields_and_a_page_cursor(api):
+ root = {"id": "root", "traceId": "t1", "type": "SPAN", "parentObservationId": None}
+ child = {
+ "id": "child",
+ "traceId": "t1",
+ "type": "GENERATION",
+ "parentObservationId": "root",
+ "usage": {"unit": "TOKENS", "input": 11, "output": 7, "total": 18},
+ "calculatedTotalCost": 0.5,
+ }
+ api.reply(json_body={"data": [child], "meta": {"page": 1, "totalPages": 2}})
+ api.reply(
+ json_body={
+ "name": "support",
+ "tags": ["a"],
+ "sessionId": "s",
+ "userId": "u",
+ "observations": [root, child],
+ }
+ )
+ ((first, second),), cursor = LangFuseClient("pk", "sk").fetch_v1_trace_page(_WINDOW)
+ assert cursor == "2"
+ assert (first.id, first.is_root_observation, second.is_root_observation) == (
+ "root",
+ True,
+ False,
+ )
+ assert (second.trace_name, second.tags, second.session_id, second.user_id) == (
+ "support",
+ ["a"],
+ "s",
+ "u",
+ )
+ assert second.usage_details == {"input": 11, "output": 7, "total": 18}
+ assert second.total_cost == 0.5
+ assert api.calls[0].path == "/api/public/observations"
+ assert api.calls[0].params["limit"] == "100"
+ assert api.calls[1].path == "/api/public/traces/t1"
+
+
+def test_v1_page_skips_empty_traces_and_keeps_usage_without_a_trace(api):
+ traced = {"id": "a", "traceId": "gone", "type": "SPAN"}
+ untraced = {"id": "b", "traceId": None, "type": "GENERATION", "usage": {"input": 3}}
+ api.reply(json_body={"data": [traced, untraced], "meta": {"page": 1, "totalPages": 1}})
+ api.reply(json_body={"name": "n", "observations": []})
+ ((only,),), cursor = LangFuseClient("pk", "sk").fetch_v1_trace_page(_WINDOW)
+ assert cursor is None
+ assert (only.id, only.usage_details) == ("b", {"input": 3})