Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

chore(export): track backfill state on export integrations and tag staleness (#18008)

Niklas Semmler9f95462f94a7
diff --git a/packages/shared/prisma/migrations/20261005120000_export_integrations_backfill/migration.sql b/packages/shared/prisma/migrations/20261005120000_export_integrations_backfill/migration.sql
new file mode 100644
index 0000000000..148ecfdc39
--- /dev/null
+++ b/packages/shared/prisma/migrations/20261005120000_export_integrations_backfill/migration.sql
@@ -0,0 +1,3 @@
+ALTER TABLE "blob_storage_integrations" ADD COLUMN "backfill" BOOLEAN NOT NULL DEFAULT true;
+ALTER TABLE "posthog_integrations" ADD COLUMN "backfill" BOOLEAN NOT NULL DEFAULT true;
+ALTER TABLE "mixpanel_integrations" ADD COLUMN "backfill" BOOLEAN NOT NULL DEFAULT true;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 36735c43ad..16e3513361 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -1310,6 +1310,11 @@ model PosthogIntegration {
createdAt DateTime @default(now()) @map("created_at")
exportSource AnalyticsIntegrationExportSource @default(TRACES_OBSERVATIONS) @map("export_source")
+ // True while the integration is exporting history (new, re-enabled, or export
+ // mode reset), so the export staleness gauge can separate it from steady
+ // state. Cleared by the worker once a run lands within an hour of its start.
+ backfill Boolean @default(true)
+
// Last deterministic customer-config fault (bad hostname) that disabled the
// integration. Written by the worker, surfaced in the integration settings
// status section, and cleared on a successful run.
@@ -1329,6 +1334,11 @@ model MixpanelIntegration {
createdAt DateTime @default(now()) @map("created_at")
exportSource AnalyticsIntegrationExportSource @default(TRACES_OBSERVATIONS) @map("export_source")
+ // True while the integration is exporting history (new, re-enabled, or export
+ // mode reset), so the export staleness gauge can separate it from steady
+ // state. Cleared by the worker once a run lands within an hour of its start.
+ backfill Boolean @default(true)
+
@@map("mixpanel_integrations")
}
@@ -1366,6 +1376,11 @@ model BlobStorageIntegration {
// Run tracking
runStartedAt DateTime? @map("run_started_at")
+ // True while the integration is exporting history (new, re-enabled, or export
+ // mode reset), so the export staleness gauge can separate it from steady
+ // state. Cleared by the worker once a run lands within an hour of its start.
+ backfill Boolean @default(true)
+
// Error tracking
lastError String? @map("last_error")
lastErrorAt DateTime? @map("last_error_at")
diff --git a/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts b/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts
index 4a42c632eb..c7b6eb3fe0 100644
--- a/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts
+++ b/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts
@@ -270,6 +270,48 @@ describe("Blob Storage Integration tRPC Router", () => {
});
});
+ describe("backfill", () => {
+ it("marks backfill on create, re-enable and export-mode change, not on a plain save", async () => {
+ const { caller, project } = await prepare();
+ const save = (
+ overrides: Partial<
+ Parameters<typeof caller.blobStorageIntegration.update>[0]
+ >,
+ ) =>
+ caller.blobStorageIntegration.update({
+ projectId: project.id,
+ ...baseConfig,
+ ...overrides,
+ });
+ const backfill = async () =>
+ (
+ await prisma.blobStorageIntegration.findUniqueOrThrow({
+ where: { projectId: project.id },
+ })
+ ).backfill;
+ const catchUp = () =>
+ prisma.blobStorageIntegration.update({
+ where: { projectId: project.id },
+ data: { backfill: false },
+ });
+
+ await save({});
+ expect(await backfill()).toBe(true);
+
+ await catchUp();
+ await save({ bucketName: "renamed-bucket" });
+ expect(await backfill()).toBe(false);
+
+ await save({ enabled: false });
+ await save({ enabled: true });
+ expect(await backfill()).toBe(true);
+
+ await catchUp();
+ await save({ exportMode: "FROM_TODAY" });
+ expect(await backfill()).toBe(true);
+ });
+ });
+
describe("runNow", () => {
it("creates a success audit log when a manual run is queued", async () => {
const add = vi.fn().mockResolvedValue(undefined);
diff --git a/web/src/__tests__/server/posthog-integration.servertest.ts b/web/src/__tests__/server/posthog-integration.servertest.ts
index 305b9d4ba4..7103fe467e 100644
--- a/web/src/__tests__/server/posthog-integration.servertest.ts
+++ b/web/src/__tests__/server/posthog-integration.servertest.ts
@@ -178,6 +178,35 @@ describe("PostHog Integration legacy export source cutoff gate", () => {
return { project, caller };
};
+ it("marks backfill on re-enable, not on a plain save", async () => {
+ const { caller, project } = await prepare();
+ const save = (enabled: boolean) =>
+ caller.posthogIntegration.update({
+ projectId: project.id,
+ ...baseConfig,
+ enabled,
+ exportSource: "EVENTS" as const,
+ });
+ const backfill = async () =>
+ (
+ await prisma.posthogIntegration.findUniqueOrThrow({
+ where: { projectId: project.id },
+ })
+ ).backfill;
+
+ await save(true);
+ await prisma.posthogIntegration.update({
+ where: { projectId: project.id },
+ data: { backfill: false },
+ });
+ await save(true);
+ expect(await backfill()).toBe(false);
+
+ await save(false);
+ await save(true);
+ expect(await backfill()).toBe(true);
+ });
+
// A pre-cutoff project no longer buys a *new* integration the right to a
// legacy source. Existing integrations stay grandfathered — see
// "Cloud new-integration enriched pin" below.
diff --git a/web/src/features/blobstorage-integration/service.ts b/web/src/features/blobstorage-integration/service.ts
index 26dfb4c9be..900dd9fbb4 100644
--- a/web/src/features/blobstorage-integration/service.ts
+++ b/web/src/features/blobstorage-integration/service.ts
@@ -123,6 +123,7 @@ export async function upsertBlobStorageIntegration(params: {
where: { projectId },
// createdAt/exportSource feed the post-upsert backstop below.
select: {
+ enabled: true,
exportMode: true,
lastError: true,
runStartedAt: true,
@@ -143,6 +144,7 @@ export async function upsertBlobStorageIntegration(params: {
}
const modeChanged = existing && existing.exportMode !== data.exportMode;
+ const justEnabled = data.enabled && !existing?.enabled;
const encryptedSecret = secretAccessKey ? encrypt(secretAccessKey) : null;
// The CREATE payload always carries a concrete source, resolved by the
@@ -181,6 +183,9 @@ export async function upsertBlobStorageIntegration(params: {
// start-date logic takes effect instead of continuing from the
// previous mode's lastSyncAt.
...(modeChanged ? { lastSyncAt: null, nextSyncAt: new Date() } : {}),
+ // Both restart the export from history; the worker clears the flag
+ // once it reaches the live tail. CREATE gets it from the column default.
+ ...(modeChanged || justEnabled ? { backfill: true } : {}),
// Saving enabled resets the failure-notification cooldown: the
// customer just acted, so a fresh failure should email promptly.
...(data.enabled ? { lastFailureNotificationSentAt: null } : {}),
diff --git a/web/src/features/mixpanel-integration/mixpanel-integration-router.ts b/web/src/features/mixpanel-integration/mixpanel-integration-router.ts
index 3317a039d6..3ef1b5fb38 100644
--- a/web/src/features/mixpanel-integration/mixpanel-integration-router.ts
+++ b/web/src/features/mixpanel-integration/mixpanel-integration-router.ts
@@ -101,6 +101,7 @@ export const mixpanelIntegrationRouter = createTRPCRouter({
select: {
exportSource: true,
createdAt: true,
+ enabled: true,
encryptedMixpanelProjectToken: true,
},
});
@@ -151,6 +152,12 @@ export const mixpanelIntegrationRouter = createTRPCRouter({
// undefined → Prisma omits the column → preserves the persisted
// value on partial updates.
exportSource: config.exportSource,
+ // A re-enabled integration resumes from its old lastSyncAt; the
+ // worker clears the flag once it reaches the live tail. CREATE gets
+ // it from the column default.
+ ...(config.enabled && !existingIntegration?.enabled
+ ? { backfill: true }
+ : {}),
},
});
diff --git a/web/src/features/posthog-integration/components/PostHogStatusSection.clienttest.tsx b/web/src/features/posthog-integration/components/PostHogStatusSection.clienttest.tsx
index 5734326a7a..0ffc240ca9 100644
--- a/web/src/features/posthog-integration/components/PostHogStatusSection.clienttest.tsx
+++ b/web/src/features/posthog-integration/components/PostHogStatusSection.clienttest.tsx
@@ -19,6 +19,7 @@ const baseConfig: PostHogIntegrationConfig = {
lastSyncAt: new Date("2024-06-01T12:00:00Z"),
lastError: null,
lastErrorAt: null,
+ backfill: false,
};
const renderSection = (overrides: Partial<PostHogIntegrationConfig> = {}) =>
diff --git a/web/src/features/posthog-integration/posthog-integration-router.ts b/web/src/features/posthog-integration/posthog-integration-router.ts
index 72af26c665..2c3abf3a64 100644
--- a/web/src/features/posthog-integration/posthog-integration-router.ts
+++ b/web/src/features/posthog-integration/posthog-integration-router.ts
@@ -114,6 +114,7 @@ export const posthogIntegrationRouter = createTRPCRouter({
select: {
exportSource: true,
createdAt: true,
+ enabled: true,
encryptedPosthogApiKey: true,
},
});
@@ -164,6 +165,12 @@ export const posthogIntegrationRouter = createTRPCRouter({
// undefined → Prisma omits the column → preserves the persisted
// value on partial updates.
exportSource: config.exportSource,
+ // A re-enabled integration resumes from its old lastSyncAt; the
+ // worker clears the flag once it reaches the live tail. CREATE gets
+ // it from the column default.
+ ...(config.enabled && !existingIntegration?.enabled
+ ? { backfill: true }
+ : {}),
// lastError is deliberately left intact so the last fault stays
// visible until a successful run clears it.
},
diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
index cddf5b5251..84fd7ab800 100644
--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
@@ -1986,6 +1986,7 @@ describe("BlobStorageIntegrationProcessingJob", () => {
updatedIntegration.nextSyncAt.getTime() - now.getTime(),
);
expect(timeDiff).toBeLessThan(5000); // Within 5 seconds
+ expect(updatedIntegration.backfill).toBe(true);
});
it("keeps the advanced watermark when catch-up enqueue fails", async () => {
@@ -2192,6 +2193,7 @@ describe("BlobStorageIntegrationProcessingJob", () => {
expect(updatedIntegration.nextSyncAt.getTime()).toBeGreaterThan(
now.getTime(),
);
+ expect(updatedIntegration.backfill).toBe(false);
});
});
diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
index 98c114b64c..de64599b25 100644
--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
@@ -76,6 +76,7 @@ import { SpanKind } from "@opentelemetry/api";
import { env } from "../../env";
import { assertExportSourceWritable } from "../exportWriteModeGuard";
import { recordExportVolume } from "../../services/exportVolumeMetric";
+import { isExportCaughtUp } from "../../services/exportStalenessMetric";
import {
buildBlobExportManifest,
buildBlobExportManifestKey,
@@ -1300,6 +1301,12 @@ export const handleBlobStorageIntegrationProjectJob = async (
nextSyncAt: new Date(now.getTime() + frequencyIntervalMs),
lastError: null,
lastErrorAt: null,
+ ...(isExportCaughtUp({
+ lastSyncAt: blobStorageIntegration.lastSyncAt,
+ runStartTime,
+ })
+ ? { backfill: false }
+ : {}),
},
});
return;
@@ -1527,6 +1534,9 @@ export const handleBlobStorageIntegrationProjectJob = async (
lastError: null,
lastErrorAt: null,
runStartedAt: null,
+ ...(isExportCaughtUp({ lastSyncAt: maxTimestamp, runStartTime })
+ ? { backfill: false }
+ : {}),
},
},
);
diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationSchedule.test.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationSchedule.test.ts
index a80601c1c9..43a68fd5d1 100644
--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationSchedule.test.ts
+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationSchedule.test.ts
@@ -37,6 +37,7 @@ describe("handleBlobStorageIntegrationSchedule", () => {
exportFrequency: "every_20_minutes",
lastSyncAt: new Date("2026-09-28T11:20:00.000Z"),
nextSyncAt: new Date("2026-09-28T11:59:00.000Z"),
+ backfill: false,
},
{
// Stalled: watermark is a day old but nextSyncAt says not due.
@@ -44,12 +45,14 @@ describe("handleBlobStorageIntegrationSchedule", () => {
exportFrequency: "hourly",
lastSyncAt: new Date("2026-09-27T12:00:00.000Z"),
nextSyncAt: new Date("2026-09-28T13:00:00.000Z"),
+ backfill: true,
},
{
projectId: "never-synced",
exportFrequency: "daily",
lastSyncAt: null,
nextSyncAt: null,
+ backfill: true,
},
]);
@@ -59,12 +62,22 @@ describe("handleBlobStorageIntegrationSchedule", () => {
[
EXPORT_STALENESS_METRIC,
40 * 60,
- { integration: "blob_storage", window: "20m", unit: "seconds" },
+ {
+ integration: "blob_storage",
+ window: "20m",
+ backfill: "false",
+ unit: "seconds",
+ },
],
[
EXPORT_STALENESS_METRIC,
24 * 60 * 60,
- { integration: "blob_storage", window: "1h", unit: "seconds" },
+ {
+ integration: "blob_storage",
+ window: "1h",
+ backfill: "true",
+ unit: "seconds",
+ },
],
]);
const enqueued = addBulk.mock.calls[0][0].map(
@@ -81,6 +94,7 @@ describe("handleBlobStorageIntegrationSchedule", () => {
exportFrequency: "monthly",
lastSyncAt: new Date("2026-09-28T10:00:00.000Z"),
nextSyncAt: new Date("2026-09-28T13:00:00.000Z"),
+ backfill: false,
},
]);
@@ -89,7 +103,12 @@ describe("handleBlobStorageIntegrationSchedule", () => {
expect(recordDistribution).toHaveBeenCalledWith(
EXPORT_STALENESS_METRIC,
2 * 60 * 60,
- { integration: "blob_storage", window: "unknown", unit: "seconds" },
+ {
+ integration: "blob_storage",
+ window: "unknown",
+ backfill: "false",
+ unit: "seconds",
+ },
);
expect(addBulk).not.toHaveBeenCalled();
});
diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationSchedule.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationSchedule.ts
index be1026015e..b034f7a7c2 100644
--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationSchedule.ts
+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationSchedule.ts
@@ -18,6 +18,7 @@ export const handleBlobStorageIntegrationSchedule = async () => {
const enabledIntegrations = await prisma.blobStorageIntegration.findMany({
select: {
lastSyncAt: true,
+ backfill: true,
nextSyncAt: true,
exportFrequency: true,
projectId: true,
@@ -33,6 +34,7 @@ export const handleBlobStorageIntegrationSchedule = async () => {
integrations: enabledIntegrations.map((integration) => ({
lastSyncAt: integration.lastSyncAt,
window: windowClassFromBlobFrequency(integration.exportFrequency),
+ backfill: integration.backfill,
})),
});
diff --git a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
index 868d384ed2..afedbac6f6 100644
--- a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
+++ b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
@@ -14,6 +14,7 @@ import {
import { decrypt } from "@langfuse/shared/encryption";
import { MixpanelClient } from "./mixpanelClient";
import { recordExportVolume } from "../../services/exportVolumeMetric";
+import { isExportCaughtUp } from "../../services/exportStalenessMetric";
import {
transformTraceForMixpanel,
transformGenerationForMixpanel,
@@ -249,6 +250,8 @@ export const handleMixpanelIntegrationProjectJob = async (
return;
}
+ const runStartTime = new Date();
+
try {
// Fetch relevant data and send it to Mixpanel
const executionConfig: MixpanelExecutionConfig = {
@@ -306,6 +309,12 @@ export const handleMixpanelIntegrationProjectJob = async (
},
data: {
lastSyncAt: executionConfig.maxTimestamp,
+ ...(isExportCaughtUp({
+ lastSyncAt: executionConfig.maxTimestamp,
+ runStartTime,
+ })
+ ? { backfill: false }
+ : {}),
},
});
// Record gzipped on-wire export volume once the run has succeeded.
diff --git a/worker/src/features/mixpanel/handleMixpanelIntegrationSchedule.ts b/worker/src/features/mixpanel/handleMixpanelIntegrationSchedule.ts
index 8eec1dd4e2..32093f3c4f 100644
--- a/worker/src/features/mixpanel/handleMixpanelIntegrationSchedule.ts
+++ b/worker/src/features/mixpanel/handleMixpanelIntegrationSchedule.ts
@@ -12,6 +12,7 @@ export const handleMixpanelIntegrationSchedule = async () => {
{
select: {
lastSyncAt: true,
+ backfill: true,
projectId: true,
},
where: {
@@ -26,6 +27,7 @@ export const handleMixpanelIntegrationSchedule = async () => {
integrations: mixpanelIntegrationProjects.map((integration) => ({
lastSyncAt: integration.lastSyncAt,
window: "1h",
+ backfill: integration.backfill,
})),
});
diff --git a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
index 075705b29e..9d3b28c6ba 100644
--- a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
+++ b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
@@ -28,6 +28,7 @@ import {
import { decrypt } from "@langfuse/shared/encryption";
import { PostHog } from "posthog-node";
import { recordExportVolume } from "../../services/exportVolumeMetric";
+import { isExportCaughtUp } from "../../services/exportStalenessMetric";
import { assertExportSourceWritable } from "../exportWriteModeGuard";
import { classifyCustomerFault } from "../integrations/customerFaultClassification";
import { isRecordNotFoundError } from "../integrations/prismaErrors";
@@ -284,6 +285,8 @@ export const handlePostHogIntegrationProjectJob = async (
return;
}
+ const runStartTime = new Date();
+
try {
// Validate PostHog hostname to prevent SSRF attacks before sending data.
// Rewrap preserving { cause } so the single catch below can classify the
@@ -417,6 +420,12 @@ export const handlePostHogIntegrationProjectJob = async (
lastSyncAt: executionConfig.maxTimestamp,
lastError: null,
lastErrorAt: null,
+ ...(isExportCaughtUp({
+ lastSyncAt: executionConfig.maxTimestamp,
+ runStartTime,
+ })
+ ? { backfill: false }
+ : {}),
},
});
// Record gzipped on-wire export volume once the run has succeeded.
diff --git a/worker/src/features/posthog/handlePostHogIntegrationSchedule.ts b/worker/src/features/posthog/handlePostHogIntegrationSchedule.ts
index c39174e716..b22b2b94fa 100644
--- a/worker/src/features/posthog/handlePostHogIntegrationSchedule.ts
+++ b/worker/src/features/posthog/handlePostHogIntegrationSchedule.ts
@@ -11,6 +11,7 @@ export const handlePostHogIntegrationSchedule = async () => {
const postHogIntegrationProjects = await prisma.posthogIntegration.findMany({
select: {
lastSyncAt: true,
+ backfill: true,
projectId: true,
},
where: {
@@ -24,6 +25,7 @@ export const handlePostHogIntegrationSchedule = async () => {
integrations: postHogIntegrationProjects.map((integration) => ({
lastSyncAt: integration.lastSyncAt,
window: "1h",
+ backfill: integration.backfill,
})),
});
diff --git a/worker/src/services/exportStalenessMetric.ts b/worker/src/services/exportStalenessMetric.ts
index e6c8d64414..3d78cea1d2 100644
--- a/worker/src/services/exportStalenessMetric.ts
+++ b/worker/src/services/exportStalenessMetric.ts
@@ -13,6 +13,23 @@ const BLOB_FREQUENCY_TO_WINDOW: Record<string, ExportStalenessWindow> = {
weekly: "1w",
};
+const BACKFILL_CAUGHT_UP_THRESHOLD_MS = 60 * 60 * 1000;
+
+/**
+ * A successful run ends a backfill once its watermark lands within an hour of
+ * the run start, i.e. the export has reached the live tail.
+ */
+export const isExportCaughtUp = ({
+ lastSyncAt,
+ runStartTime,
+}: {
+ lastSyncAt: Date | null;
+ runStartTime: Date;
+}): boolean =>
+ lastSyncAt !== null &&
+ lastSyncAt.getTime() >
+ runStartTime.getTime() - BACKFILL_CAUGHT_UP_THRESHOLD_MS;
+
// Non-throwing: runs inside the scheduler, where one bad row must not block
// scheduling for every other integration.
export const windowClassFromBlobFrequency = (
@@ -23,7 +40,9 @@ export const windowClassFromBlobFrequency = (
* Emits `now − lastSyncAt` for every enabled integration on each scheduler
* tick. Sampling at a fixed cadence makes percentiles time-weighted, and an
* integration that stops running keeps emitting a rising value instead of
- * going silent. Integrations without a watermark yet are skipped.
+ * going silent. Integrations without a watermark yet are skipped. The
+ * `backfill` tag separates integrations still exporting history, which look
+ * stale for days, from steady state.
*/
export const recordExportStaleness = ({
integration,
@@ -32,14 +51,19 @@ export const recordExportStaleness = ({
}: {
integration: ExportStalenessIntegration;
now: Date;
- integrations: { lastSyncAt: Date | null; window: ExportStalenessWindow }[];
+ integrations: {
+ lastSyncAt: Date | null;
+ window: ExportStalenessWindow;
+ backfill: boolean;
+ }[];
}): void => {
- for (const { lastSyncAt, window } of integrations) {
+ for (const { lastSyncAt, window, backfill } of integrations) {
if (!lastSyncAt) continue;
const stalenessSeconds = (now.getTime() - lastSyncAt.getTime()) / 1000;
recordDistribution(EXPORT_STALENESS_METRIC, Math.max(0, stalenessSeconds), {
integration,
window,
+ backfill: String(backfill),
unit: "seconds",
});
}