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(data-warehouse): fix langfuse score types and orphan job failures (#124242)

Tom Owers806aba4c62c1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
index 2378d2dd254a..b94ab2779dba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
@@ -563,14 +563,15 @@ async def _update_job_status(inputs: UpdateExternalDataJobStatusInputs, logger:
def _resolve_job() -> ExternalDataJob | None:
# Resolve this run's own job by run id; the finally-block update is the only finalizer for
# zero-batch runs (e.g. quiet Slack channels) that never send a batch to complete the job.
+ # The create-job activity stamps the run id on every row it inserts, so a miss means this run
+ # never created a job. The legacy fallback would then pick an unrelated RUNNING job, such as
+ # an orphan from an earlier run, and fail it with this run's error.
if inputs.workflow_run_id is not None:
- job = (
+ return (
ExternalDataJob.objects.filter(team_id=inputs.team_id, workflow_run_id=inputs.workflow_run_id)
.order_by("-created_at")
.first()
)
- if job is not None:
- return job
# Legacy fallback for runs started before workflow_run_id existed; racy under concurrent runs.
return (
ExternalDataJob.objects.filter(schema_id=inputs.schema_id, status=ExternalDataJob.Status.RUNNING)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/canonical_descriptions.py
index aa8235fb55fa..0d58620ebb0b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/canonical_descriptions.py
@@ -68,13 +68,14 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
},
},
"scores": {
- "description": "Evaluation scores attached to traces, observations, sessions, or experiments. The value type depends on dataType (numeric, boolean, categorical, text, or correction).",
+ "description": "Evaluation scores attached to traces, observations, sessions, or experiments. Numeric and boolean values are in value, text values are in stringValue.",
"docs_url": "https://api.reference.langfuse.com/#tag/scoresv3/get/api/public/v3/scores",
"columns": {
"id": "The unique identifier of the score.",
"projectId": "The project ID this score belongs to.",
"name": "The name of the score.",
- "value": "The score value. Its type depends on dataType: number for NUMERIC, boolean for BOOLEAN, string otherwise.",
+ "value": "The numeric score value. 1 or 0 for BOOLEAN scores, empty for CATEGORICAL, TEXT, and CORRECTION scores.",
+ "stringValue": "The text score value for CATEGORICAL, TEXT, and CORRECTION scores, or True or False for BOOLEAN scores.",
"dataType": "The data type of the score (NUMERIC, BOOLEAN, CATEGORICAL, TEXT, CORRECTION).",
"source": "The source of the score (e.g. API, ANNOTATION, EVAL).",
"timestamp": "The timestamp of the score.",
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 0803692b1dee..f2090a4d4b1a 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
@@ -335,6 +335,24 @@ def _coerce_float_fields(items: list[dict[str, Any]], float_fields: frozenset[st
item[field_name] = float(value)
+def _split_score_values(items: list[dict[str, Any]]) -> None:
+ """Keep score `value` numeric and move text values to `stringValue`, in place.
+
+ The type is read from the value and not from dataType, so a row without dataType still loads.
+ Booleans become 1.0 or 0.0 with "True" or "False" in `stringValue`, as in the legacy scores API.
+ """
+ for item in items:
+ value = item.get("value")
+ if isinstance(value, bool):
+ item["value"] = float(value)
+ item["stringValue"] = str(value)
+ elif isinstance(value, int | float):
+ item["value"] = float(value)
+ elif isinstance(value, str):
+ item["value"] = None
+ item["stringValue"] = value
+
+
def _list_parent_ids(
fetch_page: Callable[[str, dict[str, Any]], dict[str, Any]],
url: str,
@@ -488,6 +506,8 @@ def get_rows(
pages_fetched += 1
items = data.get("data") or []
_coerce_float_fields(items, config.float_fields)
+ if config.split_score_values:
+ _split_score_values(items)
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 ef10fdff3f97..74ddbb95d91d 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
@@ -57,6 +57,10 @@ 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()
+ # Split a score `value` whose type follows the row's dataType (a number, a boolean, or a string)
+ # into a numeric `value` and a text `stringValue`, the shape of the legacy scores API. Arrow holds
+ # one type per column, so a page that mixes NUMERIC and CATEGORICAL scores fails to load.
+ split_score_values: bool = False
# 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
@@ -132,8 +136,7 @@ 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.
+ split_score_values=True,
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 9facfc2eed17..b53f08cd4738 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
@@ -204,17 +204,32 @@ class TestGetRows:
assert rows[0]["totalCost"] == 0.0
assert rows[0]["latency"] == 2.0
- def test_fields_outside_float_fields_keep_their_type(self):
- # scores.value is numeric only for NUMERIC scores, so it must not be widened.
+ @pytest.mark.parametrize(
+ "raw_value, expected_value, expected_string_value",
+ [
+ (1, 1.0, None),
+ (0.25, 0.25, None),
+ (True, 1.0, "True"),
+ (False, 0.0, "False"),
+ ("needs_review", None, "needs_review"),
+ ("", None, ""),
+ (None, None, None),
+ ],
+ )
+ def test_score_value_is_split_into_numeric_and_text_columns(
+ self, raw_value: Any, expected_value: float | None, expected_string_value: str | None
+ ):
+ # A NUMERIC row on the same page keeps every page's `value` column numeric.
result = _driver().run(
"scores",
- [_cursor_page([{"id": "s1", "value": 1}, {"id": "s2", "value": "misc"}], cursor=None)],
+ [_cursor_page([{"id": "s0", "value": 3}, {"id": "s1", "value": raw_value}], cursor=None)],
)
rows = result.rows
assert result.raised is None
- assert rows[0]["value"] == 1
- assert not isinstance(rows[0]["value"], float)
- assert rows[1]["value"] == "misc"
+ assert rows[0]["value"] == 3.0 and isinstance(rows[0]["value"], float)
+ assert rows[1]["value"] == expected_value
+ assert type(rows[1]["value"]) is type(expected_value)
+ assert rows[1].get("stringValue") == expected_string_value
def test_resume_from_saved_cursor(self):
result = _driver().run(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_external_data_job.py
index b30cbc9dc586..c7156a803410 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_external_data_job.py
@@ -395,6 +395,56 @@ async def test_update_external_job_activity_resolves_job_by_workflow_run_id_when
assert other_run_job.status == ExternalDataJob.Status.RUNNING
[email protected]_db(transaction=True)
+async def test_update_external_job_activity_leaves_other_jobs_when_run_created_no_job(
+ activity_environment, team, **kwargs
+):
+ # When create-job times out before it inserts a row, the run has no job. An orphan RUNNING job
+ # from an earlier run must not be failed with this run's error.
+ new_source = await sync_to_async(ExternalDataSource.objects.create)(
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ team=team,
+ status="running",
+ source_type="Stripe",
+ )
+ schema = await sync_to_async(ExternalDataSchema.objects.create)(
+ name=STRIPE_BALANCE_TRANSACTION_RESOURCE_NAME,
+ team_id=team.id,
+ source_id=new_source.pk,
+ should_sync=True,
+ status=ExternalDataSchema.Status.RUNNING,
+ )
+ orphan_job = await _create_external_data_job(
+ team_id=team.id,
+ external_data_source_id=new_source.pk,
+ workflow_id=str(uuid.uuid4()),
+ workflow_run_id=str(uuid.uuid4()),
+ external_data_schema_id=schema.id,
+ )
+
+ inputs = UpdateExternalDataJobStatusInputs(
+ job_id=None,
+ status=ExternalDataJob.Status.FAILED,
+ latest_error="The activity timed out before it created the job",
+ internal_error="The activity timed out before it created the job",
+ schema_id=str(schema.pk),
+ source_id=str(new_source.pk),
+ team_id=team.id,
+ workflow_run_id=activity_environment.info.workflow_run_id,
+ )
+
+ await activity_environment.run(update_external_data_job_model, inputs)
+ await sync_to_async(orphan_job.refresh_from_db)()
+ await sync_to_async(schema.refresh_from_db)()
+
+ assert orphan_job.status == ExternalDataJob.Status.RUNNING
+ assert orphan_job.latest_error is None
+ assert schema.status == ExternalDataSchema.Status.FAILED
+
+
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_update_external_job_activity_with_retryable_error(activity_environment, team, **kwargs):