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(langfuse): emit cost and latency as floats, not integers (#106191)

posthog[bot]34c019c1c1bd
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 ccca5c852baf..48549c8166d4 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
@@ -273,6 +273,24 @@ def validate_credentials(
return False, response.text
+def _coerce_float_fields(items: list[dict[str, Any]], float_fields: frozenset[str]) -> None:
+ """Widen whole-number values in fields the API documents as fractional, in place.
+
+ Arrow types are inferred per batch from the values present, so a page whose costs are all whole
+ numbers creates an integer column that no later fractional value can be cast into. Only `int` is
+ widened: anything else is left for the pipeline's existing type handling to surface rather than
+ being reinterpreted here. `bool` is excluded because it is an `int` subclass in Python.
+ """
+ if not float_fields:
+ return
+
+ for item in items:
+ for field_name in float_fields:
+ value = item.get(field_name)
+ if isinstance(value, int) and not isinstance(value, bool):
+ item[field_name] = float(value)
+
+
def get_rows(
host: str | None,
public_key: str,
@@ -364,6 +382,7 @@ def get_rows(
data = fetch_page(params)
pages_fetched += 1
items = data.get("data") or []
+ _coerce_float_fields(items, config.float_fields)
meta = data.get("meta") or {}
if config.pagination == "page":
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 54ad3f6b3276..5329a8fa34a5 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
@@ -26,7 +26,9 @@ def _datetime_incremental_field(name: str) -> IncrementalField:
}
-@dataclass
+# Mutable to stay consistent with the other per-endpoint config objects in this package; these
+# are module-level constants that nothing reassigns.
+@dataclass(frozen=False)
class LangfuseEndpointConfig:
name: str
path: str
@@ -49,6 +51,11 @@ class LangfuseEndpointConfig:
# are on event/creation time, so rows that arrive late (ingestion lag) would otherwise be
# skipped forever. Re-pulled rows are deduped on the primary key by merge.
incremental_lookback: Optional[timedelta] = None
+ # Fields the API documents as fractional (USD costs, second-precision durations) but sends as
+ # plain JSON numbers, so a page holding only whole values infers an integer column. On an
+ # 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()
_DEFAULT_LOOKBACK = timedelta(hours=1)
@@ -78,6 +85,7 @@ LANGFUSE_ENDPOINTS: dict[str, LangfuseEndpointConfig] = {
partition_key="timestamp",
sort_mode="asc",
incremental_lookback=_DEFAULT_LOOKBACK,
+ float_fields=frozenset({"totalCost", "latency"}),
),
"observations": LangfuseEndpointConfig(
name="observations",
@@ -92,6 +100,7 @@ LANGFUSE_ENDPOINTS: dict[str, LangfuseEndpointConfig] = {
# v2 observations return newest-first (startTime descending) and accept no orderBy.
sort_mode="desc",
incremental_lookback=_DEFAULT_LOOKBACK,
+ float_fields=frozenset({"totalCost", "latency", "timeToFirstToken"}),
),
"scores": LangfuseEndpointConfig(
name="scores",
@@ -102,6 +111,8 @@ LANGFUSE_ENDPOINTS: dict[str, LangfuseEndpointConfig] = {
default_incremental_field="timestamp",
incremental_filter_param="fromTimestamp",
extra_params={"fields": _SCORE_FIELDS},
+ # No float_fields: `value` is numeric only when dataType is NUMERIC, and carries a string
+ # for CATEGORICAL/TEXT scores, so widening it would hide a genuine mixed-type column.
partition_key="timestamp",
sort_mode="desc",
incremental_lookback=_DEFAULT_LOOKBACK,
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 0a60387b248a..bc4a1ffd13d2 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
@@ -273,6 +273,53 @@ class TestGetRows:
assert session.get.call_args_list[0].kwargs["params"]["page"] == 1
assert session.get.call_args_list[1].kwargs["params"]["page"] == 2
+ def test_whole_number_costs_are_emitted_as_floats(self):
+ # The oldest traces are fetched first and often carry a flat 0 cost. Left as ints they
+ # create an integer column, and the first fractional cost then fails the whole sync.
+ manager = self._manager()
+ rows, _ = self._run(
+ manager,
+ [_page([{"id": "t1", "totalCost": 0, "latency": 2}], page=1, total_pages=1)],
+ )
+ assert isinstance(rows[0]["totalCost"], float)
+ assert isinstance(rows[0]["latency"], float)
+ assert rows[0]["totalCost"] == 0.0
+ assert rows[0]["latency"] == 2.0
+
+ def test_non_integer_values_in_float_fields_are_left_alone(self):
+ manager = self._manager()
+ rows, _ = self._run(
+ manager,
+ [
+ _page(
+ [
+ {"id": "t1", "totalCost": 0.25, "latency": None},
+ {"id": "t2", "totalCost": "n/a", "latency": True},
+ ],
+ page=1,
+ total_pages=1,
+ )
+ ],
+ )
+ assert rows[0]["totalCost"] == 0.25
+ assert rows[0]["latency"] is None
+ # A string stays a string so a genuine upstream type change still surfaces, and a bool is
+ # not an int here even though Python says otherwise.
+ assert rows[1]["totalCost"] == "n/a"
+ assert rows[1]["latency"] is True
+
+ def test_fields_outside_float_fields_keep_their_type(self):
+ # scores.value is numeric only for NUMERIC scores, so it must not be widened.
+ manager = self._manager()
+ rows, _ = self._run(
+ manager,
+ [_cursor_page([{"id": "s1", "value": 1}, {"id": "s2", "value": "misc"}], cursor=None)],
+ endpoint="scores",
+ )
+ assert rows[0]["value"] == 1
+ assert not isinstance(rows[0]["value"], float)
+ assert rows[1]["value"] == "misc"
+
def test_page_pagination_saves_next_page_after_yield(self):
manager = self._manager()
self._run(