🪢 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
perf(audit-logs): keep the relay lease on one worker task (#18728)
Steffen Reuther7a5d9ec49359
diff --git a/worker/AGENTS.md b/worker/AGENTS.mdindex e70a91e61b..87a5b6d8ea 100644--- a/worker/AGENTS.md+++ b/worker/AGENTS.md@@ -91,9 +91,11 @@- Audit log relay: `src/features/audit-log-relay/index.ts` moves Postgres`audit_log_staging` rows into ClickHouse `audit_logs`, deleting them onlyafter ClickHouse acknowledged the insert. It starts only in cloud- deployments (`NEXT_PUBLIC_LANGFUSE_CLOUD_REGION` set). Rows whose payload- fails the staging schema stay with `failed_at` set and are retried after- 10 minutes.+ deployments (`NEXT_PUBLIC_LANGFUSE_CLOUD_REGION` set). One worker task keeps+ the Redis lease and relays; the others check for a free lease every half+ lease TTL, so run count does not grow with the number of tasks. Rows whose+ payload fails the staging schema stay with `failed_at` set and are retried+ after 10 minutes.- Evaluation terminal-outcome classification: `src/features/evaluation/evalExecutionMetrics.ts`. Keep it aligned with shared code evaluator dispatcher error codes and user-visible error mapping.- Service layer: `src/services/*`- `ClickhouseWriter.getInstance()` queues JSON rows; `getNativeInstance()` queuesdiff --git a/worker/src/__tests__/auditLogRelay.test.ts b/worker/src/__tests__/auditLogRelay.test.tsindex 6253e0bdc8..e0bd4cdc3c 100644--- a/worker/src/__tests__/auditLogRelay.test.ts+++ b/worker/src/__tests__/auditLogRelay.test.ts@@ -1,9 +1,10 @@import { randomUUID } from "crypto";import { v7 as uuidv7 } from "uuid";-import { beforeEach, describe, expect, it } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";import { prisma } from "@langfuse/shared/src/db";import {queryClickhouse,+ redis,stageAuditLogEvents,} from "@langfuse/shared/src/server";import {@@ -47,6 +48,9 @@ const auditLogIds = async (orgId: string): Promise<string[]> =>const sorted = (ids: string[]) => [...ids].sort();+// A lease of its own keeps a test clear of other tests and of a local worker.+const testLockKey = () => `langfuse:test:audit-log-relay:${randomUUID()}`;+describe("AuditLogRelay", () => {// The relay claims every staged row, not only the ones a test staged.beforeEach(async () => {@@ -222,12 +226,100 @@ describe("AuditLogRelay", () => {expect(await auditLogIds(orgId)).toEqual(sorted([validId, failingId]));});- it("runs again right away while batches come back full", async () => {+ it("runs again right away while batches come back full", async (ctx) => {+ if (!redis) ctx.skip("Redis must be available for the lease");await stageChangeEvents(randomUUID(), 3);- const relay = new AuditLogRelay({ batchSize: 2 });+ const relay = new AuditLogRelay({ batchSize: 2, lockKey: testLockKey() });await expect(relay.processBatch()).resolves.toBe(0);await expect(relay.processBatch()).resolves.toBeUndefined();expect(await stagedIds()).toEqual([]);+ relay.stop();+ });++ it("relays only on the task that holds the lease", async (ctx) => {+ if (!redis) ctx.skip("Redis must be available for the lease");+ const lockKey = testLockKey();+ const leader = new AuditLogRelay({ lockKey, lockTtlSeconds: 10 });+ const follower = new AuditLogRelay({ lockKey, lockTtlSeconds: 10 });++ await expect(leader.processBatch()).resolves.toBeUndefined();+ const ids = await stageChangeEvents(randomUUID(), 1);++ // Checks the lease again after half its TTL, without relaying.+ await expect(follower.processBatch()).resolves.toBe(5_000);+ expect(await stagedIds()).toEqual(ids);++ await expect(leader.processBatch()).resolves.toBeUndefined();+ expect(await stagedIds()).toEqual([]);++ leader.stop();+ await vi.waitFor(async () => {+ await expect(follower.processBatch()).resolves.toBeUndefined();+ });+ follower.stop();+ });++ it("hands the lease over after repeated failed batches", async (ctx) => {+ if (!redis) ctx.skip("Redis must be available for the lease");+ const lockKey = testLockKey();+ const failing = new AuditLogRelay({+ lockKey,+ lockTtlSeconds: 10,+ intervalMs: 1_000,+ insertRecords: async () => {+ throw new Error("ClickHouse unreachable from this task");+ },+ });+ const healthy = new AuditLogRelay({ lockKey, lockTtlSeconds: 10 });+ await stageChangeEvents(randomUUID(), 1);++ // Backs off while keeping the lease, then waits like a follower.+ await expect(failing.processBatch()).resolves.toBe(2_000);+ await expect(failing.processBatch()).resolves.toBe(4_000);+ await expect(healthy.processBatch()).resolves.toBe(5_000);+ await expect(failing.processBatch()).resolves.toBe(5_000);++ await expect(healthy.processBatch()).resolves.toBeUndefined();+ expect(await stagedIds()).toEqual([]);+ failing.stop();+ healthy.stop();+ });++ it("keeps its lease when a renewal fails but Redis still holds it", async (ctx) => {+ if (!redis) ctx.skip("Redis must be available for the lease");+ const lockKey = testLockKey();+ const leader = new AuditLogRelay({ lockKey, lockTtlSeconds: 10 });+ const follower = new AuditLogRelay({ lockKey, lockTtlSeconds: 10 });+ await expect(leader.processBatch()).resolves.toBeUndefined();+ await stageChangeEvents(randomUUID(), 1);+ // RedisLock.extend() reports a Redis error during renewal as false.+ vi.spyOn(leader["lock"], "extend").mockResolvedValueOnce(false);++ await expect(leader.processBatch()).resolves.toBeUndefined();+ expect(await stagedIds()).toEqual([]);+ await expect(follower.processBatch()).resolves.toBe(5_000);+ leader.stop();+ follower.stop();+ });++ it("releases a lease it acquires while being stopped", async (ctx) => {+ if (!redis) ctx.skip("Redis must be available for the lease");+ const lockKey = testLockKey();+ const stopping = new AuditLogRelay({ lockKey, lockTtlSeconds: 10 });+ const next = new AuditLogRelay({ lockKey, lockTtlSeconds: 10 });+ const lock = stopping["lock"];+ const acquire = lock.acquire.bind(lock);+ vi.spyOn(lock, "acquire").mockImplementationOnce(async () => {+ stopping.stop();+ return acquire();+ });++ await stopping.processBatch();++ await vi.waitFor(async () => {+ await expect(next.processBatch()).resolves.toBeUndefined();+ });+ next.stop();});});diff --git a/worker/src/env.ts b/worker/src/env.tsindex 846178c0af..33817a04cd 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -679,11 +679,13 @@ const EnvSchema = z.object({.int().positive().default(1_000),+ // Tasks without the lease check it every half TTL, and a batch must finish+ // within half of it.LANGFUSE_AUDIT_LOG_RELAY_LOCK_TTL_SECONDS: z.coerce.number().int().positive()- .default(60), // A batch must finish within half of it+ .default(60),// Media Retention Cleaner configuration (S3/PostgreSQL)LANGFUSE_MEDIA_RETENTION_CLEANER_ITEM_LIMIT: z.coercediff --git a/worker/src/features/audit-log-relay/index.ts b/worker/src/features/audit-log-relay/index.tsindex bd37b6e4f7..9ea2e6b7a4 100644--- a/worker/src/features/audit-log-relay/index.ts+++ b/worker/src/features/audit-log-relay/index.ts@@ -8,7 +8,11 @@ import {type AuditLogRecordInsertType,} from "@langfuse/shared/src/server";import { env } from "../../env";-import { PeriodicExclusiveRunner } from "../../utils/PeriodicExclusiveRunner";+import type { LockAcquireResult } from "../../utils/RedisLock";+import {+ PeriodicExclusiveRunner,+ PeriodicExclusiveRunnerLeaseLostError,+} from "../../utils/PeriodicExclusiveRunner";const METRIC_PREFIX = "langfuse.audit_log_relay";@@ -23,6 +27,10 @@ const FAILED_ROW_RETRY_DELAY = Prisma.sql`INTERVAL '10 minutes'`;const MAX_FAILURE_BACKOFF_MS = 30_000;+// A task whose batches keep failing gives up the lease, so a fault local to+// it, such as a broken connection pool, does not stall the relay.+const LEASE_HANDOVER_AFTER_FAILURES = 3;+// Counting the staging table scans it, so the gauges are refreshed at most// this often while a backlog drains batch after batch, and the scan is cut// off well within the lease.@@ -40,16 +48,23 @@ const LOGGED_FAILURES_MAX = 10;* back, so the rows stay and the next batch retries them. A retry can insert* a row a second time; `audit_logs` collapses rows by id.*- * Concurrent batches claim disjoint rows (FOR UPDATE SKIP LOCKED), so the- * Redis lease only keeps workers from competing for the same rows. When Redis- * is unavailable, every worker relays.+ * One worker task keeps the Redis lease and relays every interval. The other+ * tasks check for a free lease every half lease TTL, so a lease left by a+ * crashed task is taken over within 1.5 lease TTLs, and a task whose batches+ * keep failing hands it over. Concurrent batches claim+ * disjoint rows (FOR UPDATE SKIP LOCKED), so the lease only keeps tasks from+ * competing for the same rows. When Redis is unavailable, every task relays+ * at the slower cadence.*/export class AuditLogRelay extends PeriodicExclusiveRunner {private readonly intervalMs: number;private readonly lockTtlSeconds: number;private readonly batchSize: number;private readonly transactionTimeoutMs: number;+ private readonly leaseCheckIntervalMs: number;private readonly insertRecords: AuditLogRecordInserter;+ private holdsLease = false;+ private stopped = false;private consecutiveFailures = 0;private lastStagingMetricsAt = 0;@@ -62,6 +77,7 @@ export class AuditLogRelay extends PeriodicExclusiveRunner {intervalMs?: number;lockTtlSeconds?: number;batchSize?: number;+ lockKey?: string;insertRecords?: AuditLogRecordInserter;} = {},) {@@ -71,7 +87,7 @@ export class AuditLogRelay extends PeriodicExclusiveRunner {super({name: "AuditLogRelay",metricName: "audit_log_relay",- lockKey: AUDIT_LOG_RELAY_LOCK_KEY,+ lockKey: opts.lockKey ?? AUDIT_LOG_RELAY_LOCK_KEY,lockTtlSeconds,onUnavailable: "proceed",});@@ -83,32 +99,95 @@ export class AuditLogRelay extends PeriodicExclusiveRunner {// A batch that runs out of time rolls back before the lease can expire// under it.this.transactionTimeoutMs = (lockTtlSeconds * 1000) / 2;+ this.leaseCheckIntervalMs = (lockTtlSeconds * 1000) / 2;this.insertRecords = opts.insertRecords ?? insertAuditLogRecords;}public override start(): void {+ this.stopped = false;logger.info(`Starting ${this.instanceName}`, {intervalMs: this.intervalMs,lockTtlSeconds: this.lockTtlSeconds,+ leaseCheckIntervalMs: this.leaseCheckIntervalMs,batchSize: this.batchSize,});super.start();}+ /**+ * Releases a held lease, so another task takes over without waiting for+ * its TTL.+ */+ public override stop(): void {+ super.stop();+ this.stopped = true;+ this.releaseLease();+ }+protected async execute(): Promise<number | void> {- return await this.withLock(- async () => {- try {- const result = await this.relayBatch();- this.consecutiveFailures = 0;- // A full batch means more rows are waiting, so run again right away.- return result.claimed === this.batchSize ? 0 : undefined;- } finally {- await this.recordStagingMetrics();- }- },- () => this.backOffAfterFailure(),- );+ const lease = await this.holdLease();+ // stop() may have run while the lease was being taken.+ if (this.stopped) {+ this.releaseLease();+ this.markRunSkipped();+ return;+ }+ if (lease === "held_by_other") {+ this.markRunSkipped();+ return this.leaseCheckIntervalMs;+ }++ try {+ const result = await this.relayBatch();+ this.consecutiveFailures = 0;+ // A full batch means more rows are waiting, so run again right away.+ if (result.claimed === this.batchSize) return 0;+ return lease === "acquired" ? undefined : this.leaseCheckIntervalMs;+ } catch (error) {+ logger.error(`${this.instanceName}: Failed to relay a batch`, { error });+ this.markRunFailed(error);+ return this.backOffAfterFailure();+ } finally {+ await this.recordStagingMetrics();+ }+ }++ /**+ * Renews a held lease at most every third of its TTL, or tries to take a+ * free one. "skipped" means Redis is unavailable; a task that held the+ * lease keeps counting it as held and renews it once Redis is back.+ */+ private async holdLease(): Promise<LockAcquireResult> {+ if (this.holdsLease && (await this.renewLease())) return "acquired";++ const result = await this.lock.acquire();+ if (result === "skipped") return result;+ if (result === "acquired") {+ this.holdsLease = true;+ return result;+ }+ // A renewal that failed on a Redis error leaves this task's own lease in+ // place, which SET NX refuses.+ this.holdsLease =+ this.holdsLease && (await this.lock.isHeldByCurrentProcess());+ return this.holdsLease ? "acquired" : "held_by_other";+ }++ private async renewLease(): Promise<boolean> {+ try {+ await this.extendLockOnProgress();+ return true;+ } catch (error) {+ if (error instanceof PeriodicExclusiveRunnerLeaseLostError) return false;+ throw error;+ }+ }++ private releaseLease(): void {+ if (!this.holdsLease) return;+ this.holdsLease = false;+ // Logs instead of rejecting, and stop() cannot await it.+ this.lock.release();}/**@@ -175,6 +254,11 @@ export class AuditLogRelay extends PeriodicExclusiveRunner {private backOffAfterFailure(): number {recordIncrement(`${METRIC_PREFIX}.relay_errors`, 1);this.consecutiveFailures += 1;+ if (this.consecutiveFailures >= LEASE_HANDOVER_AFTER_FAILURES) {+ this.consecutiveFailures = 0;+ this.releaseLease();+ return this.leaseCheckIntervalMs;+ }return Math.min(this.intervalMs * 2 ** this.consecutiveFailures,MAX_FAILURE_BACKOFF_MS,