Skip to content

The platform for continuously improving AI agents.

Make Langfuse imports resumable with measured sync progress (#285)

Tyler-Edwardscd6607756cc9
diff --git a/frontend/src/openapi/.openapi-generator/FILES b/frontend/src/openapi/.openapi-generator/FILES
index 724daf5b..ff3be5b1 100644
--- a/frontend/src/openapi/.openapi-generator/FILES
+++ b/frontend/src/openapi/.openapi-generator/FILES
@@ -110,6 +110,8 @@ models/ConnectorShapeCandidate.ts
models/ConnectorSourceProject.ts
models/ConnectorSyncConfigCreateResponse.ts
models/ConnectorSyncConfigWriteRequest.ts
+models/ConnectorSyncProgress.ts
+models/ConnectorSyncProgressStateEnum.ts
models/ConnectorSyncRun.ts
models/ConnectorSyncRunModeEnum.ts
models/ConnectorSyncRunStatusEnum.ts
diff --git a/frontend/src/openapi/models/ConnectorCredential.ts b/frontend/src/openapi/models/ConnectorCredential.ts
index d86242fe..e88fa4e6 100644
--- a/frontend/src/openapi/models/ConnectorCredential.ts
+++ b/frontend/src/openapi/models/ConnectorCredential.ts
@@ -13,6 +13,13 @@
*/
import { mapValues } from '../runtime';
+import type { ConnectorSyncProgress } from './ConnectorSyncProgress';
+import {
+ ConnectorSyncProgressFromJSON,
+ ConnectorSyncProgressFromJSONTyped,
+ ConnectorSyncProgressToJSON,
+ ConnectorSyncProgressToJSONTyped,
+} from './ConnectorSyncProgress';
import type { ApiVersionEnum } from './ApiVersionEnum';
import {
ApiVersionEnumFromJSON,
@@ -126,6 +133,12 @@ export interface ConnectorCredential {
* @memberof ConnectorCredential
*/
readonly backfillTotal: number | null;
+ /**
+ *
+ * @type {ConnectorSyncProgress}
+ * @memberof ConnectorCredential
+ */
+ readonly syncProgress: ConnectorSyncProgress | null;
/**
*
* @type {string}
@@ -204,6 +217,7 @@ export function instanceOfConnectorCredential(value: object): value is Connector
if (!('syncStatus' in value) || value['syncStatus'] === undefined) return false;
if (!('backfillImported' in value) || value['backfillImported'] === undefined) return false;
if (!('backfillTotal' in value) || value['backfillTotal'] === undefined) return false;
+ if (!('syncProgress' in value) || value['syncProgress'] === undefined) return false;
if (!('syncError' in value) || value['syncError'] === undefined) return false;
if (!('apiVersion' in value) || value['apiVersion'] === undefined) return false;
if (!('verifiedAt' in value) || value['verifiedAt'] === undefined) return false;
@@ -239,6 +253,7 @@ export function ConnectorCredentialFromJSONTyped(json: any, ignoreDiscriminator:
'syncStatus': SyncStatusEnumFromJSON(json['sync_status']),
'backfillImported': json['backfill_imported'],
'backfillTotal': json['backfill_total'],
+ 'syncProgress': ConnectorSyncProgressFromJSON(json['sync_progress']),
'syncError': json['sync_error'],
'apiVersion': ApiVersionEnumFromJSON(json['api_version']),
'verifiedAt': (json['verified_at'] == null ? null : new Date(json['verified_at'])),
@@ -256,7 +271,7 @@ export function ConnectorCredentialToJSON(json: any): ConnectorCredential {
return ConnectorCredentialToJSONTyped(json, false);
}
-export function ConnectorCredentialToJSONTyped(value?: Omit<ConnectorCredential, 'id'|'api_key_hint'|'is_active'|'last_synced_at'|'sync_status'|'backfill_imported'|'backfill_total'|'sync_error'|'api_version'|'verified_at'|'total_spans_imported'|'total_traces_imported'|'next_poll_at'|'active_config'|'created_at'|'updated_at'> | null, ignoreDiscriminator: boolean = false): any {
+export function ConnectorCredentialToJSONTyped(value?: Omit<ConnectorCredential, 'id'|'api_key_hint'|'is_active'|'last_synced_at'|'sync_status'|'backfill_imported'|'backfill_total'|'sync_progress'|'sync_error'|'api_version'|'verified_at'|'total_spans_imported'|'total_traces_imported'|'next_poll_at'|'active_config'|'created_at'|'updated_at'> | null, ignoreDiscriminator: boolean = false): any {
if (value == null) {
return value;
}
diff --git a/frontend/src/openapi/models/ConnectorSyncProgress.ts b/frontend/src/openapi/models/ConnectorSyncProgress.ts
new file mode 100644
index 00000000..9d834268
--- /dev/null
+++ b/frontend/src/openapi/models/ConnectorSyncProgress.ts
@@ -0,0 +1,156 @@
+/* tslint:disable */
+/* eslint-disable */
+/**
+ * Overbae API
+ * Backend API for the Overclaw / Overmind platform.
+ *
+ * The version of the OpenAPI document: 2.0.0
+ *
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+import { mapValues } from '../runtime';
+import type { ConnectorSyncProgressStateEnum } from './ConnectorSyncProgressStateEnum';
+import {
+ ConnectorSyncProgressStateEnumFromJSON,
+ ConnectorSyncProgressStateEnumFromJSONTyped,
+ ConnectorSyncProgressStateEnumToJSON,
+ ConnectorSyncProgressStateEnumToJSONTyped,
+} from './ConnectorSyncProgressStateEnum';
+
+/**
+ *
+ * @export
+ * @interface ConnectorSyncProgress
+ */
+export interface ConnectorSyncProgress {
+ /**
+ *
+ * @type {ConnectorSyncProgressStateEnum}
+ * @memberof ConnectorSyncProgress
+ */
+ state: ConnectorSyncProgressStateEnum;
+ /**
+ *
+ * @type {number}
+ * @memberof ConnectorSyncProgress
+ */
+ totalEstimate: number | null;
+ /**
+ *
+ * @type {number}
+ * @memberof ConnectorSyncProgress
+ */
+ observationsTotal: number | null;
+ /**
+ *
+ * @type {number}
+ * @memberof ConnectorSyncProgress
+ */
+ imported: number;
+ /**
+ *
+ * @type {string}
+ * @memberof ConnectorSyncProgress
+ */
+ countBasis: string;
+ /**
+ *
+ * @type {number}
+ * @memberof ConnectorSyncProgress
+ */
+ tracesPerSecond: number | null;
+ /**
+ *
+ * @type {number}
+ * @memberof ConnectorSyncProgress
+ */
+ estimatedSecondsRemaining: number | null;
+ /**
+ *
+ * @type {Date}
+ * @memberof ConnectorSyncProgress
+ */
+ countedAt: Date | null;
+ /**
+ *
+ * @type {Date}
+ * @memberof ConnectorSyncProgress
+ */
+ lastProgressAt: Date | null;
+ /**
+ *
+ * @type {Date}
+ * @memberof ConnectorSyncProgress
+ */
+ retryAt: Date | null;
+}
+
+
+
+/**
+ * Check if a given object implements the ConnectorSyncProgress interface.
+ */
+export function instanceOfConnectorSyncProgress(value: object): value is ConnectorSyncProgress {
+ if (!('state' in value) || value['state'] === undefined) return false;
+ if (!('totalEstimate' in value) || value['totalEstimate'] === undefined) return false;
+ if (!('observationsTotal' in value) || value['observationsTotal'] === undefined) return false;
+ if (!('imported' in value) || value['imported'] === undefined) return false;
+ if (!('countBasis' in value) || value['countBasis'] === undefined) return false;
+ if (!('tracesPerSecond' in value) || value['tracesPerSecond'] === undefined) return false;
+ if (!('estimatedSecondsRemaining' in value) || value['estimatedSecondsRemaining'] === undefined) return false;
+ if (!('countedAt' in value) || value['countedAt'] === undefined) return false;
+ if (!('lastProgressAt' in value) || value['lastProgressAt'] === undefined) return false;
+ if (!('retryAt' in value) || value['retryAt'] === undefined) return false;
+ return true;
+}
+
+export function ConnectorSyncProgressFromJSON(json: any): ConnectorSyncProgress {
+ return ConnectorSyncProgressFromJSONTyped(json, false);
+}
+
+export function ConnectorSyncProgressFromJSONTyped(json: any, ignoreDiscriminator: boolean): ConnectorSyncProgress {
+ if (json == null) {
+ return json;
+ }
+ return {
+
+ 'state': ConnectorSyncProgressStateEnumFromJSON(json['state']),
+ 'totalEstimate': json['total_estimate'],
+ 'observationsTotal': json['observations_total'],
+ 'imported': json['imported'],
+ 'countBasis': json['count_basis'],
+ 'tracesPerSecond': json['traces_per_second'],
+ 'estimatedSecondsRemaining': json['estimated_seconds_remaining'],
+ 'countedAt': (json['counted_at'] == null ? null : new Date(json['counted_at'])),
+ 'lastProgressAt': (json['last_progress_at'] == null ? null : new Date(json['last_progress_at'])),
+ 'retryAt': (json['retry_at'] == null ? null : new Date(json['retry_at'])),
+ };
+}
+
+export function ConnectorSyncProgressToJSON(json: any): ConnectorSyncProgress {
+ return ConnectorSyncProgressToJSONTyped(json, false);
+}
+
+export function ConnectorSyncProgressToJSONTyped(value?: ConnectorSyncProgress | null, ignoreDiscriminator: boolean = false): any {
+ if (value == null) {
+ return value;
+ }
+
+ return {
+
+ 'state': ConnectorSyncProgressStateEnumToJSON(value['state']),
+ 'total_estimate': value['totalEstimate'],
+ 'observations_total': value['observationsTotal'],
+ 'imported': value['imported'],
+ 'count_basis': value['countBasis'],
+ 'traces_per_second': value['tracesPerSecond'],
+ 'estimated_seconds_remaining': value['estimatedSecondsRemaining'],
+ 'counted_at': value['countedAt'] == null ? value['countedAt'] : value['countedAt'].toISOString(),
+ 'last_progress_at': value['lastProgressAt'] == null ? value['lastProgressAt'] : value['lastProgressAt'].toISOString(),
+ 'retry_at': value['retryAt'] == null ? value['retryAt'] : value['retryAt'].toISOString(),
+ };
+}
diff --git a/frontend/src/openapi/models/ConnectorSyncProgressStateEnum.ts b/frontend/src/openapi/models/ConnectorSyncProgressStateEnum.ts
new file mode 100644
index 00000000..05ae7761
--- /dev/null
+++ b/frontend/src/openapi/models/ConnectorSyncProgressStateEnum.ts
@@ -0,0 +1,57 @@
+/* tslint:disable */
+/* eslint-disable */
+/**
+ * Overbae API
+ * Backend API for the Overclaw / Overmind platform.
+ *
+ * The version of the OpenAPI document: 2.0.0
+ *
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+
+/**
+ * * `estimating` - estimating
+ * * `importing` - importing
+ * * `waiting` - waiting
+ * * `complete` - complete
+ * @export
+ */
+export const ConnectorSyncProgressStateEnum = {
+ estimating: 'estimating',
+ importing: 'importing',
+ waiting: 'waiting',
+ complete: 'complete'
+} as const;
+export type ConnectorSyncProgressStateEnum = typeof ConnectorSyncProgressStateEnum[keyof typeof ConnectorSyncProgressStateEnum];
+
+
+export function instanceOfConnectorSyncProgressStateEnum(value: any): boolean {
+ for (const key in ConnectorSyncProgressStateEnum) {
+ if (Object.prototype.hasOwnProperty.call(ConnectorSyncProgressStateEnum, key)) {
+ if (ConnectorSyncProgressStateEnum[key as keyof typeof ConnectorSyncProgressStateEnum] === value) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+export function ConnectorSyncProgressStateEnumFromJSON(json: any): ConnectorSyncProgressStateEnum {
+ return ConnectorSyncProgressStateEnumFromJSONTyped(json, false);
+}
+
+export function ConnectorSyncProgressStateEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): ConnectorSyncProgressStateEnum {
+ return json as ConnectorSyncProgressStateEnum;
+}
+
+export function ConnectorSyncProgressStateEnumToJSON(value?: ConnectorSyncProgressStateEnum | null): any {
+ return value as any;
+}
+
+export function ConnectorSyncProgressStateEnumToJSONTyped(value: any, ignoreDiscriminator: boolean): ConnectorSyncProgressStateEnum {
+ return value as ConnectorSyncProgressStateEnum;
+}
diff --git a/frontend/src/openapi/models/index.ts b/frontend/src/openapi/models/index.ts
index 6065a267..c7c2b09a 100644
--- a/frontend/src/openapi/models/index.ts
+++ b/frontend/src/openapi/models/index.ts
@@ -68,6 +68,8 @@ export * from './ConnectorShapeCandidate';
export * from './ConnectorSourceProject';
export * from './ConnectorSyncConfigCreateResponse';
export * from './ConnectorSyncConfigWriteRequest';
+export * from './ConnectorSyncProgress';
+export * from './ConnectorSyncProgressStateEnum';
export * from './ConnectorSyncRun';
export * from './ConnectorSyncRunModeEnum';
export * from './ConnectorSyncRunStatusEnum';
diff --git a/frontend/src/routes/_auth/observability_.integrations.tsx b/frontend/src/routes/_auth/observability_.integrations.tsx
index 422481ef..2d148284 100644
--- a/frontend/src/routes/_auth/observability_.integrations.tsx
+++ b/frontend/src/routes/_auth/observability_.integrations.tsx
@@ -10,6 +10,7 @@ import { ConnectorSetupWizard } from "@/components/connectors/setup-wizard";
import { CreateProjectDialog } from "@/components/create-project";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { DateTime } from "@/components/ui/datetime";
import { FloatingNudge } from "@/components/ui/floating-nudge";
@@ -18,7 +19,6 @@ import { Label } from "@/components/ui/label";
import { PageHeader } from "@/components/ui/page-header";
import { PageShell } from "@/components/ui/page-shell";
import { Progress } from "@/components/ui/progress";
-import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { SortableHeader } from "@/components/ui/sortable-header";
import { LoadingState } from "@/components/ui/spinner";
@@ -63,27 +63,35 @@ function SyncStatusLine({ credential }: { credential: ConnectorCredential }) {
const { syncStatus, backfillImported, backfillTotal, syncError, lastSyncedAt, nextPollAt } =
credential;
- if (!credential.autoSyncEnabled && syncStatus !== "backfilling" && syncStatus !== "live") {
+ if (
+ !credential.autoSyncEnabled &&
+ syncStatus !== "backfilling" &&
+ syncStatus !== "live" &&
+ syncStatus !== "error"
+ ) {
return <span className="text-xs text-muted-foreground">Auto-sync off</span>;
}
- if (syncStatus === "backfilling") {
- // Prefer totalTracesImported — same unit as the Traces stat.
- // No Spinner: lookback walks many (often empty) windows after the count
- // stops moving; a spinner reads as "still importing" when history scan
- // is just draining older days.
- const tracesDone = credential.totalTracesImported || backfillImported;
+ if (syncStatus === "backfilling" || (syncStatus === "error" && credential.syncProgress)) {
+ const progress = credential.syncProgress;
+ const tracesDone = progress?.imported ?? credential.totalTracesImported ?? backfillImported;
+ const total = progress?.totalEstimate ?? backfillTotal;
const pct =
- backfillTotal && backfillTotal > 0
- ? Math.round((tracesDone / backfillTotal) * 100)
- : undefined;
+ total && total > 0 ? Math.min(99, Math.round((tracesDone / total) * 100)) : undefined;
+ const seconds = progress?.estimatedSecondsRemaining;
return (
<div className="flex min-w-[180px] flex-col gap-1">
<span className="text-xs text-muted-foreground">
- Importing history · {tracesDone.toLocaleString()}
- {backfillTotal ? ` / ~${backfillTotal.toLocaleString()}` : ""} traces
+ {progress?.state === "waiting" ? "Waiting for provider" : "Importing"}
+ {" · "}
+ {tracesDone.toLocaleString()}
+ {total != null && total > 0 ? ` / ~${total.toLocaleString()}` : ""} traces
+ {seconds != null && progress?.state !== "waiting" && (
+ <> · ~{Math.max(1, Math.ceil(seconds / 60)).toLocaleString()} min left</>
+ )}
</span>
- {pct != null && <Progress label="Backfill progress" percent={pct} />}
+ {pct != null && <Progress label="Estimated backfill progress" percent={pct} />}
+ {syncError && <span className="text-xs text-destructive">{syncError}</span>}
</div>
);
}
@@ -444,7 +452,6 @@ interface ConnectorSectionProps {
meta: ConnectorMeta;
credentials: ConnectorCredential[];
projectId: string;
- isLast: boolean;
/** Called when the user wants to add a connection but has no project yet. */
onRequireProject: () => void;
onSyncStarted?: (info: SyncStartedInfo) => void;
@@ -455,7 +462,6 @@ function ConnectorSection({
meta,
credentials,
projectId,
- isLast,
onRequireProject,
onSyncStarted,
onSyncKicked,
@@ -522,8 +528,6 @@ function ConnectorSection({
)}
</div>
- {!isLast && <Separator />}
-
{/* Available connectors use the setup wizard; others fall back to the credentials dialog. */}
{projectId &&
(meta.available ? (
@@ -642,19 +646,18 @@ function IntegrationsPage() {
</div>
)}
- <div className="rounded-md border border-border">
- {CONNECTORS.map((meta, i) => (
- <div className="px-4" key={meta.type}>
+ <div className="flex flex-col gap-4">
+ {CONNECTORS.map((meta) => (
+ <Card className="bg-transparent px-4" key={meta.type}>
<ConnectorSection
credentials={credentialsByType[meta.type] ?? []}
- isLast={i === CONNECTORS.length - 1}
meta={meta}
onRequireProject={() => setCreateProjectOpen(true)}
onSyncKicked={bumpFastPoll}
onSyncStarted={setPostSync}
projectId={projectId}
/>
- </div>
+ </Card>
))}
</div>
diff --git a/overbae/api/serializers.py b/overbae/api/serializers.py
index 192c3ce7..8f4cd11b 100644
--- a/overbae/api/serializers.py
+++ b/overbae/api/serializers.py
@@ -47,6 +47,7 @@ from overbae.services.codebase.flow import (
capability_input_keys,
capability_tool_names,
)
+from overbae.services.connectors.progress import sync_progress
from overbae.services.datasets import use as dataset_use
from overbae.services.datasets.lifecycle import DatasetError
from overbae.services.deployment import deployment_progress
@@ -2257,6 +2258,19 @@ class ConnectorCapabilityMappingResponseSerializer(serializers.Serializer):
relabeled_span_count = serializers.IntegerField()
+class ConnectorSyncProgressSerializer(serializers.Serializer):
+ state = serializers.ChoiceField(choices=["estimating", "importing", "waiting", "complete"])
+ total_estimate = serializers.IntegerField(allow_null=True)
+ observations_total = serializers.IntegerField(allow_null=True)
+ imported = serializers.IntegerField()
+ count_basis = serializers.CharField()
+ traces_per_second = serializers.FloatField(allow_null=True)
+ estimated_seconds_remaining = serializers.IntegerField(allow_null=True)
+ counted_at = serializers.DateTimeField(allow_null=True)
+ last_progress_at = serializers.DateTimeField(allow_null=True)
+ retry_at = serializers.DateTimeField(allow_null=True)
+
+
class ConnectorCredentialSerializer(serializers.ModelSerializer):
api_key = serializers.CharField(
write_only=True,
@@ -2267,6 +2281,12 @@ class ConnectorCredentialSerializer(serializers.ModelSerializer):
api_secret = serializers.CharField(write_only=True, required=False, allow_blank=True)
api_key_hint = serializers.SerializerMethodField(read_only=True)
active_config = serializers.SerializerMethodField(read_only=True)
+ sync_progress = serializers.SerializerMethodField(read_only=True)
+
+ @extend_schema_field(ConnectorSyncProgressSerializer(allow_null=True))
+ def get_sync_progress(self, obj):
+ progress = sync_progress(obj)
+ return progress.model_dump(mode="json") if progress else None
class Meta:
model = ConnectorCredential
@@ -2286,6 +2306,7 @@ class ConnectorCredentialSerializer(serializers.ModelSerializer):
"sync_status",
"backfill_imported",
"backfill_total",
+ "sync_progress",
"sync_error",
"api_version",
"verified_at",
@@ -2307,6 +2328,7 @@ class ConnectorCredentialSerializer(serializers.ModelSerializer):
"sync_status",
"backfill_imported",
"backfill_total",
+ "sync_progress",
"sync_error",
"api_version",
"verified_at",
diff --git a/overbae/api/views.py b/overbae/api/views.py
index 30faead7..0701f5ed 100644
--- a/overbae/api/views.py
+++ b/overbae/api/views.py
@@ -1705,8 +1705,9 @@ class ConnectorCredentialViewSet(viewsets.ModelViewSet):
config_kwargs = {
"source_project_id": data.get("source_project_id") or "",
"target_project": target_project,
- "lookback_days": data.get("lookback_days"),
}
+ if "lookback_days" in data:
+ config_kwargs["lookback_days"] = data["lookback_days"]
if "backfill_from" in data:
config_kwargs["backfill_from"] = data["backfill_from"]
if "backfill_to" in data:
diff --git a/overbae/services/connectors/feedforward.py b/overbae/services/connectors/feedforward.py
index 38062cac..596e14bf 100644
--- a/overbae/services/connectors/feedforward.py
+++ b/overbae/services/connectors/feedforward.py
@@ -14,7 +14,7 @@ def save_sync_config(
*,
source_project_id: str = "",
target_project=None,
- lookback_days: int | None = None,
+ lookback_days: Any = _UNSET,
backfill_from: Any = _UNSET,
backfill_to: Any = _UNSET,
) -> Any:
@@ -29,7 +29,7 @@ def save_sync_config(
source_project_id=source_project_id or (prev.source_project_id if prev else ""),
target_project=target_project or (prev.target_project if prev else None),
lookback_days=lookback_days
- if lookback_days is not None
+ if lookback_days is not _UNSET
else (prev.lookback_days if prev else None),
backfill_from=prev.backfill_from
if backfill_from is _UNSET and prev
diff --git a/overbae/services/connectors/langfuse/adapter.py b/overbae/services/connectors/langfuse/adapter.py
index 8e907a1e..f7ef3723 100644
--- a/overbae/services/connectors/langfuse/adapter.py
+++ b/overbae/services/connectors/langfuse/adapter.py
@@ -22,12 +22,15 @@ from overbae.services.connectors.base import (
from overbae.services.connectors.langfuse.client import LangFuseClient, LangFuseError
from overbae.services.connectors.langfuse.mapping import LANGFUSE
from overbae.services.connectors.mapping import observations_to_span_dicts
+from overbae.services.connectors.progress import prepare_backfill_progress
from overbae.services.connectors.windows import TimeWindow, plan_windows
LANGFUSE_CAPABILITIES = Capabilities(
- exact_count=True,
+ exact_count=False,
capability_sources=("observation_name", "trace_name", "tag", "metadata"),
needs_source_project=True,
+ retention_note="Langfuse Cloud API history is plan-limited: Hobby 30 days, Core 90 days. "
+ "Older records may be absent from imports even when visible in Langfuse.",
)
@@ -40,6 +43,12 @@ def _parse_iso(value: str | None) -> datetime | None:
return None
+def _within_bound(watermark: str | None, bound: datetime) -> str | None:
+ """A completed tree can start after the backfill bound; live polling must not skip that gap."""
+ parsed = _parse_iso(watermark)
+ return bound.isoformat() if parsed and parsed > bound else watermark
+
+
class LangfuseAdapter:
source = LANGFUSE.source
capabilities = LANGFUSE_CAPABILITIES
@@ -110,7 +119,30 @@ class LangfuseAdapter:
start=window_from or end - timedelta(days=lookback_days),
end=end,
)
+ if limit <= 0:
+ return []
+ # Interactive previews must surface throttling instead of holding the API
+ # 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:
@@ -118,6 +150,12 @@ class LangfuseAdapter:
return units
def fetch_page(self, state: dict[str, Any]) -> Page:
+ page = self._fetch_page(state)
+ if state.get("progress"):
+ page.next_state["progress"] = state["progress"]
+ return page
+
+ def _fetch_page(self, state: dict[str, Any]) -> Page:
"""Fetch one time window. Cursor keys match the pre-adapter shape."""
config = self.credential.active_config()
lookback_days = config.lookback_days if config else None
@@ -138,6 +176,7 @@ class LangfuseAdapter:
anchor,
max_lookback=timedelta(days=lookback_days) if lookback_days else None,
)
+ prepare_backfill_progress(self.credential, self._client, state, all_windows, anchor)
next_end = state.get("next_window_end")
if next_end:
all_windows = [w for w in all_windows if w.end.isoformat() <= next_end]
@@ -150,8 +189,36 @@ class LangfuseAdapter:
)
window = all_windows[0]
- units, newest = self._collect_window(window.start, window.end)
+ 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
+ newest = _within_bound(
+ max((ts for ts in (newest, watermark) if ts), key=_parse_iso, default=None), anchor
+ )
self._persist_api_version()
+ if next_cursor:
+ return Page(
+ units=units,
+ next_state={
+ "mode": "backfill",
+ "watermark": newest,
+ "backfill_anchor": anchor.isoformat(),
+ "next_window_end": window.end.isoformat(),
+ "next_cursor": next_cursor,
+ "windows_remaining": len(all_windows),
+ },
+ done=False,
+ window_from=window.start if window.start.year > 1 else None,
+ window_to=window.end,
+ mode="backfill",
+ )
remaining = all_windows[1:]
if not remaining:
next_state = {"mode": "live", "watermark": newest or watermark}
diff --git a/overbae/services/connectors/langfuse/client.py b/overbae/services/connectors/langfuse/client.py
index 97dae569..7339f0c8 100644
--- a/overbae/services/connectors/langfuse/client.py
+++ b/overbae/services/connectors/langfuse/client.py
@@ -1,13 +1,4 @@
-"""Langfuse REST client — v2 observations with v1 traces fallback.
-
-Auth: Basic (public_key, secret_key). Default host: https://cloud.langfuse.com.
-v2 observations is Cloud-only; self-hosted v3 returns 404 — probe caches
-``api_version`` on the credential.
-
-Cloud rate-limits deprecated reads (GET /traces, GET /observations) at 15/min
-on Hobby and tells high-volume callers to use v2. Ingest stays on v2; v1 is
-only for self-hosted 404s.
-"""
+"""Langfuse REST reads with bounded pages and provider-directed retries."""
from __future__ import annotations
@@ -17,6 +8,7 @@ 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
import httpx
@@ -28,9 +20,10 @@ ApiVersion = Literal["v1", "v2", "unknown"]
_DEFAULT_HOST = "https://cloud.langfuse.com"
_V2_FIELDS = "core,basic,time,io,metadata,model,usage,prompt,metrics,trace_context"
-_V2_PAGE_SIZE = 100 # v2 allows up to 1000; stay conservative
+_V2_PAGE_SIZE = 1000
+_TRACE_FILTER_BATCH_SIZE = 150
_DEPRECATED_READ_PREFIXES = ("/api/public/traces", "/api/public/observations")
-_DEPRECATED_MIN_INTERVAL = 4.5 # Hobby deprecated-read bucket is 15/min
+_DEPRECATED_MIN_INTERVAL = 24.0 # Hobby deprecated-read bucket is 150/hour
_429_ATTEMPTS = 4
_429_WAIT_CAP = 60.0
@@ -60,10 +53,18 @@ class LangFuseProject:
class LangFuseClient:
"""Thin synchronous wrapper around the Langfuse public REST API."""
- def __init__(self, public_key: str, secret_key: str, base_url: str = ""):
+ def __init__(
+ self,
+ public_key: str,
+ secret_key: str,
+ base_url: str = "",
+ *,
+ retry_attempts: int = _429_ATTEMPTS,
+ ):
self.base_url = (base_url or _DEFAULT_HOST).rstrip("/")
self._auth = (public_key, secret_key)
self._api_version: ApiVersion = "unknown"
+ self.retry_attempts = retry_attempts
@property
def api_version(self) -> ApiVersion:
@@ -75,7 +76,7 @@ class LangFuseClient:
url = f"{self.base_url}{path}"
last_429 = ""
last_retry_after = _DEPRECATED_MIN_INTERVAL
- for attempt in range(_429_ATTEMPTS):
+ for attempt in range(self.retry_attempts):
if _is_deprecated_read(path):
_pace_deprecated_read()
try:
@@ -86,7 +87,7 @@ class LangFuseClient:
if resp.status_code == 429:
last_429 = resp.text[:200]
last_retry_after = _retry_after_seconds(resp)
- if attempt < _429_ATTEMPTS - 1:
+ if attempt < self.retry_attempts - 1 and last_retry_after <= _429_WAIT_CAP:
time.sleep(last_retry_after)
continue
break
@@ -144,19 +145,46 @@ class LangFuseClient:
window: TimeWindow | None = None,
lookback_days: int | None = None,
) -> int:
- """Best-effort count of traces in *window* / lookback.
+ """Estimate trace volume from semantic roots in one aggregate request.
- Walks pages until exhausted. Used by the wizard preview — not a hot path.
+ Roots are not guaranteed to be one-to-one with trace IDs. Never scan
+ the full dataset merely to populate a preview or progress indicator.
"""
- n = 0
- for _ in self.iter_ingest_units(
- window_from=window.start if window else None,
- window_to=window.end if window else None,
- lookback_days=lookback_days,
- windows=[window] if window is not None else None,
- ):
- n += 1
- return n
+ end = window.end if window else datetime.now(UTC)
+ start = (
+ window.start
+ if window
+ else (
+ end - timedelta(days=lookback_days)
+ if lookback_days
+ else datetime(1970, 1, 1, tzinfo=UTC)
+ )
+ )
+ return self.volume(TimeWindow(start=start, end=end))["roots"]
+
+ def volume(self, window: TimeWindow) -> dict[str, int]:
+ """Count observations and semantic roots without consuming read pages."""
+ query = {
+ "view": "observations",
+ "metrics": [{"measure": "count", "aggregation": "count"}],
+ "dimensions": [{"field": "isRootObservation"}],
+ "filters": [],
+ "fromTimestamp": _iso(max(window.start, datetime(1970, 1, 1, tzinfo=UTC))),
+ "toTimestamp": _iso(window.end),
+ }
+ data = self._get("/api/public/v2/metrics", query=json.dumps(query))
+ rows = data.get("data")
+ if not isinstance(rows, list):
+ raise LangFuseError("Langfuse did not return a valid volume count.")
+ roots = observations = 0
+ for row in rows:
+ value = row.get("count_count")
+ if not isinstance(value, (int, float)) or value < 0:
+ raise LangFuseError("Langfuse did not return a valid volume count.")
+ observations += int(value)
+ if row.get("isRootObservation") is True:
+ roots += int(value)
+ return {"roots": roots, "observations": observations}
def iter_ingest_units(
self,
@@ -190,9 +218,12 @@ class LangFuseClient:
seen: set[str] = set()
while True:
observations, cursor = self._v2_observation_page(cursor=cursor, **filters)
+ if cursor and cursor in seen:
+ raise LangFuseError(
+ "Langfuse repeated a pagination cursor; the page was not imported."
+ )
yield from observations
- # A repeated cursor would page forever inside a worker.
- if not cursor or not observations or cursor in seen:
+ if not cursor:
break
seen.add(cursor)
@@ -201,19 +232,26 @@ class LangFuseClient:
*,
cursor: str | None = None,
expand_metadata: str | None = None,
+ limit: int = _V2_PAGE_SIZE,
**filters,
) -> tuple[list[LangFuseObservation], str | None]:
data = self._get(
"/api/public/v2/observations",
- limit=_V2_PAGE_SIZE,
+ limit=limit,
fields=_V2_FIELDS,
expandMetadata=expand_metadata,
cursor=cursor,
**filters,
)
- observations = [_observation_from_v2(raw) for raw in data.get("data") or []]
+ rows = data.get("data")
+ if not isinstance(rows, list):
+ raise LangFuseError("Langfuse did not return a valid observations page.")
next_cursor = (data.get("meta") or {}).get("cursor")
- return observations, next_cursor if next_cursor != cursor else None
+ if next_cursor and (next_cursor == cursor or not rows):
+ raise LangFuseError(
+ "Langfuse returned a stalled pagination cursor; the page was not imported."
+ )
+ return [_observation_from_v2(raw) for raw in rows], next_cursor
def fetch_trace_observations(
self, trace_id: str, *, expand_metadata: str | None = None
@@ -227,10 +265,12 @@ class LangFuseClient:
*,
cursor: str | None = None,
expand_metadata: str | None = None,
+ limit: int = _V2_PAGE_SIZE,
) -> tuple[list[list[LangFuseObservation]], str | None]:
"""Complete touched traces because a cursor page can split one trace."""
observations, next_cursor = self._v2_observation_page(
cursor=cursor,
+ limit=limit,
expand_metadata=expand_metadata,
fromStartTime=_iso(window.start) if window.start.year > 1 else None,
toStartTime=_iso(window.end),
@@ -239,14 +279,41 @@ class LangFuseClient:
for observation in observations:
by_trace.setdefault(observation.trace_id or observation.id, []).append(observation)
- trees: list[list[LangFuseObservation]] = []
- for trace_id, page_group in by_trace.items():
- if not all(observation.trace_id for observation in page_group):
- trees.append(page_group)
- continue
- whole_trace = self.fetch_trace_observations(trace_id, expand_metadata=expand_metadata)
- if whole_trace:
- trees.append(whole_trace)
+ # Complete the selected trees without a request per trace. No time filter:
+ # 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]
+ if len(batch) == 1:
+ observations = self.fetch_trace_observations(
+ batch[0], expand_metadata=expand_metadata
+ )
+ else:
+ observations = self._iter_v2_observations(
+ filter=json.dumps(
+ [
+ {
+ "type": "stringOptions",
+ "column": "traceId",
+ "operator": "any of",
+ "value": batch,
+ }
+ ]
+ ),
+ expand_metadata=expand_metadata,
+ )
+ for observation in observations:
+ if observation.trace_id not in batch:
+ raise LangFuseError(
+ "Langfuse returned observations outside the requested trace batch."
+ )
+ complete.setdefault(observation.trace_id, []).append(observation)
+ if any(tid not in complete for tid in batch):
+ raise LangFuseError(
+ "Langfuse did not return every requested trace; the page was not imported."
+ )
+ trees = [complete.get(tid, group) for tid, group in by_trace.items()]
return trees, next_cursor
def _iter_v2_traces(
@@ -306,14 +373,20 @@ def _retry_after_seconds(resp: httpx.Response) -> float:
header = resp.headers.get("Retry-After")
if header:
try:
- return min(float(header), _429_WAIT_CAP)
+ seconds = float(header)
+ if isfinite(seconds) and seconds >= 0:
+ return seconds
except ValueError:
pass
try:
details = (json.loads(resp.text) or {}).get("details") or {}
- raw = details.get("retryAfter") or details.get("retry_after")
+ raw = details.get(
+ "retryAfterSeconds", details.get("retryAfter", details.get("retry_after"))
+ )
if raw is not None:
- return min(float(raw), _429_WAIT_CAP)
+ seconds = float(raw)
+ if isfinite(seconds) and seconds >= 0:
+ return seconds
except (TypeError, ValueError, json.JSONDecodeError):
pass
return _DEPRECATED_MIN_INTERVAL
diff --git a/overbae/services/connectors/progress.py b/overbae/services/connectors/progress.py
new file mode 100644
index 00000000..52796a69
--- /dev/null
+++ b/overbae/services/connectors/progress.py
@@ -0,0 +1,150 @@
+"""Durable source-count estimates shared by Console and MCP polling.
+
+Metrics roots approximate trace IDs; they are never an exact completion gate.
+Polling reads stored counts only. Time includes provider waits and retries.
+"""
+
+from datetime import datetime, timedelta
+from math import ceil
+from typing import Literal
+
+from django.utils import timezone
+from pydantic import BaseModel, Field
+
+from overbae.services.connectors.langfuse.client import LangFuseError
+from overbae.services.connectors.sync import connector_imported_spans
+from overbae.services.connectors.windows import TimeWindow
+
+
+class SyncProgress(BaseModel):
+ state: Literal["estimating", "importing", "waiting", "complete"]
+ total_estimate: int | None = Field(default=None, ge=0)
+ observations_total: int | None = Field(default=None, ge=0)
+ imported: int = Field(ge=0)
+ count_basis: Literal["semantic_roots"] = "semantic_roots"
+ traces_per_second: float | None = Field(default=None, ge=0)
+ estimated_seconds_remaining: int | None = Field(default=None, ge=0)
+ counted_at: datetime | None = None
+ last_progress_at: datetime | None = None
+ retry_at: datetime | None = None
+
+
+def _scoped_imported(credential, snapshot):
+ spans = connector_imported_spans(credential)
+ if snapshot.get("window_from"):
+ start = datetime.fromisoformat(snapshot["window_from"])
+ spans = spans.filter(start_time_ns__gte=int(start.timestamp() * 1_000_000_000))
+ end = datetime.fromisoformat(snapshot["window_to"])
+ return (
+ spans.filter(start_time_ns__lt=int(end.timestamp() * 1_000_000_000))
+ .values("attributes__langfuse.trace_id")
+ .distinct()
+ .count()
+ )
+
+
+def prepare_backfill_progress(credential, client, state, windows, anchor):
+ """Count once per backfill, before the first data page; failure is optional."""
+ if not windows or not getattr(credential, "pk", None):
+ return
+ now = timezone.now().isoformat()
+ start = windows[-1].start
+ snapshot = state.get("progress")
+ if snapshot:
+ if snapshot.get("total") is not None:
+ return
+ if snapshot.get("count_retry_at") and timezone.now() < datetime.fromisoformat(
+ snapshot["count_retry_at"]
+ ):
+ return
+ attempted = datetime.fromisoformat(
+ snapshot.get("count_attempted_at", snapshot["started_at"])
+ )
+ if (timezone.now() - attempted).total_seconds() < 300:
+ return
+ else:
+ snapshot = {
+ "started_at": now,
+ "window_from": start.isoformat() if start.year > 1 else None,
+ "window_to": anchor.isoformat(),
+ "last_progress_at": None,
+ "done": False,
+ }
+ baseline = _scoped_imported(credential, snapshot)
+ snapshot.update(baseline=baseline, imported=baseline)
+ snapshot["count_attempted_at"] = now
+ attempts = client.retry_attempts
+ try:
+ client.retry_attempts = 1
+ volume = client.volume(TimeWindow(start=start, end=anchor))
+ snapshot.update(total=volume["roots"], observations=volume["observations"], counted_at=now)
+ except LangFuseError as exc:
+ # No permission, unsupported metrics, or quota exhaustion must not stop data import.
+ snapshot.update(total=None, observations=None, counted_at=None)
+ snapshot["count_retry_at"] = (
+ timezone.now() + timedelta(seconds=max(300, exc.retry_after or 0))
+ ).isoformat()
+ finally:
+ client.retry_attempts = attempts
+ state["progress"] = snapshot
+ state["backfill_anchor"] = anchor.isoformat()
+ type(credential).objects.filter(pk=credential.pk).update(
+ sync_cursor=state, backfill_total=snapshot["total"]
+ )
+ credential.backfill_total = snapshot["total"]
+
+
+def checkpoint_progress(credential, snapshot, *, gained, done):
+ """Add source traces new to this chunk; completion recounts the persisted spans once."""
+ imported = _scoped_imported(credential, snapshot) if done else snapshot["imported"] + gained
+ now = timezone.now().isoformat()
+ if imported > snapshot["imported"]:
+ snapshot["last_progress_at"] = now
+ snapshot.update(imported=imported, done=done, checkpointed_at=now)
+
+
+def sync_progress(credential) -> SyncProgress | None:
+ snapshot = (credential.sync_cursor or {}).get("progress")
+ if not snapshot:
+ return None
+ now = timezone.now()
+ last = (
+ datetime.fromisoformat(snapshot["last_progress_at"])
+ if snapshot.get("last_progress_at")
+ else None
+ )
+ elapsed = (now - datetime.fromisoformat(snapshot["started_at"])).total_seconds()
+ gained = max(0, snapshot["imported"] - snapshot["baseline"])
+ # A chunk that revisits imported traces is still working, so only a silent import is stale.
+ checkpointed = snapshot.get("checkpointed_at")
+ stale = (
+ (now - datetime.fromisoformat(checkpointed)).total_seconds() > 300
+ if checkpointed
+ else elapsed > 300
+ )
+ done = snapshot.get("done", False)
+ waiting = bool(credential.sync_error) or (stale and not done)
+ rate = gained / elapsed if gained and elapsed > 0 and not waiting and not done else None
+ total = snapshot.get("total")
+ # A root estimate can be too low. Never claim zero seconds before exhaustion.
+ remaining = max(0, total - snapshot["imported"]) if total is not None else None
+ eta = ceil(remaining / rate) if rate and remaining else None
+ if waiting:
+ state = "waiting"
+ elif done:
+ state = "complete"
+ elif rate:
+ state = "importing"
+ else:
+ state = "estimating"
+ return SyncProgress(
+ state=state,
+ total_estimate=total,
+ observations_total=snapshot.get("observations"),
+ imported=snapshot["imported"],
+ traces_per_second=rate,
+ estimated_seconds_remaining=0 if state == "complete" else eta,
+ counted_at=snapshot.get("counted_at"),
+ last_progress_at=last,
+ retry_at=credential.next_poll_at if credential.sync_error else None,
+ )
diff --git a/overbae/services/connectors/sync.py b/overbae/services/connectors/sync.py
index a6a37852..982992f9 100644
--- a/overbae/services/connectors/sync.py
+++ b/overbae/services/connectors/sync.py
@@ -4,6 +4,8 @@ from __future__ import annotations
import json
+from django.db.models import Q
+
from overbae.services.connectors.schema import CONNECTOR_CREDENTIAL_ID_ATTR
@@ -32,7 +34,9 @@ def connector_imported_spans(credential):
from overbae.models import Span
cred_id = str(credential.id)
- qs = Span.objects.filter(project=credential.project)
+ # Every target it has written to: a changed target must not orphan earlier imports.
+ targets = credential.configs.exclude(target_project=None).values("target_project")
+ qs = Span.objects.filter(Q(project=credential.project) | Q(project__in=targets))
if connection.features.supports_json_field_contains:
return qs.filter(resource_attrs__contains={CONNECTOR_CREDENTIAL_ID_ATTR: cred_id})
ids = [
diff --git a/overbae/services/mcp/__init__.py b/overbae/services/mcp/__init__.py
index 25e9b51e..5dde3afe 100644
--- a/overbae/services/mcp/__init__.py
+++ b/overbae/services/mcp/__init__.py
@@ -1,3 +1,3 @@
"""MCP protocol and catalog services."""
-CONTRACT_VERSION = "7.23.0"
+CONTRACT_VERSION = "7.24.0"
diff --git a/overbae/services/mcp/contracts/connectors.py b/overbae/services/mcp/contracts/connectors.py
index c0f3e739..1bf4f555 100644
--- a/overbae/services/mcp/contracts/connectors.py
+++ b/overbae/services/mcp/contracts/connectors.py
@@ -7,6 +7,7 @@ from typing import Literal
from pydantic import AliasChoices, Field, field_validator
+from overbae.services.connectors.progress import SyncProgress
from overbae.services.mcp.contracts.common import MCPModel, ResourceLinkContract
ConnectorMappingSource = Literal["observation_name", "metadata", "tag", "trace_name"]
@@ -117,6 +118,7 @@ class ConnectorSyncState(MCPModel):
next_poll_at: datetime | None = None
backfill_imported: int = Field(ge=0)
backfill_total: int | None = Field(default=None, ge=0)
+ progress: SyncProgress | None = None
total_spans_imported: int = Field(ge=0)
total_traces_imported: int = Field(ge=0)
has_error: bool = False
diff --git a/overbae/services/mcp/resources.py b/overbae/services/mcp/resources.py
index f5ea46dd..0abeed24 100644
--- a/overbae/services/mcp/resources.py
+++ b/overbae/services/mcp/resources.py
@@ -58,6 +58,7 @@ from overbae.services import (
training_monitoring,
)
from overbae.services.codebase.flow import build_capability_flow
+from overbae.services.connectors.progress import sync_progress
from overbae.services.datasets import paths, pipeline_bindings, pipeline_packages, workbench
from overbae.services.datasets.admission import status as landing_admission_status
from overbae.services.datasets.imports import status as import_status
@@ -512,6 +513,7 @@ def connector_resource_payload(project, connector, uri: str) -> dict:
config = connector.active_config()
mapping, assignment_details = _connector_mapping(project, connector)
runs = list(connector.runs.order_by("-started_at")[:51])
+ progress = sync_progress(connector)
return {
"uri": uri,
"kind": "connector",
@@ -548,6 +550,7 @@ def connector_resource_payload(project, connector, uri: str) -> dict:
"next_poll_at": connector.next_poll_at,
"backfill_imported": connector.backfill_imported,
"backfill_total": connector.backfill_total,
+ "progress": progress.model_dump(mode="json") if progress else None,
"total_spans_imported": connector.total_spans_imported,
"total_traces_imported": connector.total_traces_imported,
"has_error": bool(connector.sync_error),
diff --git a/overbae/services/mcp/tools_observability.py b/overbae/services/mcp/tools_observability.py
index ca0c6a71..652c5130 100644
--- a/overbae/services/mcp/tools_observability.py
+++ b/overbae/services/mcp/tools_observability.py
@@ -34,6 +34,7 @@ from overbae.services import (
operational_progress,
training_monitoring,
)
+from overbae.services.connectors.progress import sync_progress
from overbae.services.datasets import transfers, workbench
from overbae.services.deployment import deployment_progress
from overbae.services.entity_resolution import (
@@ -589,6 +590,7 @@ def get_job_sync(payload: GetJobInput, context: MCPContext) -> GetJobOutput:
created_at, updated_at = job.created_at, job.updated_at
label, status = job.name, job.sync_status
job_error = "Connector sync failed." if job.sync_error else None
+ connector_progress = sync_progress(job)
details = {
"connector_type": job.connector_type,
"sync": {
@@ -599,6 +601,9 @@ def get_job_sync(payload: GetJobInput, context: MCPContext) -> GetJobOutput:
"next_poll_at": job.next_poll_at,
"backfill_imported": job.backfill_imported,
"backfill_total": job.backfill_total,
+ "progress": connector_progress.model_dump(mode="json")
+ if connector_progress
+ else None,
"total_spans_imported": job.total_spans_imported,
"total_traces_imported": job.total_traces_imported,
"has_error": bool(job.sync_error),
diff --git a/overbae/tasks/connector_sync.py b/overbae/tasks/connector_sync.py
index 82ac3221..92fda98e 100644
--- a/overbae/tasks/connector_sync.py
+++ b/overbae/tasks/connector_sync.py
@@ -4,15 +4,18 @@ from __future__ import annotations
import logging
from datetime import timedelta
+from math import ceil
from typing import Any
from celery import shared_task
from celery.exceptions import SoftTimeLimitExceeded
-from django.db.models import Q
+from django.db.models import F, Q
from django.utils import timezone
from overbae.api.otlp import enqueue_scoring
+from overbae.services.connectors.progress import checkpoint_progress
from overbae.services.connectors.schema import CONNECTOR_VERSION_ATTR
+from overbae.services.connectors.sync import connector_imported_spans
from overbae.services.span_pricing import stamp_span_cost
logger = logging.getLogger(__name__)
@@ -176,13 +179,15 @@ def _apply_backoff(credential, exc: Exception) -> dict:
auth_failure = status_code in (401, 403)
if status_code == 429:
- delay = int(getattr(exc, "retry_after", None) or _BACKOFF_BASE_SECONDS)
+ delay = ceil(getattr(exc, "retry_after", None) or _BACKOFF_BASE_SECONDS)
_save_sync_state(
credential,
sync_status=ConnectorCredential.SyncStatus.ERROR,
sync_error=str(exc)[:1000],
next_poll_at=timezone.now() + timedelta(seconds=delay),
)
+ if not credential.auto_sync_enabled:
+ _schedule_next_chunk(credential, delay=delay)
return {"status": "error", "retry_after": delay, "error": str(exc)}
if auth_failure or retry >= _MAX_SYNC_RETRIES:
@@ -223,17 +228,26 @@ def _apply_backoff(credential, exc: Exception) -> dict:
delay,
exc,
)
+ if not credential.auto_sync_enabled:
+ _schedule_next_chunk(credential, delay=delay)
return {"status": "error", "retry_after": delay, "error": str(exc)}
-def _schedule_next_chunk(credential) -> None:
+def _schedule_next_chunk(credential, *, delay: int = 2) -> None:
from overbae.models import ConnectorCredential
# The chunk that is already running passed the active check at entry.
# Deactivation has to stop the continuation it is about to publish.
if not ConnectorCredential.objects.filter(pk=credential.pk, is_active=True).exists():
return
- sync_connector_chunk.apply_async(args=[str(credential.id)], countdown=2)
+ sync_connector_chunk.apply_async(args=[str(credential.id)], countdown=delay)
+
+
+def _add_imported(credential, spans: int, traces: int) -> None:
+ type(credential).objects.filter(pk=credential.pk).update(
+ total_spans_imported=F("total_spans_imported") + spans,
+ total_traces_imported=F("total_traces_imported") + traces,
+ )
def _run_adapter_chunk(credential, cursor: dict) -> dict:
@@ -242,7 +256,7 @@ def _run_adapter_chunk(credential, cursor: dict) -> dict:
from overbae.services.connectors import get_adapter
adapter = get_adapter(credential)
- page = adapter.fetch_page(dict(cursor))
+ page = adapter.fetch_page(cursor)
config = credential.active_config()
target_project = (
@@ -252,6 +266,8 @@ def _run_adapter_chunk(credential, cursor: dict) -> dict:
# Empty backfill completion (no windows left) — flip to LIVE without a run row.
if page.mode == "backfill" and page.done and not page.units and page.window_from is None:
+ if page.next_state.get("progress"):
+ checkpoint_progress(credential, page.next_state["progress"], gained=0, done=True)
_save_sync_state(
credential,
sync_status=ConnectorCredential.SyncStatus.LIVE,
@@ -273,6 +289,9 @@ def _run_adapter_chunk(credential, cursor: dict) -> dict:
imported = 0
traces_seen = 0
+ # A source trace is new only when none of its spans existed. Pages can repeat a
+ # tree and chunks can retry, so counting visits would inflate the total.
+ gained = 0
try:
for unit in page.units:
traces_seen += 1
@@ -281,7 +300,9 @@ def _run_adapter_chunk(credential, cursor: dict) -> dict:
credential=credential,
project=target_project,
)
- imported += _upsert_spans(target_project, span_dicts, credential=credential)
+ created = _upsert_spans(target_project, span_dicts, credential=credential)
+ imported += created
+ gained += bool(span_dicts) and created == len(span_dicts)
except Exception as exc:
run.status = ConnectorSyncRun.Status.FAILED
run.error = str(exc)[:1000]
@@ -289,6 +310,7 @@ def _run_adapter_chunk(credential, cursor: dict) -> dict:
run.traces_seen = traces_seen
run.spans_created = imported
run.save()
+ _add_imported(credential, imported, gained)
raise
run.status = ConnectorSyncRun.Status.COMPLETED
@@ -297,12 +319,21 @@ def _run_adapter_chunk(credential, cursor: dict) -> dict:
run.spans_created = imported
run.save()
+ _add_imported(credential, imported, gained)
+ if page.mode == "backfill" and page.done:
+ # A chunk killed by the hard time limit leaves its spans uncounted; settle once.
+ persisted = connector_imported_spans(credential)
+ type(credential).objects.filter(pk=credential.pk).update(
+ total_spans_imported=persisted.count(),
+ total_traces_imported=persisted.values(f"attributes__{adapter.source}.trace_id")
+ .distinct()
+ .count(),
+ )
credential.refresh_from_db()
- new_traces = credential.total_traces_imported + traces_seen
- type(credential).objects.filter(pk=credential.pk).update(
- total_spans_imported=credential.total_spans_imported + imported,
- total_traces_imported=new_traces,
- )
+ new_traces = credential.total_traces_imported
+
+ if page.mode == "backfill" and page.next_state.get("progress"):
+ checkpoint_progress(credential, page.next_state["progress"], gained=gained, done=page.done)
if page.done:
_save_sync_state(
@@ -334,7 +365,7 @@ def _run_adapter_chunk(credential, cursor: dict) -> dict:
),
sync_cursor=page.next_state,
backfill_imported=(new_traces if page.mode == "backfill" else credential.backfill_imported),
- backfill_total=None if page.mode == "backfill" else credential.backfill_total,
+ backfill_total=credential.backfill_total,
sync_error="",
sync_retry_count=0,
last_synced_at=timezone.now(),
diff --git a/overmind/.claude-plugin/plugin.json b/overmind/.claude-plugin/plugin.json
index c6f2af2c..1425eedf 100644
--- a/overmind/.claude-plugin/plugin.json
+++ b/overmind/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "overmind",
- "version": "1.2.10",
+ "version": "1.2.11",
"description": "Overmind skills — agent observability, tracing, and platform workflows for coding agents.",
"author": {
"name": "Overmind",
diff --git a/overmind/.codex-plugin/plugin.json b/overmind/.codex-plugin/plugin.json
index 78852081..22882f3d 100644
--- a/overmind/.codex-plugin/plugin.json
+++ b/overmind/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "overmind",
- "version": "1.2.10",
+ "version": "1.2.11",
"description": "Investigate agent failures, prepare datasets, evaluate models, and manage training and serving with Overmind.",
"author": {
"name": "Overmind",
diff --git a/overmind/.cursor-plugin/plugin.json b/overmind/.cursor-plugin/plugin.json
index cbc92535..f923c742 100644
--- a/overmind/.cursor-plugin/plugin.json
+++ b/overmind/.cursor-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "overmind",
"displayName": "Overmind",
- "version": "1.2.10",
+ "version": "1.2.11",
"description": "Overmind skills and MCP — agent observability, tracing, and platform tools for coding agents.",
"author": {
"name": "Overmind",
diff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.py
index 885eb55b..dc610d84 100644
--- a/overmind/overmind/__init__.py
+++ b/overmind/overmind/__init__.py
@@ -10,7 +10,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any
-__version__ = "0.1.117"
+__version__ = "0.1.118"
from .client import Client, ModelDeleted, OvermindInferenceError
diff --git a/overmind/overmind/skills_db.py b/overmind/overmind/skills_db.py
index a69d9e4e..09097e9b 100644
--- a/overmind/overmind/skills_db.py
+++ b/overmind/overmind/skills_db.py
@@ -1,7 +1,7 @@
from dataclasses import dataclass
# Every plugin manifest (.claude-plugin, .codex-plugin, .cursor-plugin) carries this version.
-SKILLS_VERSION = "1.2.10"
+SKILLS_VERSION = "1.2.11"
@dataclass
diff --git a/overmind/pyproject.toml b/overmind/pyproject.toml
index acd4af2a..030d20bd 100644
--- a/overmind/pyproject.toml
+++ b/overmind/pyproject.toml
@@ -46,7 +46,7 @@ license = { text = "MIT" }
name = "overmind"
readme = "README.md"
requires-python = ">=3.10,<4" # todo; remove the upper bound
-version = "0.1.117"
+version = "0.1.118"
[project.urls]
"Agent setup" = "https://console.overmindlab.ai/setup.md"
diff --git a/overmind/skills/overmind-integrations/SKILL.md b/overmind/skills/overmind-integrations/SKILL.md
index 477ef929..8f2ce331 100644
--- a/overmind/skills/overmind-integrations/SKILL.md
+++ b/overmind/skills/overmind-integrations/SKILL.md
@@ -57,3 +57,16 @@ tools to invent.
Return the source/destination identities, mapping decision, sync outcome and
`console_traces_url`. For configuration, open `observability/integrations` under
the project's Console base with its `projectId`.
+
+Langfuse backfills expose `details.sync.progress` in `get_job` and `sync.progress`
+on the connector resource. The cached Metrics API root count is a trace estimate,
+not an exact trace-ID count. Report its `count_basis` and `counted_at`; newly
+arriving data may not be included. `estimated_seconds_remaining` uses measured
+unique import throughput including waits. Null means not enough progress or a
+stalled/error state; do not invent an ETA. `retry_at` is a provider retry, whereas
+`next_poll_at` alone can be a worker lease. Status polling does not call Langfuse.
+
+Langfuse counts and backfill completion cover API-accessible history only. Cloud
+Hobby exposes 30 days and Core 90 days through the API; an empty response does
+not prove the project is empty. Compare the project ID and visible record dates
+before reporting missing data. Honour the provider's full `Retry-After` delay.
diff --git a/overmind/uv.lock b/overmind/uv.lock
index 25f75d8f..78cb7bee 100644
--- a/overmind/uv.lock
+++ b/overmind/uv.lock
@@ -923,7 +923,7 @@ wheels = [
[[package]]
name = "overmind"
-version = "0.1.117"
+version = "0.1.118"
source = { editable = "." }
dependencies = [
{ name = "packaging" },
diff --git a/tests/fakes/vendors.py b/tests/fakes/vendors.py
index 722c3e97..c1aa63cd 100644
--- a/tests/fakes/vendors.py
+++ b/tests/fakes/vendors.py
@@ -85,6 +85,8 @@ class LangfuseAPI:
requests: list[Call] = field(default_factory=list)
page_size: int | None = None
status: int = 200
+ metrics_status: int = 200
+ metrics_retry_after: int = 0
outage: str = "fake outage"
def record(self, trace_id: str, steps: list[Step]) -> None:
@@ -116,12 +118,16 @@ class LangfuseAPI:
def _observations(self, query: dict[str, str]) -> dict[str, Any]:
wanted = query.get("traceId")
+ trace_ids = None
+ for condition in json.loads(query.get("filter") or "[]"):
+ if condition["column"] == "traceId" and condition["operator"] == "any of":
+ trace_ids = set(condition["value"])
since = _parse(query["fromStartTime"]) if query.get("fromStartTime") else None
until = _parse(query["toStartTime"]) if query.get("toStartTime") else None
rows = [
self._observation(trace_id, step)
for trace_id, steps in self.traces.items()
- if wanted in (None, trace_id)
+ if wanted in (None, trace_id) and (trace_ids is None or trace_id in trace_ids)
for step in steps
if wanted
or ((since is None or step.start >= since) and (until is None or step.start < until))
@@ -143,6 +149,30 @@ class LangfuseAPI:
return _json({"message": self.outage}, status=self.status)
if parsed.path == "/api/public/projects":
return _json({"data": [{"id": "lf-project", "name": "support-desk"}]})
+ if parsed.path == "/api/public/v2/metrics":
+ if self.metrics_status != 200:
+ return _json(
+ {
+ "message": self.outage,
+ "details": {"retryAfterSeconds": self.metrics_retry_after},
+ },
+ status=self.metrics_status,
+ )
+ query = json.loads(parse_qs(parsed.query)["query"][0])
+ start, end = _parse(query["fromTimestamp"]), _parse(query["toTimestamp"])
+ counts = {True: 0, False: 0}
+ for steps in self.traces.values():
+ for step in steps:
+ if start <= step.start < end:
+ counts[step.parent is None] += 1
+ return _json(
+ {
+ "data": [
+ {"isRootObservation": root, "count_count": count}
+ for root, count in counts.items()
+ ]
+ }
+ )
if parsed.path == "/api/public/v2/observations":
return _json(self._observations({k: v[0] for k, v in parse_qs(parsed.query).items()}))
return _json({"message": f"not found: {parsed.path}"}, status=404)
diff --git a/tests/test_connector_poll.py b/tests/test_connector_poll.py
index ddf1e60b..e0449466 100644
--- a/tests/test_connector_poll.py
+++ b/tests/test_connector_poll.py
@@ -6,12 +6,22 @@ from datetime import UTC, datetime, timedelta
import pytest
import time_machine
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
from django.utils import timezone
-from factories import make_connector, sync_until_live
+from factories import make_connector, make_project, sync_until_live
from fakes.vendors import LangfuseAPI, Step
+from overbae.api.serializers import ConnectorCredentialSerializer
from overbae.models import ConnectorCredential, Span
-from overbae.services.connectors.sync import boundary_import_key, enqueue_connector_sync
+from overbae.services.connectors.feedforward import save_sync_config
+from overbae.services.connectors.progress import checkpoint_progress, sync_progress
+from overbae.services.connectors.sync import (
+ boundary_import_key,
+ enqueue_connector_sync,
+ reset_connector_import,
+)
+from overbae.services.mcp.resources import connector_resource_payload
from overbae.tasks import connector_sync
pytestmark = [pytest.mark.django_db, pytest.mark.covers("vendor-connectors")]
@@ -256,3 +266,194 @@ def test_a_sync_request_restarts_the_backfill_when_the_boundaries_changed(creden
credential.refresh_from_db()
assert credential.sync_status == ConnectorCredential.SyncStatus.BACKFILLING
assert credential.sync_cursor == {}
+
+
+def test_split_trace_pages_and_retries_do_not_inflate_import_counts(credential, langfuse):
+ start = datetime(2026, 1, 1, tzinfo=UTC)
+ root = Step("root", "span", None, start=start, end=start + timedelta(seconds=2))
+ child = Step(
+ "child",
+ "span",
+ root.id,
+ start=start + timedelta(seconds=1),
+ end=start + timedelta(seconds=2),
+ )
+ langfuse.record(uuid.uuid4().hex, [root, child])
+ langfuse.page_size = 1
+ cred = sync_until_live(credential)
+ assert cred.total_traces_imported == 1
+ assert cred.total_spans_imported == 2
+ _chunk(credential)
+ credential.refresh_from_db()
+ assert credential.total_traces_imported == 1
+ assert credential.total_spans_imported == 2
+
+
+def test_all_history_clears_the_previous_lookback(credential):
+ save_sync_config(credential, lookback_days=1)
+ assert save_sync_config(credential).lookback_days == 1
+ assert save_sync_config(credential, lookback_days=None).lookback_days is None
+
+
+def test_manual_import_resumes_after_provider_throttling(credential, langfuse, continuations):
+ langfuse.status = 429
+ result = _chunk(credential)
+ assert result["status"] == "error"
+ assert continuations == [str(credential.id)]
+ credential.refresh_from_db()
+ assert credential.auto_sync_enabled is False
+
+
+def test_source_count_and_eta_include_waits_and_survive_page_resume(
+ credential, langfuse, time_machine
+):
+ clock = time_machine
+ clock.move_to("2026-01-03T00:00:00Z", tick=False)
+ _traces(langfuse, 6)
+ langfuse.page_size = 2
+ _chunk(credential)
+ credential.refresh_from_db()
+ first = sync_progress(credential)
+ assert first.total_estimate == 6
+ assert first.observations_total == 6
+ assert first.imported == 2
+ clock.shift(60)
+ _chunk(credential)
+ credential.refresh_from_db()
+ progress = sync_progress(credential)
+ assert progress.imported == 4
+ assert progress.estimated_seconds_remaining == 30
+ assert len([call for call in langfuse.requests if "/v2/metrics" in call.url]) == 1
+ # Status polling never calls the provider and doesn't count lease expiry as a retry.
+ assert progress.retry_at is None
+ clock.shift(301)
+ assert sync_progress(credential).estimated_seconds_remaining is None
+ assert sync_progress(credential).state == "waiting"
+ _chunk(credential)
+ credential.refresh_from_db()
+ progress = sync_progress(credential)
+ assert progress.state == "complete"
+ assert progress.imported == 6
+ assert progress.estimated_seconds_remaining == 0
+
+
+def test_source_count_persists_when_a_data_page_is_throttled(credential, langfuse):
+ _traces(langfuse, 3)
+ langfuse.page_size = 1
+ _chunk(credential)
+ credential.refresh_from_db()
+ total = sync_progress(credential).total_estimate
+ langfuse.status = 429
+ _chunk(credential)
+ credential.refresh_from_db()
+ progress = sync_progress(credential)
+ assert progress.total_estimate == total == 3
+ assert progress.imported == 1
+ assert progress.state == "waiting"
+ assert progress.estimated_seconds_remaining is None
+ assert progress.retry_at is not None
+
+
+def test_unavailable_count_does_not_block_import_and_is_retried(credential, langfuse, time_machine):
+ time_machine.move_to("2026-01-03T00:00:00Z", tick=False)
+ _traces(langfuse, 4)
+ langfuse.page_size = 1
+ langfuse.metrics_status = 429
+ _chunk(credential)
+ credential.refresh_from_db()
+ assert sync_progress(credential).total_estimate is None
+ assert sync_progress(credential).imported == 1
+ time_machine.shift(301)
+ langfuse.metrics_status = 200
+ _chunk(credential)
+ credential.refresh_from_db()
+ progress = ConnectorCredentialSerializer(credential).data["sync_progress"]
+ assert progress["total_estimate"] == 4
+ assert progress["imported"] == 2
+ assert progress["estimated_seconds_remaining"] == 301
+ resource = connector_resource_payload(
+ credential.project, credential, "overmind://connectors/test"
+ )
+ assert resource["sync"]["progress"] == progress
+
+
+def test_empty_backfill_reports_completion_instead_of_estimating(credential, langfuse):
+ _chunk(credential)
+ credential.refresh_from_db()
+ progress = sync_progress(credential)
+ assert credential.sync_status == "live"
+ assert progress.state == "complete"
+ assert progress.imported == 0
+ assert progress.estimated_seconds_remaining == 0
+
+
+def test_metrics_quota_wait_does_not_block_trace_pages_or_retry_early(
+ credential, langfuse, time_machine
+):
+ time_machine.move_to("2026-01-03T00:00:00Z", tick=False)
+ _traces(langfuse, 4)
+ langfuse.page_size = 1
+ langfuse.metrics_status = 429
+ langfuse.metrics_retry_after = 3600
+ _chunk(credential)
+ time_machine.shift(301)
+ _chunk(credential)
+ assert len([call for call in langfuse.requests if "/v2/metrics" in call.url]) == 1
+ assert _spans(credential) == 2
+
+
+def test_totals_and_progress_count_the_target_project(credential, langfuse):
+ target = make_project()
+ save_sync_config(credential, target_project=target)
+ _traces(langfuse, 3)
+ credential = sync_until_live(credential)
+ assert Span.objects.filter(project=target).count() == 3
+ assert (credential.total_spans_imported, credential.total_traces_imported) == (3, 3)
+ assert sync_progress(credential).imported == 3
+
+
+def test_a_failed_live_poll_after_a_finished_backfill_is_not_complete(credential, langfuse):
+ _traces(langfuse, 1)
+ credential = sync_until_live(credential)
+ assert sync_progress(credential).state == "complete"
+ retry = timezone.now() + timedelta(minutes=5)
+ ConnectorCredential.objects.filter(pk=credential.pk).update(
+ sync_error="Langfuse rate limited", next_poll_at=retry
+ )
+ credential.refresh_from_db()
+ progress = sync_progress(credential)
+ assert progress.state == "waiting"
+ assert progress.retry_at == retry
+ assert progress.estimated_seconds_remaining is None
+
+
+def test_a_middle_chunk_does_not_count_the_whole_import(credential, langfuse):
+ _traces(langfuse, 3)
+ langfuse.page_size = 1
+ _chunk(credential)
+ with CaptureQueriesContext(connection) as queries:
+ _chunk(credential)
+ credential.refresh_from_db()
+ assert credential.total_traces_imported == 2
+ assert not [q["sql"] for q in queries if "COUNT(" in q["sql"] and "resource_attrs" in q["sql"]]
+
+
+def test_a_reset_reaches_spans_in_a_former_target_project(credential, langfuse):
+ first, second = make_project(), make_project()
+ save_sync_config(credential, target_project=first)
+ _traces(langfuse, 2)
+ sync_until_live(credential)
+ assert Span.objects.filter(project=first).count() == 2
+ save_sync_config(credential, target_project=second)
+ assert reset_connector_import(credential) == 2
+ assert not Span.objects.filter(project=first).exists()
+
+
+def test_a_chunk_without_new_traces_keeps_the_import_active(credential, langfuse):
+ _traces(langfuse, 3)
+ langfuse.page_size = 1
+ _chunk(credential)
+ credential.refresh_from_db()
+ with time_machine.travel(timezone.now() + timedelta(minutes=10), tick=False):
+ checkpoint_progress(credential, credential.sync_cursor["progress"], gained=0, done=False)
+ assert sync_progress(credential).state != "waiting"
diff --git a/tests/test_langfuse_adapter.py b/tests/test_langfuse_adapter.py
index 4ef8d422..ae7e3ae8 100644
--- a/tests/test_langfuse_adapter.py
+++ b/tests/test_langfuse_adapter.py
@@ -1,3 +1,4 @@
+import json
from datetime import UTC, datetime, timedelta
import pytest
@@ -5,6 +6,7 @@ import time_machine
from factories import make_connector
from overbae.services.connectors.langfuse.adapter import LangfuseAdapter
+from overbae.services.connectors.langfuse.client import LangFuseError
pytestmark = [pytest.mark.django_db, pytest.mark.covers("vendor-connectors")]
@@ -71,7 +73,8 @@ def test_backfill_uses_the_configured_bounds(api):
def test_count_and_discovery_prefer_explicit_bounds(api):
api.steps.clear()
- api.reply(json_body={"data": [], "meta": {"totalItems": 7}})
+ api.reply(json_body={"data": [{"isRootObservation": True, "count_count": 7}]})
+ api.reply(json_body={"data": []})
start = datetime(2026, 8, 1, tzinfo=UTC)
end = start + timedelta(days=3)
adapter = _adapter()
@@ -79,7 +82,10 @@ def test_count_and_discovery_prefer_explicit_bounds(api):
adapter.count(lookback_days=30, window_from=start, window_to=end)
adapter.sample_units(lookback_days=30, window_from=start, window_to=end)
- for call in api.calls:
+ query = json.loads(api.calls[0].params["query"])
+ assert query["fromTimestamp"].startswith("2026-08-01T00:00:00")
+ assert query["toTimestamp"].startswith("2026-08-04T00:00:00")
+ for call in api.calls[1:]:
assert call.params["fromStartTime"].startswith("2026-08-01T00:00:00")
assert call.params["toStartTime"].startswith("2026-08-04T00:00:00")
@@ -117,3 +123,78 @@ def test_live_pagination_pins_its_window_and_resumes(api, clock):
}
assert pages[1]["cursor"] == "cursor-1"
assert all(c.params["expandMetadata"] == "capability" for c in api.calls)
+
+
+def test_sampling_stops_before_reading_the_full_window(api):
+ root = {
+ "id": "root",
+ "traceId": "t1",
+ "type": "SPAN",
+ "isRootObservation": True,
+ "startTime": _START.isoformat(),
+ }
+ api.steps.clear()
+ api.reply(json_body={"data": [root], "meta": {"cursor": "more"}})
+ api.reply(json_body={"data": [root], "meta": {}})
+ adapter = _adapter()
+ units = adapter.sample_units(lookback_days=1, limit=1)
+ assert len(units) == 1
+ assert not any(call.params.get("cursor") for call in api.calls)
+
+
+def test_backfill_checkpoints_inside_a_dense_window(api, clock):
+ root = {
+ "id": "root",
+ "traceId": "t1",
+ "type": "SPAN",
+ "isRootObservation": True,
+ "startTime": _START.isoformat(),
+ }
+ api.steps.clear()
+ api.reply(json_body={"data": [{"isRootObservation": True, "count_count": 1}]})
+ api.reply(json_body={"data": [root], "meta": {"cursor": "more"}})
+ api.reply(json_body={"data": [root], "meta": {}})
+ adapter = _adapter(lookback_days=1)
+ page = adapter.fetch_page({})
+ assert not page.done
+ assert page.next_state["next_cursor"] == "more"
+ assert not any(call.params.get("cursor") for call in api.calls)
+ api.steps.clear()
+ api.reply(json_body={"data": [], "meta": {}})
+ clock.shift(timedelta(minutes=1))
+ final = adapter.fetch_page(page.next_state)
+ assert final.done
+ assert (final.window_from, final.window_to) == (page.window_from, page.window_to)
+ assert api.calls[-1].params["cursor"] == "more"
+
+
+def test_rate_limited_sampling_returns_without_background_retry_waits(api):
+ api.steps.clear()
+ api.reply(429, text="throttled", headers={"Retry-After": "60"})
+ with pytest.raises(LangFuseError):
+ _adapter().sample_units(lookback_days=1)
+ assert len(api.calls) == 1
+
+
+def test_backfill_watermark_stops_at_its_bound(api, clock):
+ late = (_START + timedelta(hours=2)).isoformat()
+ api.reply(
+ json_body={
+ "data": [{"id": "o1", "traceId": "t1", "startTime": late, "name": "n", "type": "SPAN"}],
+ "meta": {},
+ }
+ )
+ adapter = _adapter()
+ page = adapter.fetch_page({})
+ while not page.done:
+ page = adapter.fetch_page(page.next_state)
+ assert page.next_state["watermark"] == _START.isoformat()
+
+
+def test_backfill_watermark_compares_instants_across_formats(api, clock):
+ later = "2026-08-19T11:00:00.900500+00:00"
+ earlier = "2026-08-19T11:00:00.900Z"
+ observation = {"id": "o1", "traceId": "t1", "startTime": earlier, "name": "n", "type": "SPAN"}
+ api.reply(json_body={"data": [observation], "meta": {}})
+ page = _adapter().fetch_page({"mode": "backfill", "watermark": later})
+ assert page.next_state["watermark"] == later
diff --git a/tests/test_langfuse_client.py b/tests/test_langfuse_client.py
index 8cb8d097..93add173 100644
--- a/tests/test_langfuse_client.py
+++ b/tests/test_langfuse_client.py
@@ -80,9 +80,8 @@ def test_v2_trace_page_completes_trees_and_keeps_the_cursor(api):
def test_v2_trace_page_stops_a_repeated_cursor(api):
api.reply(json_body={"data": [], "meta": {"cursor": "stuck"}})
- _, cursor = LangFuseClient("pk", "sk").fetch_v2_trace_page(_WINDOW, cursor="stuck")
-
- assert cursor is None
+ with pytest.raises(LangFuseError, match="cursor"):
+ LangFuseClient("pk", "sk").fetch_v2_trace_page(_WINDOW, cursor="stuck")
def test_a_rate_limit_that_never_lifts_raises_with_its_status(api):
@@ -152,6 +151,64 @@ def test_a_complete_trace_is_not_refetched(api):
def test_window_paging_stops_when_the_cursor_repeats(api):
- _groups(api, {"data": [_obs("root", root=True)], "meta": {"cursor": "stuck"}})
+ 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}
+ child = {"id": "c", "traceId": "t1", "type": "SPAN", "parentObservationId": "a"}
+ api.reply(json_body={"data": [first, second], "meta": {"cursor": "discovery"}})
+ api.reply(json_body={"data": [first, second], "meta": {"cursor": "children"}})
+ api.reply(json_body={"data": [child], "meta": {}})
+ groups, cursor = LangFuseClient("pk", "sk").fetch_v2_trace_page(_WINDOW)
+ assert [[obs.id for obs in group] for group in groups] == [["a", "c"], ["b"]]
+ assert cursor == "discovery"
+ assert len(api.calls) == 3
+
+
[email protected]("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": {}})
+ api.reply(json_body={"data": returned, "meta": {}})
+ with pytest.raises(LangFuseError):
+ LangFuseClient("pk", "sk").fetch_v2_trace_page(_WINDOW)
+
+
+def test_count_uses_one_aggregate_request_not_observation_pagination(api):
+ api.reply(
+ json_body={
+ "data": [
+ {"isRootObservation": True, "count_count": 70000},
+ {"isRootObservation": False, "count_count": 212},
+ ]
+ }
+ )
+ client = LangFuseClient("pk", "sk")
+ assert client.volume(_WINDOW) == {"roots": 70000, "observations": 70212}
+ assert len(api.calls) == 1
+ assert api.calls[0].path == "/api/public/v2/metrics"
+
+
+def test_missing_count_is_not_reported_as_zero(api):
+ api.reply(json_body={"data": [{"isRootObservation": True}]})
+ with pytest.raises(LangFuseError, match="valid volume count"):
+ LangFuseClient("pk", "sk").volume(_WINDOW)
+
+
+ "headers,body",
+ [
+ ({"Retry-After": "3600"}, {}),
+ ({}, {"details": {"retryAfterSeconds": 3600}}),
+ ],
+)
+def test_long_rate_limit_wait_is_deferred_without_shortening_it(api, headers, body):
+ api.reply(429, headers=headers, json_body=body)
+ with pytest.raises(LangFuseError) as caught:
+ LangFuseClient("pk", "sk").list_projects()
+ assert caught.value.retry_after == 3600
+ assert len(api.calls) == 1
diff --git a/tests/test_mcp_connector_job_poll.py b/tests/test_mcp_connector_job_poll.py
index 3bfd0209..69864d1e 100644
--- a/tests/test_mcp_connector_job_poll.py
+++ b/tests/test_mcp_connector_job_poll.py
@@ -50,6 +50,7 @@ def test_connector_sync_get_job_uses_connector_receipt_id_and_resource():
"next_poll_at": None,
"backfill_imported": 7,
"backfill_total": 12,
+ "progress": None,
"total_spans_imported": 20,
"total_traces_imported": 8,
"has_error": False,
diff --git a/tests/test_sessions.py b/tests/test_sessions.py
index e027297b..4dbef25e 100644
--- a/tests/test_sessions.py
+++ b/tests/test_sessions.py
@@ -289,8 +289,7 @@ def test_an_imported_langfuse_session_groups_its_traces(scripted, slept):
for i in range(2)
]
api.reply(json_body={"data": observations, "meta": {}})
- for observation in observations:
- api.reply(json_body={"data": [observation], "meta": {}})
+ api.reply(json_body={"data": observations, "meta": {}})
connector_sync.sync_connector_chunk(str(credential.pk))