🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(worker): prevent PostHog export event loss (#15351)
Valery Meleshkin46b9aeefb652
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6e82f391e2..80306f52f9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -738,8 +738,8 @@ importers:specifier: ^1.390.2version: 1.390.2posthog-node:- specifier: ^5.32.0- version: 5.38.4([email protected])+ specifier: ^5.45.2+ version: 5.45.2([email protected])prexit:specifier: ^2.2.0version: 2.2.0@@ -1069,8 +1069,8 @@ importers:specifier: ^7.3.0version: 7.3.0posthog-node:- specifier: ^5.32.0- version: 5.38.4([email protected])+ specifier: ^5.45.2+ version: 5.45.2([email protected])stripe:specifier: ^17.4.0version: 17.4.0@@ -3744,11 +3744,11 @@ packages:'@polka/[email protected]':resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}- '@posthog/[email protected]':- resolution: {integrity: sha512-KRBuxF/XBm3tNpqWlXpWE82XxsYsJb0jSyEic14LMXMvqDv5iApK1jfV0+seikDb9SpPs3tPkWUfHdwaUtFBtQ==}+ '@posthog/[email protected]':+ resolution: {integrity: sha512-hGM8f5sp3we6Em/RQHXbmyYm554hUx9+9jhf92ZQgDS4/xW72KHyZiO9wcFye+qAx2cJAOhOCDIznmO1FV8IbA==}- '@posthog/[email protected]':- resolution: {integrity: sha512-ASwd7Nf4pViqdYRYaNRyPYRVKWa1CcHUAUWR0XeQJLGdNnsWACBwe0sSieb/cHnKsRXjRwO/23KIY83lm/Ccpw==}+ '@posthog/[email protected]':+ resolution: {integrity: sha512-Pa7FtsBo3V0XrhY4y8Xquwp8U07syuZ2IGQdlsRyxhz0yejQLceFjI58UssCXE5zDCDj3km5l7H3ufD6rHChCg==}'@prisma/[email protected]':resolution: {integrity: sha512-mKq3jQFhjvko5LTJFHGilsuQs+W+T3Gm451NzuTDGQxwCzwXHYnIu2zGkRoW+Exq3Rob7yp2MfzSrdIiZVhrBg==}@@ -9900,8 +9900,8 @@ packages:resolution: {integrity: sha512-z1zh0mMokecCILXxabmo5Xag6uCVYEDhP2JnMYLNxwmKN7d7u1S94XYmhUTF3iyAo2JOg6c7n86mGaTXliz4MA==}- resolution: {integrity: sha512-Jti056f+5C9y1MXb5yhxwwYBITxypWZHWcAp+UevcZ7/AKEQdSB9FiJP3WzEznw4vH3Bz0IlRKVgsofizRAoEA==}+ resolution: {integrity: sha512-QhHw/xL0ntMG/DzqA/qdiKu8JY8ChK5Obm8m1nMJor5sjJ7+pfVJSx1yAynC7iUAJfJ9V+OhBNhDCyi5IFWC0Q==}engines: {node: ^20.20.0 || >=22.22.0}peerDependencies:rxjs: ^7.0.0@@ -14013,7 +14013,7 @@ snapshots:p-map: 7.0.4p-retry: 7.1.1picomatch: 4.0.4- posthog-node: 5.38.4([email protected])+ posthog-node: 5.45.2([email protected])tokenx: 1.3.0ws: 8.21.1xxhash-wasm: 1.1.0@@ -14061,7 +14061,7 @@ snapshots:p-map: 7.0.4p-retry: 7.1.1picomatch: 4.0.4- posthog-node: 5.38.4([email protected])+ posthog-node: 5.45.2([email protected])tokenx: 1.3.0ws: 8.21.1xxhash-wasm: 1.1.0@@ -14880,11 +14880,11 @@ snapshots:'@polka/[email protected]': {}- '@posthog/[email protected]':+ '@posthog/[email protected]':dependencies:- '@posthog/types': 1.391.1+ '@posthog/types': 1.397.0- '@posthog/[email protected]': {}+ '@posthog/[email protected]': {}'@prisma/[email protected]([email protected]([email protected])([email protected]))([email protected])':optionalDependencies:@@ -21862,8 +21862,8 @@ snapshots:dependencies:- '@posthog/core': 1.37.1- '@posthog/types': 1.391.1+ '@posthog/core': 1.43.1+ '@posthog/types': 1.397.0core-js: 3.38.1dompurify: 3.4.12fflate: 0.4.8@@ -21871,9 +21871,9 @@ snapshots:query-selector-shadow-dom: 1.0.1web-vitals: 5.2.0dependencies:- '@posthog/core': 1.37.1+ '@posthog/core': 1.43.1optionalDependencies:rxjs: 7.8.1diff --git a/web/package.json b/web/package.jsonindex 499d68b7f4..ee1a20dbaa 100644--- a/web/package.json+++ b/web/package.json@@ -138,7 +138,7 @@"next-query-params": "^5.1.0","next-themes": "^0.4.6","posthog-js": "^1.390.2",- "posthog-node": "^5.32.0",+ "posthog-node": "^5.45.2","prexit": "^2.2.0","prism-react-renderer": "^2.4.1","protobufjs": "7.6.5",diff --git a/worker/package.json b/worker/package.jsonindex f9e7c43fc0..ee6cf14132 100644--- a/worker/package.json+++ b/worker/package.json@@ -58,7 +58,7 @@"ioredis": "^5.10.1","lodash": "4.18.1","p-limit": "^7.3.0",- "posthog-node": "^5.32.0",+ "posthog-node": "^5.45.2","stripe": "^17.4.0","tiktoken": "^1.0.20","uuid": "^14.0.0",diff --git a/worker/src/__tests__/posthogExportVolume.test.ts b/worker/src/__tests__/posthogExportVolume.test.tsindex 6b9c44f95d..1b6cc55ee2 100644--- a/worker/src/__tests__/posthogExportVolume.test.ts+++ b/worker/src/__tests__/posthogExportVolume.test.ts@@ -12,7 +12,7 @@ describe("countingFetch (posthog export volume)", () => {afterEach(() => vi.unstubAllGlobals());- it("counts /batch/ string and Blob bodies, ignores /flags/, forwards all", async () => {+ it("counts V0 and V1 capture bodies, ignores /flags/, and forwards all", async () => {const volume = { bytes: 0 };const wrapped = countingFetch(volume)!;@@ -30,15 +30,22 @@ describe("countingFetch (posthog export volume)", () => {});expect(volume.bytes).toBe(14);+ await wrapped("https://app.posthog.com/i/v1/analytics/events", {+ method: "POST",+ headers: {},+ body: "v1-body",+ });+ expect(volume.bytes).toBe(21);+// Feature-flag traffic must not be counted as export egress.await wrapped("https://app.posthog.com/flags/?v=2", {method: "POST",headers: {},body: "ignored",});- expect(volume.bytes).toBe(14);+ expect(volume.bytes).toBe(21);// Every request is still forwarded to the underlying fetch.- expect(fetchMock).toHaveBeenCalledTimes(3);+ expect(fetchMock).toHaveBeenCalledTimes(4);});});diff --git a/worker/src/__tests__/posthogIntegrationProjectJob.test.ts b/worker/src/__tests__/posthogIntegrationProjectJob.test.tsindex 52507fbefd..b557dafb7c 100644--- a/worker/src/__tests__/posthogIntegrationProjectJob.test.ts+++ b/worker/src/__tests__/posthogIntegrationProjectJob.test.ts@@ -1,19 +1,54 @@import { describe, it, expect, beforeEach, vi } from "vitest";/**- * Unit tests for the PostHog integration project job's events_only legacy- * guard (LFE-10148): a persisted legacy export source on an events_only- * deployment reads the v3 traces/observations tables, which are no longer- * written — the job must fail loudly before exporting empty data and- * advancing lastSyncAt. Mocked in the same style as- * mixpanelIntegrationProjectJob.test.ts.+ * Unit tests for the PostHog integration project job:+ *+ * 1. The write-mode guards prevent a stale export source from advancing its+ * cursor after reading from tables that the deployment no longer writes.+ *+ * 2. Export delivery controls (issue #12786) reuse one PostHog client,+ * process streams sequentially, flush before the producer can outrun the+ * SDK queue, and shut the client down on every exit path.*/// vi.mock factories are hoisted above module scope, so all shared mutable// state the factories touch must live inside vi.hoisted().const h = vi.hoisted(() => {- async function* fakeStream(label: string) {- yield { langfuse_id: `${label}-1` };+ type StreamKind = "scores" | "traces" | "generations" | "events";++ const timeline: string[] = [];+ const constructed: Array<{+ capture: ReturnType<typeof vi.fn>;+ flush: ReturnType<typeof vi.fn>;+ shutdown: ReturnType<typeof vi.fn>;+ options: Record<string, unknown>;+ }> = [];+ const state = {+ afterFlush: undefined as (() => void) | undefined,+ emitErrorAfterNonEmptyFlush: false,+ emittedError: false,+ emitErrorOnShutdown: false,+ shutdownError: undefined as Error | undefined,+ rowCounts: {+ scores: 2,+ traces: 2,+ generations: 2,+ events: 2,+ } satisfies Record<StreamKind, number>,+ };++ function fakeStream(label: StreamKind) {+ return (async function* () {+ timeline.push(`${label}:start`);+ try {+ for (let index = 0; index < state.rowCounts[label]; index++) {+ await Promise.resolve();+ yield { langfuse_id: `${label}-${index + 1}` };+ }+ } finally {+ timeline.push(`${label}:end`);+ }+ })();}const posthogIntegrationUpdate = vi.fn();@@ -37,6 +72,9 @@ const h = vi.hoisted(() => {const db = { integration: defaultIntegration() as Record<string, unknown> };return {+ timeline,+ constructed,+ state,posthogIntegrationUpdate,getTraces,getGenerations,@@ -82,19 +120,51 @@ vi.mock("@langfuse/shared/encryption", () => ({vi.mock("posthog-node", () => ({PostHog: class {capture = vi.fn();- flush = vi.fn(async () => {});- on = vi.fn();+ private errorHandler?: (error: Error) => void;+ flush = vi.fn(async () => {+ h.state.afterFlush?.();+ if (+ h.state.emitErrorAfterNonEmptyFlush &&+ !h.state.emittedError &&+ this.capture.mock.calls.length > 0+ ) {+ h.state.emittedError = true;+ this.errorHandler?.(new Error("send failed"));+ }+ });+ shutdown = vi.fn(async () => {+ if (h.state.emitErrorOnShutdown) {+ this.errorHandler?.(new Error("shutdown delivery failed"));+ }+ if (h.state.shutdownError) throw h.state.shutdownError;+ });+ on = vi.fn((event: string, handler: (error: Error) => void) => {+ if (event === "error") this.errorHandler = handler;+ });+ constructor(_apiKey: string, options: Record<string, unknown> = {}) {+ h.constructed.push({+ capture: this.capture,+ flush: this.flush,+ shutdown: this.shutdown,+ options,+ });+ }},}));// Resolves to worker/src/env (read by exportWriteModeGuard and the score// routing); the helpers mirror the real implementations.vi.mock("../env", () => ({- env: { LANGFUSE_MIGRATION_V4_WRITE_MODE: "legacy" },- v4WritesToLegacyTables: (e: { LANGFUSE_MIGRATION_V4_WRITE_MODE: string }) =>- e.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only",- v4WritesToEventsTable: (e: { LANGFUSE_MIGRATION_V4_WRITE_MODE: string }) =>- e.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "legacy",+ env: {+ LANGFUSE_MIGRATION_V4_WRITE_MODE: "legacy",+ LANGFUSE_POSTHOG_FLUSH_DELAY_MS: 0,+ },+ v4WritesToLegacyTables: (workerEnv: {+ LANGFUSE_MIGRATION_V4_WRITE_MODE: string;+ }) => workerEnv.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only",+ v4WritesToEventsTable: (workerEnv: {+ LANGFUSE_MIGRATION_V4_WRITE_MODE: string;+ }) => workerEnv.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "legacy",}));// Import after mocks are registered.@@ -108,16 +178,30 @@ function makeJob() {} as unknown as Parameters<typeof handlePostHogIntegrationProjectJob>[0];}+function resetSharedState() {+ h.timeline.length = 0;+ h.constructed.length = 0;+ h.state.afterFlush = undefined;+ h.state.emitErrorAfterNonEmptyFlush = false;+ h.state.emittedError = false;+ h.state.emitErrorOnShutdown = false;+ h.state.shutdownError = undefined;+ h.state.rowCounts.scores = 2;+ h.state.rowCounts.traces = 2;+ h.state.rowCounts.generations = 2;+ h.state.rowCounts.events = 2;+ h.posthogIntegrationUpdate.mockClear();+ h.getTraces.mockClear();+ h.getGenerations.mockClear();+ h.getScores.mockClear();+ h.getEvents.mockClear();+ h.db.integration = h.defaultIntegration();+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";+ (env as any).LANGFUSE_POSTHOG_FLUSH_DELAY_MS = 0;+}+describe("handlePostHogIntegrationProjectJob events_only legacy guard (LFE-10148)", () => {- beforeEach(() => {- h.posthogIntegrationUpdate.mockClear();- h.getTraces.mockClear();- h.getGenerations.mockClear();- h.getScores.mockClear();- h.getEvents.mockClear();- h.db.integration = h.defaultIntegration();- (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";- });+ beforeEach(resetSharedState);it("throws before export and does not advance lastSyncAt on events_only + legacy source", async () => {(env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";@@ -180,15 +264,7 @@ describe("handlePostHogIntegrationProjectJob events_only legacy guard (LFE-10148// LFE-11009: enriched sources on legacy write mode must fail loudly instead// of silently exporting empty data while lastSyncAt advances.describe("handlePostHogIntegrationProjectJob legacy-mode enriched guard (LFE-11009)", () => {- beforeEach(() => {- h.posthogIntegrationUpdate.mockClear();- h.getTraces.mockClear();- h.getGenerations.mockClear();- h.getScores.mockClear();- h.getEvents.mockClear();- h.db.integration = h.defaultIntegration();- (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";- });+ beforeEach(resetSharedState);it.each(["EVENTS", "TRACES_OBSERVATIONS_EVENTS"])("throws before export and does not advance lastSyncAt on legacy + %s source",@@ -215,3 +291,137 @@ describe("handlePostHogIntegrationProjectJob legacy-mode enriched guard (LFE-110expect(h.posthogIntegrationUpdate).toHaveBeenCalledTimes(1);});});++describe("handlePostHogIntegrationProjectJob delivery controls (issue #12786)", () => {+ beforeEach(() => {+ resetSharedState();+ h.db.integration = {+ ...h.defaultIntegration(),+ exportSource: "TRACES_OBSERVATIONS_EVENTS",+ };+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";+ });++ it("uses one client, runs streams sequentially, and shuts down", async () => {+ await handlePostHogIntegrationProjectJob(makeJob());++ expect(h.constructed).toHaveLength(1);+ expect(h.constructed[0].options).toMatchObject({+ flushAt: 1_000,+ maxQueueSize: 10_000,+ });+ expect(h.timeline).toEqual([+ "scores:start",+ "scores:end",+ "traces:start",+ "traces:end",+ "generations:start",+ "generations:end",+ "events:start",+ "events:end",+ ]);+ expect(h.constructed[0].shutdown).toHaveBeenCalledTimes(1);+ });++ it("flushes before producing beyond the SDK flush threshold", async () => {+ h.db.integration = {+ ...h.defaultIntegration(),+ exportSource: "TRACES_OBSERVATIONS",+ };+ h.state.rowCounts.scores = 1_001;+ h.state.rowCounts.traces = 0;+ h.state.rowCounts.generations = 0;++ await handlePostHogIntegrationProjectJob(makeJob());++ expect(h.constructed).toHaveLength(1);+ const { capture, flush } = h.constructed[0];+ expect(capture).toHaveBeenCalledTimes(1_001);+ expect(flush).toHaveBeenCalledTimes(2);+ expect(capture.mock.invocationCallOrder[999]).toBeLessThan(+ flush.mock.invocationCallOrder[0],+ );+ expect(flush.mock.invocationCallOrder[0]).toBeLessThan(+ capture.mock.invocationCallOrder[1_000],+ );+ });++ it("waits for the configured delay after a non-empty flush", async () => {+ vi.useFakeTimers();+ try {+ (env as any).LANGFUSE_POSTHOG_FLUSH_DELAY_MS = 25;+ h.state.rowCounts.scores = 1;+ h.state.rowCounts.traces = 0;+ h.state.rowCounts.generations = 0;+ h.state.rowCounts.events = 0;++ let resolveFlush!: () => void;+ const flushStarted = new Promise<void>((resolve) => {+ resolveFlush = resolve;+ });+ h.state.afterFlush = resolveFlush;+ const run = handlePostHogIntegrationProjectJob(makeJob());+ await flushStarted;+ await vi.advanceTimersByTimeAsync(0);++ expect(vi.getTimerCount()).toBe(1);+ expect(h.posthogIntegrationUpdate).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(24);+ expect(h.posthogIntegrationUpdate).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ await run;+ expect(h.posthogIntegrationUpdate).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it("stops the stream immediately when a flush reports an error", async () => {+ h.db.integration = {+ ...h.defaultIntegration(),+ exportSource: "EVENTS",+ };+ h.state.rowCounts.scores = 0;+ h.state.rowCounts.events = 1_001;+ h.state.emitErrorAfterNonEmptyFlush = true;++ await expect(handlePostHogIntegrationProjectJob(makeJob())).rejects.toThrow(+ "send failed",+ );++ const captureCount = h.constructed.reduce(+ (count, client) => count + client.capture.mock.calls.length,+ 0,+ );+ expect(captureCount).toBe(1_000);+ expect(h.posthogIntegrationUpdate).not.toHaveBeenCalled();+ });++ it("preserves the stream error and cursor when shutdown also fails", async () => {+ h.state.shutdownError = new Error("shutdown failed");+ h.getScores.mockImplementationOnce(() =>+ (async function* (): AsyncGenerator<{ langfuse_id: string }> {+ yield { langfuse_id: "scores-1" };+ throw new Error("stream failed");+ })(),+ );++ await expect(handlePostHogIntegrationProjectJob(makeJob())).rejects.toThrow(+ "stream failed",+ );++ expect(h.constructed).toHaveLength(1);+ expect(h.constructed[0].shutdown).toHaveBeenCalledTimes(1);+ expect(h.posthogIntegrationUpdate).not.toHaveBeenCalled();+ });++ it("does not advance the cursor when shutdown reports a delivery error", async () => {+ h.state.emitErrorOnShutdown = true;++ await expect(handlePostHogIntegrationProjectJob(makeJob())).rejects.toThrow(+ "shutdown delivery failed",+ );++ expect(h.posthogIntegrationUpdate).not.toHaveBeenCalled();+ });+});diff --git a/worker/src/__tests__/posthogNodeDelivery.test.ts b/worker/src/__tests__/posthogNodeDelivery.test.tsnew file mode 100644index 0000000000..cb1c731581--- /dev/null+++ b/worker/src/__tests__/posthogNodeDelivery.test.ts@@ -0,0 +1,173 @@+import { gunzipSync } from "node:zlib";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { PostHog } from "posthog-node";++type PostHogOptions = NonNullable<ConstructorParameters<typeof PostHog>[1]>;+type PostHogFetch = NonNullable<PostHogOptions["fetch"]>;+type PostHogFetchOptions = Parameters<PostHogFetch>[1];+type PostHogFetchResponse = Awaited<ReturnType<PostHogFetch>>;++const okResponse = (): PostHogFetchResponse => ({+ status: 200,+ text: async () => "",+ json: async () => ({}),+ headers: { get: () => null },+});++const decodeBatch = async (options: PostHogFetchOptions) => {+ const { body } = options;+ let buffer: Buffer;+ if (typeof body === "string") {+ buffer = Buffer.from(body);+ } else if (body instanceof Blob) {+ buffer = Buffer.from(await body.arrayBuffer());+ } else {+ throw new Error(`Unexpected PostHog request body: ${typeof body}`);+ }+ if (options.headers["Content-Encoding"] === "gzip") {+ buffer = gunzipSync(buffer);+ }+ return JSON.parse(buffer.toString("utf8")) as {+ batch: Array<{ uuid?: string }>;+ };+};++const createRejectedCaptureClient = () => {+ const sendErrors: Error[] = [];+ const fetch: PostHogFetch = async () => ({+ status: 500,+ text: async () => "capture failed",+ json: async () => ({}),+ headers: { get: () => null },+ });+ const client = new PostHog("phc_delivery_test", {+ host: "https://posthog.invalid",+ flushAt: 1_000,+ maxQueueSize: 10_000,+ fetchRetryCount: 0,+ fetchRetryDelay: 0,+ fetch,+ });+ client.on("error", (error) => {+ sendErrors.push(error instanceof Error ? error : new Error(String(error)));+ });+ client.capture({+ distinctId: "langfuse-project",+ event: "langfuse observation",+ properties: { exportId: "observation-1" },+ });++ return { client, sendErrors };+};++describe("posthog-node delivery contract", () => {+ beforeEach(() => vi.stubEnv("POSTHOG_CAPTURE_MODE", "v0"));+ afterEach(() => vi.unstubAllEnvs());++ it("applies awaited backpressure and delivers every captured event", async () => {+ const eventCount = 10_005;+ const expectedUuids = Array.from(+ { length: eventCount },+ (_, index) =>+ `00000000-0000-4000-8000-${index.toString().padStart(12, "0")}`,+ );+ const deliveredUuids: string[] = [];+ let resolveFirstRequest!: () => void;+ const firstRequestStarted = new Promise<void>((resolve) => {+ resolveFirstRequest = resolve;+ });+ let releaseFirstRequest!: () => void;+ const firstRequestGate = new Promise<void>((resolve) => {+ releaseFirstRequest = resolve;+ });+ let requestCount = 0;++ const fetch: PostHogFetch = async (url, options) => {+ requestCount++;+ if (requestCount === 1) {+ resolveFirstRequest();+ }+ expect(url.endsWith("/batch/")).toBe(true);+ expect(options.headers["Content-Encoding"]).toBe("gzip");+ expect(options.body).toBeInstanceOf(Blob);+ const payload = await decodeBatch(options);+ deliveredUuids.push(+ ...payload.batch.flatMap((event) => (event.uuid ? [event.uuid] : [])),+ );+ if (requestCount === 1) {+ await firstRequestGate;+ }+ return okResponse();+ };++ const client = new PostHog("phc_delivery_test", {+ host: "https://posthog.invalid",+ flushAt: 1_000,+ maxQueueSize: 10_000,+ flushInterval: 60_000,+ fetch,+ });+ let shutdownComplete = false;+ let exportRun: Promise<void> | undefined;++ try {+ let produced = 0;+ exportRun = (async () => {+ for (let index = 0; index < eventCount; index++) {+ produced++;+ client.capture({+ distinctId: "langfuse-project",+ event: "langfuse observation",+ properties: { exportId: `observation-${index}` },+ uuid: expectedUuids[index],+ });+ if (produced % 1_000 === 0) {+ await client.flush();+ }+ }+ if (produced % 1_000 !== 0) {+ await client.flush();+ }+ })();++ await firstRequestStarted;+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(produced).toBe(1_000);++ releaseFirstRequest();+ await exportRun;++ expect(deliveredUuids).toHaveLength(eventCount);+ expect(new Set(deliveredUuids)).toEqual(new Set(expectedUuids));++ await client.shutdown();+ shutdownComplete = true;+ } finally {+ releaseFirstRequest();+ await exportRun?.catch(() => {});+ if (!shutdownComplete) {+ await client.shutdown().catch(() => {});+ }+ }+ });++ it("rejects flush when the capture endpoint rejects a batch", async () => {+ const { client, sendErrors } = createRejectedCaptureClient();++ try {+ await expect(client.flush()).rejects.toThrow(+ "HTTP error while fetching PostHog",+ );+ expect(sendErrors).toHaveLength(1);+ } finally {+ await client.shutdown();+ }+ });++ it("emits a delivery error but resolves shutdown after a rejected batch", async () => {+ const { client, sendErrors } = createRejectedCaptureClient();++ await expect(client.shutdown()).resolves.toBeUndefined();+ expect(sendErrors).toHaveLength(1);+ });+});diff --git a/worker/src/env.ts b/worker/src/env.tsindex 1fc9930102..e7cc10f3a1 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -136,6 +136,9 @@ const EnvSchema = z.object({// Delay (ms) inserted after each Mixpanel flush to throttle analytics exports// and avoid overwhelming the target instance (see issue #12786).LANGFUSE_MIXPANEL_FLUSH_DELAY_MS: z.coerce.number().min(0).default(100),+ // Delay (ms) after each PostHog flush. Together with 1,000-event flushes,+ // this bounds the export rate for fast-acknowledging target instances.+ LANGFUSE_POSTHOG_FLUSH_DELAY_MS: z.coerce.number().min(0).default(100),LANGFUSE_DATASET_DELETE_CONCURRENCY: z.coerce.number().positive().default(1),LANGFUSE_PROJECT_DELETE_CONCURRENCY: z.coerce.number().positive().default(1),LANGFUSE_EVAL_EXECUTION_WORKER_CONCURRENCY: z.coercediff --git a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.tsindex d13790f9c6..9ef9f637b5 100644--- a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts+++ b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts@@ -35,15 +35,37 @@ type PostHogExecutionConfig = {// attempt recovers without manual intervention while healthy syncs stay fast.useGraceHash: boolean;// Shared accumulator for gzipped on-wire upload volume, written by the- // fetch wrapper on each client and read once the run succeeds.+ // fetch wrapper and read once the run succeeds.volume: { bytes: number };+ // Last error emitted by the shared PostHog client. The SDK reports+ // asynchronous delivery failures through this handler.+ sendError?: Error;};const postHogSettings = {- flushAt: 1000,- // Must be >= the capture loops' manual flush cadence (every 10k events);- // past this cap the SDK silently drops the oldest queued event.- maxQueueSize: 10000,+ flushAt: 1_000,+ // Keep enough headroom for events captured while an SDK flush is in flight.+ // Older posthog-node releases defaulted this to 1,000 and silently evicted+ // the oldest events when Langfuse produced a burst.+ maxQueueSize: 10_000,+};++const sleep = (ms: number) =>+ ms > 0+ ? new Promise((resolve) => setTimeout(resolve, ms))+ : Promise.resolve();++const throwIfPostHogSendError = (config: PostHogExecutionConfig) => {+ if (config.sendError) throw config.sendError;+};++const flushPostHog = async (+ posthog: PostHog,+ config: PostHogExecutionConfig,+) => {+ await posthog.flush();+ throwIfPostHogSendError(config);+ await sleep(env.LANGFUSE_POSTHOG_FLUSH_DELAY_MS);};type PostHogClientOptions = NonNullable<@@ -51,12 +73,14 @@ type PostHogClientOptions = NonNullable<>;// Wrap the SDK's fetch transport to count gzipped on-wire upload volume for-// the export-volume metric. The SDK gzips the /batch/ body by default and also-// calls /flags/, so only /batch/ request bodies are measured (LFE-10508).+// the export-volume metric. Capture V0 uses /batch/ and the opt-in Capture V1+// mode uses /i/v1/analytics/events; feature-flag requests are excluded.export const countingFetch =(volume: { bytes: number }): PostHogClientOptions["fetch"] =>(url, options) => {- if (url.endsWith("/batch/")) {+ // Extend the existing V0 counter to cover the additional capture mode+ // supported by newer posthog-node releases.+ if (url.endsWith("/batch/") || url.endsWith("/i/v1/analytics/events")) {const body = options.body;if (typeof body === "string") {volume.bytes += Buffer.byteLength(body);@@ -67,64 +91,49 @@ export const countingFetch =// counting 0) if a future SDK version uses another body type, so the// export-volume under-reporting is observable.logger.warn(- `[POSTHOG] Unexpected /batch/ body type "${typeof body}"; export volume under-reported`,+ `[POSTHOG] Unexpected capture body type "${typeof body}"; export volume under-reported`,);}}return globalThis.fetch(url, options as RequestInit);};-const processPostHogTraces = async (config: PostHogExecutionConfig) => {- const traces = getTracesForAnalyticsIntegrations(- config.projectId,- config.projectName,- config.minTimestamp,- config.maxTimestamp,- { useGraceHash: config.useGraceHash },- );-+const processPostHogStream = async <T>(+ posthog: PostHog,+ config: PostHogExecutionConfig,+ stream: AsyncIterable<T>,+ streamName: "traces" | "generations" | "scores" | "events",+ transform: (value: T, projectId: string) => Parameters<PostHog["capture"]>[0],+) => {logger.info(- `[POSTHOG] Sending traces for project ${config.projectId} to PostHog`,+ `[POSTHOG] Sending ${streamName} for project ${config.projectId} to PostHog`,);- // Send each via PostHog SDK- const posthog = new PostHog(config.decryptedPostHogApiKey, {- host: config.postHogHost,- ...postHogSettings,- fetch: countingFetch(config.volume),- });-- let sendError: Error | undefined;- posthog.on("error", (error) => {- logger.error(- `[POSTHOG] Error sending traces to PostHog for project ${config.projectId}: ${error}`,- );- sendError = error instanceof Error ? error : new Error(String(error));- });-let count = 0;- for await (const trace of traces) {- if (sendError) throw sendError;+ for await (const value of stream) {+ throwIfPostHogSendError(config);count++;- const event = transformTraceForPostHog(trace, config.projectId);- posthog.capture(event);- if (count % 10000 === 0) {- await posthog.flush();- if (sendError) throw sendError;+ posthog.capture(transform(value, config.projectId));+ if (count % postHogSettings.flushAt === 0) {+ await flushPostHog(posthog, config);logger.info(- `[POSTHOG] Sent ${count} traces to PostHog for project ${config.projectId}`,+ `[POSTHOG] Sent ${count} ${streamName} to PostHog for project ${config.projectId}`,);}}- await posthog.flush();- if (sendError) throw sendError;+ if (count % postHogSettings.flushAt !== 0) {+ await flushPostHog(posthog, config);+ }logger.info(- `[POSTHOG] Sent ${count} traces to PostHog for project ${config.projectId}`,+ `[POSTHOG] Sent ${count} ${streamName} to PostHog for project ${config.projectId}`,);};-const processPostHogGenerations = async (config: PostHogExecutionConfig) => {- const generations = getGenerationsForAnalyticsIntegrations(+const processPostHogTraces = async (+ posthog: PostHog,+ config: PostHogExecutionConfig,+) => {+ const traces = getTracesForAnalyticsIntegrations(config.projectId,config.projectName,config.minTimestamp,@@ -132,47 +141,40 @@ const processPostHogGenerations = async (config: PostHogExecutionConfig) => {{ useGraceHash: config.useGraceHash },);- logger.info(- `[POSTHOG] Sending generations for project ${config.projectId} to PostHog`,+ await processPostHogStream(+ posthog,+ config,+ traces,+ "traces",+ transformTraceForPostHog,);+};- // Send each via PostHog SDK- const posthog = new PostHog(config.decryptedPostHogApiKey, {- host: config.postHogHost,- ...postHogSettings,- fetch: countingFetch(config.volume),- });-- let sendError: Error | undefined;- posthog.on("error", (error) => {- logger.error(- `[POSTHOG] Error sending generations to PostHog for project ${config.projectId}: ${error}`,- );- sendError = error instanceof Error ? error : new Error(String(error));- });+const processPostHogGenerations = async (+ posthog: PostHog,+ config: PostHogExecutionConfig,+) => {+ const generations = getGenerationsForAnalyticsIntegrations(+ config.projectId,+ config.projectName,+ config.minTimestamp,+ config.maxTimestamp,+ { useGraceHash: config.useGraceHash },+ );- let count = 0;- for await (const generation of generations) {- if (sendError) throw sendError;- count++;- const event = transformGenerationForPostHog(generation, config.projectId);- posthog.capture(event);- if (count % 10000 === 0) {- await posthog.flush();- if (sendError) throw sendError;- logger.info(- `[POSTHOG] Sent ${count} generations to PostHog for project ${config.projectId}`,- );- }- }- await posthog.flush();- if (sendError) throw sendError;- logger.info(- `[POSTHOG] Sent ${count} generations to PostHog for project ${config.projectId}`,+ await processPostHogStream(+ posthog,+ config,+ generations,+ "generations",+ transformGenerationForPostHog,);};-const processPostHogScores = async (config: PostHogExecutionConfig) => {+const processPostHogScores = async (+ posthog: PostHog,+ config: PostHogExecutionConfig,+) => {const scores = getScoresForAnalyticsIntegrations(config.projectId,config.projectName,@@ -185,47 +187,19 @@ const processPostHogScores = async (config: PostHogExecutionConfig) => {},);- logger.info(- `[POSTHOG] Sending scores for project ${config.projectId} to PostHog`,- );-- // Send each via PostHog SDK- const posthog = new PostHog(config.decryptedPostHogApiKey, {- host: config.postHogHost,- ...postHogSettings,- fetch: countingFetch(config.volume),- });-- let sendError: Error | undefined;- posthog.on("error", (error) => {- logger.error(- `[POSTHOG] Error sending scores to PostHog for project ${config.projectId}: ${error}`,- );- sendError = error instanceof Error ? error : new Error(String(error));- });-- let count = 0;- for await (const score of scores) {- if (sendError) throw sendError;- count++;- const event = transformScoreForPostHog(score, config.projectId);- posthog.capture(event);- if (count % 10000 === 0) {- await posthog.flush();- if (sendError) throw sendError;- logger.info(- `[POSTHOG] Sent ${count} scores to PostHog for project ${config.projectId}`,- );- }- }- await posthog.flush();- if (sendError) throw sendError;- logger.info(- `[POSTHOG] Sent ${count} scores to PostHog for project ${config.projectId}`,+ await processPostHogStream(+ posthog,+ config,+ scores,+ "scores",+ transformScoreForPostHog,);};-const processPostHogEvents = async (config: PostHogExecutionConfig) => {+const processPostHogEvents = async (+ posthog: PostHog,+ config: PostHogExecutionConfig,+) => {const events = getEventsForAnalyticsIntegrations(config.projectId,config.projectName,@@ -233,42 +207,12 @@ const processPostHogEvents = async (config: PostHogExecutionConfig) => {config.maxTimestamp,);- logger.info(- `[POSTHOG] Sending events for project ${config.projectId} to PostHog`,- );-- // Send each via PostHog SDK- const posthog = new PostHog(config.decryptedPostHogApiKey, {- host: config.postHogHost,- ...postHogSettings,- fetch: countingFetch(config.volume),- });-- let sendError: Error | undefined;- posthog.on("error", (error) => {- logger.error(- `[POSTHOG] Error sending events to PostHog for project ${config.projectId}: ${error}`,- );- sendError = error instanceof Error ? error : new Error(String(error));- });-- let count = 0;- for await (const analyticsEvent of events) {- if (sendError) throw sendError;- count++;- const event = transformEventForPostHog(analyticsEvent, config.projectId);- posthog.capture(event);- if (count % 10000 === 0) {- await posthog.flush();- logger.info(- `[POSTHOG] Sent ${count} events to PostHog for project ${config.projectId}`,- );- }- }- await posthog.flush();- if (sendError) throw sendError;- logger.info(- `[POSTHOG] Sent ${count} events to PostHog for project ${config.projectId}`,+ await processPostHogStream(+ posthog,+ config,+ events,+ "events",+ transformEventForPostHog,);};@@ -380,31 +324,56 @@ export const handlePostHogIntegrationProjectJob = async ("Select the enriched observations export source in the PostHog integration settings.",);- const processPromises: Promise<void>[] = [];-- // Always include scores- processPromises.push(processPostHogScores(executionConfig));+ // Reuse one client and process streams sequentially so their aggregate+ // production rate cannot outrun the SDK's bounded queue.+ const posthog = new PostHog(executionConfig.decryptedPostHogApiKey, {+ host: executionConfig.postHogHost,+ ...postHogSettings,+ fetch: countingFetch(executionConfig.volume),+ });- // Traces and observations - for TRACES_OBSERVATIONS and TRACES_OBSERVATIONS_EVENTS- if (- postHogIntegration.exportSource === "TRACES_OBSERVATIONS" ||- postHogIntegration.exportSource === "TRACES_OBSERVATIONS_EVENTS"- ) {- processPromises.push(- processPostHogTraces(executionConfig),- processPostHogGenerations(executionConfig),- );- }+ try {+ posthog.on("error", (error) => {+ logger.error(+ `[POSTHOG] Error sending data to PostHog for project ${projectId}: ${error}`,+ );+ executionConfig.sendError =+ error instanceof Error ? error : new Error(String(error));+ });++ // Always include scores+ await processPostHogScores(posthog, executionConfig);++ // Traces and observations - for TRACES_OBSERVATIONS and TRACES_OBSERVATIONS_EVENTS+ if (+ postHogIntegration.exportSource === "TRACES_OBSERVATIONS" ||+ postHogIntegration.exportSource === "TRACES_OBSERVATIONS_EVENTS"+ ) {+ await processPostHogTraces(posthog, executionConfig);+ await processPostHogGenerations(posthog, executionConfig);+ }- // Events - for EVENTS and TRACES_OBSERVATIONS_EVENTS- if (- postHogIntegration.exportSource === "EVENTS" ||- postHogIntegration.exportSource === "TRACES_OBSERVATIONS_EVENTS"- ) {- processPromises.push(processPostHogEvents(executionConfig));+ // Events - for EVENTS and TRACES_OBSERVATIONS_EVENTS+ if (+ postHogIntegration.exportSource === "EVENTS" ||+ postHogIntegration.exportSource === "TRACES_OBSERVATIONS_EVENTS"+ ) {+ await processPostHogEvents(posthog, executionConfig);+ }+ } catch (processingError) {+ try {+ await posthog.shutdown();+ } catch (shutdownError) {+ logger.error(+ `[POSTHOG] Error shutting down PostHog client for project ${projectId} after export failure`,+ shutdownError,+ );+ }+ throw processingError;}- await Promise.all(processPromises);+ await posthog.shutdown();+ throwIfPostHogSendError(executionConfig);// Update the last run information for the postHogIntegration record.await prisma.posthogIntegration.update({