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.

feat(warehouse_sources): add langfuse score config and annotation queue tables (#113904)

Tom Owersd4a1062cb12e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index b0703cfb2329..8c38098a324d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -4969,15 +4969,15 @@ Note: The Lambda Cloud API v1.10.0 exposes 24 paths and every GET-able collectio
## Langfuse — gaps
-Today (8): `dataset_items`, `datasets`, `models`, `observations`, `prompts`, `scores`, `sessions`, `traces`
+Today (11): `annotation_queue_items`, `annotation_queues`, `dataset_items`, `datasets`, `models`, `observations`, `prompts`, `score_configs`, `scores`, `sessions`, `traces`
Diffed against: <https://cloud.langfuse.com/generated/api/openapi.yml>
-- [ ] `GET /api/public/dataset-run-items` — join table linking dataset items to the trace/observation produced in each eval run - without it synced dataset_items and traces cannot be joined (high)
-- [ ] `GET /api/public/datasets/{datasetName}/runs` — the eval run records that dataset-run-items and scores hang off; the unit of 'how did this prompt version do' (high)
-- [ ] `GET /api/public/score-configs` — lookup that resolves the config, data type and categorical values behind the score rows already synced (high)
+- [ ] `GET /api/public/dataset-run-items` — join table linking dataset items to the trace/observation produced in each eval run - without it synced dataset_items and traces cannot be joined (high) — skipped: deprecated, removed from Langfuse Cloud on 2026-11-16; superseded by `GET /api/public/experiment-items`
+- [ ] `GET /api/public/datasets/{datasetName}/runs` — the eval run records that dataset-run-items and scores hang off; the unit of 'how did this prompt version do' (high) — skipped: deprecated, removed from Langfuse Cloud on 2026-11-16; superseded by `GET /api/public/experiments`
+- [x] `GET /api/public/score-configs` — lookup that resolves the config, data type and categorical values behind the score rows already synced (high)
- [ ] `GET /api/public/experiments and GET /api/public/experiment-items` — experiment runs and their per-item results, the headline eval surface (medium)
-- [ ] `GET /api/public/annotation-queues, /{queueId}/items` — human annotation queue state and per-item status for review throughput analysis (medium)
+- [x] `GET /api/public/annotation-queues, /{queueId}/items` — human annotation queue state and per-item status for review throughput analysis (medium)
- [ ] `GET /api/public/comments` — human comments attached to traces/observations/sessions, useful for qualitative review joins (low)
- [ ] `GET /api/public/organizations/memberships and /projects/{projectId}/memberships` — org/project membership lookup resolving user ids seen on traces and annotations (org-scoped key required) (low)
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 fbd34fd3dd43..8200717e26ec 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
@@ -161,4 +161,47 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"isLangfuseManaged": "Whether the model definition is managed by Langfuse or user-defined.",
},
},
+ "score_configs": {
+ "description": "Score configurations that define the name, data type, and allowed values of the scores attached to traces, observations, and sessions.",
+ "docs_url": "https://api.reference.langfuse.com/#tag/scoreconfigs/get/api/public/score-configs",
+ "columns": {
+ "id": "The unique identifier of the score config. Scores reference it through configId.",
+ "name": "The name of the score config.",
+ "createdAt": "The timestamp when the score config was created.",
+ "updatedAt": "The timestamp when the score config was last updated.",
+ "projectId": "The Langfuse project the score config belongs to.",
+ "dataType": "The data type of scores that use this config (NUMERIC, BOOLEAN, CATEGORICAL, or TEXT).",
+ "isArchived": "Whether the score config is archived.",
+ "minValue": "The minimum allowed value for numeric scores. Unbounded if not set.",
+ "maxValue": "The maximum allowed value for numeric scores. Unbounded if not set.",
+ "categories": "The allowed categories (label and value) for categorical scores.",
+ "description": "A description of the score config.",
+ },
+ },
+ "annotation_queues": {
+ "description": "Annotation queues that collect traces, observations, or sessions for human review against a set of score configs.",
+ "docs_url": "https://api.reference.langfuse.com/#tag/annotationqueues/get/api/public/annotation-queues",
+ "columns": {
+ "id": "The unique identifier of the annotation queue.",
+ "name": "The name of the annotation queue.",
+ "description": "A description of the annotation queue.",
+ "scoreConfigIds": "The IDs of the score configs reviewers fill in for items in this queue.",
+ "createdAt": "The timestamp when the annotation queue was created.",
+ "updatedAt": "The timestamp when the annotation queue was last updated.",
+ },
+ },
+ "annotation_queue_items": {
+ "description": "Items in annotation queues: one trace, observation, or session waiting for or finished with human review.",
+ "docs_url": "https://api.reference.langfuse.com/#tag/annotationqueues/get/api/public/annotation-queues/{queueId}/items",
+ "columns": {
+ "id": "The unique identifier of the annotation queue item.",
+ "queueId": "The annotation queue the item belongs to.",
+ "objectId": "The ID of the trace, observation, or session to review.",
+ "objectType": "The type of the object to review (TRACE, OBSERVATION, or SESSION).",
+ "status": "The review status of the item (PENDING or COMPLETED).",
+ "completedAt": "The timestamp when the review of the item was completed.",
+ "createdAt": "The timestamp when the item was added to the queue.",
+ "updatedAt": "The timestamp when the item was last updated.",
+ },
+ },
}
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 7d45c34f2097..6669c25ec9c5 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
@@ -1,11 +1,12 @@
import re
import json
import time
+import bisect
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
-from urllib.parse import urlparse
+from urllib.parse import quote, urlparse
import requests
from structlog.types import FilteringBoundLogger
@@ -45,6 +46,12 @@ RESPONSE_CHUNK_BYTES = 1024 * 1024
# allows 2.5M rows per run on page endpoints and 50M observations, far above a normal sync.
MAX_PAGES_PER_RUN = 50_000
+# Parent ids are all held in memory before the first child row is yielded, so cap what a hostile host
+# can make a worker retain. Real queue ids are short cuids; this allows far more than any real project.
+MAX_PARENT_ID_BYTES = 16 * 1024 * 1024
+# Rough per-id cost of the str object and set slot, so many short ids count against the budget too.
+PARENT_ID_OVERHEAD_BYTES = 64
+
DEFAULT_HOST = "https://cloud.langfuse.com"
HOST_NOT_ALLOWED_ERROR = "Langfuse host is not allowed"
HTTP_NOT_ALLOWED_ERROR = "Langfuse host must use HTTPS"
@@ -80,7 +87,7 @@ class LangfusePaginationError(Exception):
pass
[email protected](frozen=False)
class LangfuseResumeConfig:
# Next page number ("page" endpoints) or opaque cursor ("cursor" endpoints) to fetch.
page: int | None = None
@@ -89,6 +96,8 @@ class LangfuseResumeConfig:
# saved page/cursor stays aligned with the query it was produced by (the incremental watermark
# can advance mid-run for ascending endpoints).
from_value: str | None = None
+ # Parent row the saved page belongs to, for fan-out endpoints.
+ parent_id: str | None = None
def normalize_host(host: str | None) -> str:
@@ -319,6 +328,38 @@ def _coerce_float_fields(items: list[dict[str, Any]], float_fields: frozenset[st
item[field_name] = float(value)
+def _list_parent_ids(
+ fetch_page: Callable[[str, dict[str, Any]], dict[str, Any]],
+ url: str,
+ config: LangfuseEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[LangfuseResumeConfig],
+) -> list[str]:
+ """Every parent row id, sorted so a saved parent_id marks a stable resume position."""
+ ids: set[str] = set()
+ retained_bytes = 0
+ page = 1
+ while True:
+ data = fetch_page(url, {"limit": config.page_size, "page": page})
+ items = data.get("data") or []
+ for item in items:
+ parent_id = str(item["id"]) if item.get("id") else None
+ if parent_id is not None and parent_id not in ids:
+ retained_bytes += PARENT_ID_OVERHEAD_BYTES + len(parent_id.encode())
+ if retained_bytes > MAX_PARENT_ID_BYTES:
+ raise LangfuseResponseTooLargeError(
+ f"{RESPONSE_LIMIT_ERROR}: {config.name} ids exceeded {MAX_PARENT_ID_BYTES} bytes"
+ )
+ ids.add(parent_id)
+ total_pages = (data.get("meta") or {}).get("totalPages")
+ if not items or total_pages is None or page >= total_pages:
+ return sorted(ids)
+ if page >= MAX_PAGES_PER_RUN:
+ raise LangfusePaginationError(f"{PAGE_LIMIT_ERROR}: {page} pages fetched from {config.name}")
+ # Nothing is yielded while the parents are listed, so give the pipeline a chance to hand off.
+ resumable_source_manager.safe_point()
+ page += 1
+
+
def get_rows(
host: str | None,
public_key: str,
@@ -343,16 +384,18 @@ def get_rows(
page: int = 1
cursor: str | None = None
+ resume_parent_id: str | None = None
resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
if resume_config is not None:
# Reuse the interrupted run's from-filter so the saved page/cursor matches its query.
from_value = resume_config.from_value
page = resume_config.page or 1
cursor = resume_config.cursor
- logger.debug(f"Langfuse: resuming {endpoint} from page={page}, cursor={cursor}")
+ resume_parent_id = resume_config.parent_id
+ logger.debug(f"Langfuse: resuming {endpoint} from page={page}, cursor={cursor}, parent={resume_parent_id}")
base_params = _build_params(config, from_value)
- url = f"{normalize_host(host)}{config.path}"
+ base_url = normalize_host(host)
auth = (public_key.strip(), secret_key.strip())
# One session reused across every page so urllib3 keeps the connection alive instead of
# re-handshaking per request. `retry=Retry(total=0)` disables adapter-level retries, whose
@@ -367,7 +410,7 @@ def get_rows(
wait=_retry_wait,
reraise=True,
)
- def fetch_page(params: dict[str, Any]) -> dict[str, Any]:
+ def fetch_page(url: str, params: dict[str, Any]) -> dict[str, Any]:
# stream=True so the (customer-controlled) body isn't buffered until we read it under a cap.
# Don't follow redirects: an attacker-controlled host could 3xx to an internal address (SSRF).
response = session.get(
@@ -399,15 +442,42 @@ def get_rows(
return json.loads(body)
+ parent_ids: list[str | None] = [None]
+ parent_index = 0
+ if config.parent is not None:
+ parent_config = LANGFUSE_ENDPOINTS[config.parent]
+ ids = _list_parent_ids(fetch_page, f"{base_url}{parent_config.path}", parent_config, resumable_source_manager)
+ if resume_parent_id is not None:
+ parent_index = bisect.bisect_left(ids, resume_parent_id)
+ # The saved parent was deleted since the interrupted run, so start its successor from the top.
+ if parent_index < len(ids) and ids[parent_index] != resume_parent_id:
+ page = 1
+ if parent_index >= len(ids):
+ return
+ parent_ids = list(ids)
+
pages_fetched = 0
while True:
+ parent_id = parent_ids[parent_index]
+ if parent_id is None:
+ url = f"{base_url}{config.path}"
+ else:
+ url = f"{base_url}{config.path.format(parent_id=quote(parent_id, safe=''))}"
+ next_parent_id = parent_ids[parent_index + 1] if parent_index + 1 < len(parent_ids) else None
+
params = dict(base_params)
if config.pagination == "page":
params["page"] = page
elif cursor is not None:
params["cursor"] = cursor
- data = fetch_page(params)
+ try:
+ data = fetch_page(url, params)
+ except requests.HTTPError as e:
+ # A parent deleted after it was listed has no child route anymore.
+ if parent_id is None or e.response is None or e.response.status_code != 404:
+ raise
+ data = {}
pages_fetched += 1
items = data.get("data") or []
_coerce_float_fields(items, config.float_fields)
@@ -418,7 +488,9 @@ def get_rows(
total_pages = meta.get("totalPages")
has_next = bool(items) and total_pages is not None and page < total_pages
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)
+ next_state = LangfuseResumeConfig(
+ page=1 if advanced else page + 1, from_value=advanced or from_value, parent_id=parent_id
+ )
else:
next_cursor = meta.get("cursor")
# A compliant server never hands back the cursor it was just given; looping on it would
@@ -427,16 +499,25 @@ def get_rows(
if next_cursor is not None and next_cursor == cursor:
raise LangfusePaginationError(f"{REPEATED_CURSOR_ERROR} (endpoint {endpoint})")
has_next = bool(items) and next_cursor is not None
- next_state = LangfuseResumeConfig(cursor=next_cursor, from_value=from_value)
+ next_state = LangfuseResumeConfig(cursor=next_cursor, from_value=from_value, parent_id=parent_id)
+
+ if not has_next and next_parent_id is not None:
+ next_state = LangfuseResumeConfig(page=1, from_value=from_value, parent_id=next_parent_id)
+ has_more = has_next or next_parent_id is not None
if items:
yield items
# Save AFTER yielding (and only when more pages remain) so a crash re-yields the last
# page rather than skipping it — merge dedupes on the primary key.
- if has_next:
+ if has_more:
resumable_source_manager.save_state(next_state)
+ elif has_more:
+ # An empty parent yields nothing. Every earlier row is already yielded, so moving the
+ # checkpoint on and handing off here loses nothing.
+ resumable_source_manager.save_state(next_state)
+ resumable_source_manager.safe_point()
- if not has_next:
+ if not has_more:
break
# The checkpoint above already points at the next page, so raising here (retryable) lets a
@@ -448,7 +529,11 @@ def get_rows(
resumable_source_manager.safe_point()
raise LangfusePaginationError(f"{PAGE_LIMIT_ERROR}: {pages_fetched} pages fetched from {endpoint}")
- if config.pagination == "page":
+ if not has_next:
+ parent_index += 1
+ page = 1
+ cursor = None
+ elif config.pagination == "page":
page = next_state.page or 1
if next_state.from_value != from_value:
from_value = next_state.from_value
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 9d03221e33cd..cc6a84f49415 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
@@ -61,6 +61,9 @@ class LangfuseEndpointConfig:
# 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
+ # Fan-out child: `path` holds a `{parent_id}` placeholder, filled with the `id` of every row of
+ # this parent endpoint.
+ parent: Optional[str] = None
_DEFAULT_LOOKBACK = timedelta(hours=1)
@@ -73,7 +76,8 @@ _OBSERVATION_FIELDS = "core,basic,time,io,metadata,model,usage,prompt,metrics,tr
_SCORE_FIELDS = "details,subject,annotation"
# Endpoints cover the resources a user most commonly wants to analyze from an LLM observability
-# platform: traces, observations, scores, sessions, prompts, datasets, and model pricing.
+# platform: traces, observations, scores, sessions, prompts, datasets, model pricing, score
+# configs, and annotation queues.
# Incremental support is only declared where the API documents a server-side timestamp filter.
LANGFUSE_ENDPOINTS: dict[str, LangfuseEndpointConfig] = {
"traces": LangfuseEndpointConfig(
@@ -169,6 +173,32 @@ LANGFUSE_ENDPOINTS: dict[str, LangfuseEndpointConfig] = {
page_size=50,
# No server-side timestamp filter -> full refresh only.
),
+ "score_configs": LangfuseEndpointConfig(
+ name="score_configs",
+ path="/api/public/score-configs",
+ pagination="page",
+ page_size=50,
+ # No server-side timestamp filter -> full refresh only.
+ partition_key="createdAt",
+ ),
+ "annotation_queues": LangfuseEndpointConfig(
+ name="annotation_queues",
+ path="/api/public/annotation-queues",
+ pagination="page",
+ page_size=50,
+ # No server-side timestamp filter -> full refresh only.
+ partition_key="createdAt",
+ ),
+ "annotation_queue_items": LangfuseEndpointConfig(
+ name="annotation_queue_items",
+ path="/api/public/annotation-queues/{parent_id}/items",
+ pagination="page",
+ page_size=50,
+ parent="annotation_queues",
+ # Only filterable by status, not by time -> full refresh only.
+ primary_keys=["queueId", "id"],
+ partition_key="createdAt",
+ ),
}
ENDPOINTS = tuple(LANGFUSE_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/source.py
index 41fdb0f1f63e..dd7d98fc4dd3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/source.py
@@ -66,7 +66,7 @@ class LangfuseSource(ResumableSource[LangfuseSourceConfig, LangfuseResumeConfig]
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Langfuse",
releaseStatus=ReleaseStatus.ALPHA,
- caption="""Sync traces, observations, scores, sessions, prompts, and datasets from your Langfuse project.
+ caption="""Sync traces, observations, scores, sessions, prompts, datasets, and annotation queues from your Langfuse project.
Find your project API keys in your Langfuse **Project settings > API Keys**. Set the host to match your data region (`https://cloud.langfuse.com` for EU, `https://us.cloud.langfuse.com` for US) or your self-hosted instance URL.""",
iconPath="/static/services/langfuse.svg",
@@ -114,9 +114,10 @@ Find your project API keys in your Langfuse **Project settings > API Keys**. Set
return {
"401 Client Error": "Invalid Langfuse API keys. Check the project public key and secret key, and make sure the host matches your Langfuse data region.",
"403 Client Error": "Your Langfuse API keys do not have access to this resource. Check the keys and try again.",
- # Every LANGFUSE_ENDPOINTS path is a collection route (no resource id in the URL), so a
- # 404 here means the route itself doesn't exist on this host - typically a self-hosted
- # instance running a Langfuse version that predates this endpoint. Retrying never helps.
+ # Every LANGFUSE_ENDPOINTS path is a collection route, and get_rows skips a fan-out child
+ # whose parent was deleted, so a 404 here means the route itself doesn't exist on this
+ # host - typically a self-hosted instance running a Langfuse version that predates this
+ # endpoint. Retrying never helps.
"404 Client Error": "This Langfuse endpoint was not found on your host. Self-hosted instances on an older Langfuse version may not support it yet - upgrade your instance or remove this table from the sync.",
HOST_NOT_ALLOWED_ERROR: "The Langfuse host is not allowed. Please use a publicly reachable instance URL.",
HTTP_NOT_ALLOWED_ERROR: "The Langfuse host must use HTTPS. Please update the host to use https://.",
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 68fd2b7d779b..cfb6df428f5d 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
@@ -5,6 +5,8 @@ from typing import Any, Optional
import pytest
from unittest import mock
+import requests
+
from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse import langfuse as langfuse_module
from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.langfuse import (
HOST_NOT_ALLOWED_ERROR,
@@ -56,6 +58,12 @@ def _trace(trace_id: str, timestamp: str) -> dict[str, Any]:
return {"id": trace_id, "timestamp": timestamp}
+def _not_found() -> mock.MagicMock:
+ response = _response(status_code=404, text="Not found")
+ response.raise_for_status.side_effect = requests.HTTPError("404 Client Error", response=response)
+ return response
+
+
def _cursor_page(items: list[dict[str, Any]], *, cursor: Optional[str]) -> mock.MagicMock:
return _response(json_data={"data": items, "meta": {"cursor": cursor}})
@@ -416,6 +424,72 @@ class TestGetRows:
assert langfuse_module.PAGE_LIMIT_ERROR in str(exc.value)
assert manager.save_state.call_args.args[0].page == 3
+ def test_parent_id_listing_over_byte_budget_raises_non_retryable(self):
+ # Parent ids are all buffered before the first child row is yielded, so a hostile host
+ # streaming unique large ids must be cut off at the budget rather than grow worker memory.
+ manager = self._manager()
+ with (
+ mock.patch.object(langfuse_module, "MAX_PARENT_ID_BYTES", 100),
+ pytest.raises(langfuse_module.LangfuseResponseTooLargeError) as exc,
+ ):
+ self._run(
+ manager,
+ [_page([{"id": "q-aaaaaa"}, {"id": "q-bbbbbb"}], page=1, total_pages=1)],
+ endpoint="annotation_queue_items",
+ )
+ assert langfuse_module.RESPONSE_LIMIT_ERROR in str(exc.value)
+
+ def test_fan_out_walks_every_parent_and_checkpoints_the_next_one(self):
+ manager = self._manager()
+ rows, session = self._run(
+ manager,
+ [
+ _page([{"id": "q-c"}, {"id": "q/a"}], page=1, total_pages=2),
+ _page([{"id": "q-b"}], page=2, total_pages=2),
+ _page([{"id": "i1", "queueId": "q-b"}], page=1, total_pages=2),
+ _page([{"id": "i2", "queueId": "q-b"}], page=2, total_pages=2),
+ _not_found(),
+ _page([{"id": "i3", "queueId": "q/a"}], page=1, total_pages=1),
+ ],
+ endpoint="annotation_queue_items",
+ )
+
+ assert [r["id"] for r in rows] == ["i1", "i2", "i3"]
+ urls = [c.args[0] for c in session.get.call_args_list]
+ assert urls[2:] == [
+ "https://cloud.langfuse.com/api/public/annotation-queues/q-b/items",
+ "https://cloud.langfuse.com/api/public/annotation-queues/q-b/items",
+ "https://cloud.langfuse.com/api/public/annotation-queues/q-c/items",
+ "https://cloud.langfuse.com/api/public/annotation-queues/q%2Fa/items",
+ ]
+ saved = [(c.args[0].parent_id, c.args[0].page) for c in manager.save_state.call_args_list]
+ assert saved == [("q-b", 2), ("q-c", 1), ("q/a", 1)]
+
+ @pytest.mark.parametrize(
+ "saved_parent, expected_url_parent, expected_page",
+ [
+ ("q-b", "q-b", 3),
+ # The saved parent was deleted, so its successor starts from its first page.
+ ("q-bb", "q-c", 1),
+ ],
+ )
+ def test_fan_out_resumes_from_saved_parent(self, saved_parent, expected_url_parent, expected_page):
+ manager = self._manager(LangfuseResumeConfig(page=3, parent_id=saved_parent))
+ rows, session = self._run(
+ manager,
+ [
+ _page([{"id": "q-a"}, {"id": "q-b"}, {"id": "q-c"}], page=1, total_pages=1),
+ _page([{"id": "i9", "queueId": expected_url_parent}], page=expected_page, total_pages=expected_page),
+ _page([], page=1, total_pages=0),
+ ],
+ endpoint="annotation_queue_items",
+ )
+
+ assert [r["id"] for r in rows] == ["i9"]
+ resumed = session.get.call_args_list[1]
+ assert resumed.args[0].endswith(f"/annotation-queues/{expected_url_parent}/items")
+ assert resumed.kwargs["params"]["page"] == expected_page
+
class TestRetryBehavior:
@pytest.mark.parametrize(