Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix: S3/MinIO event storage fails silently when observation IDs exceed ext4 NAME_MAX (#14090)

Valery Meleshkinc753ff5dbdf3
diff --git a/.env.dev.example b/.env.dev.example
index 245b58b629..6926510938 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -113,6 +113,10 @@ LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT=http://localhost:9090
## Necessary for minio compatibility
LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE=true
LANGFUSE_S3_EVENT_UPLOAD_PREFIX=events/
+## Per-segment byte budget for S3 event keys built from entity IDs.
+## Default 2048 is above idSchema's 800-byte cap,
+## so length-driven hashing is disabled out of the box.
+# LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES=2048
# Set during docker build of application
# Used to disable environment verification at build time
diff --git a/.env.prod.example b/.env.prod.example
index 045704cd7f..1421db3e61 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -175,6 +175,17 @@ OTEL_SERVICE_NAME="langfuse"
# LANGFUSE_S3_EVENT_UPLOAD_REGION=
# LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID=
# LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY=
+#
+# Per-segment byte budget for S3 event keys built from entity IDs.
+# Default 2048 is above idSchema's 800-byte cap, so length-driven hashing
+# is disabled out of the box. Lower this on backends with a per-segment
+# limit β€” set to 255 for MinIO on ext4 (or any other NAME_MAX=255 fs) to
+# enable hash-suffix sanitization. Must be the same across web and worker;
+# changing it re-keys long-ID objects.
+# In order to avoid missing writes when upgrading we recommend deploying
+# with the default value first, then setting it to a desired limit.
+# LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES=2048
+#
# Whether to use blob_storage_file_log table to manage blob storage events
# Can be set to `false` if `event` entities are managed using lifecycle policies in the blob storage bucket.
LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 0a74da5b36..9a63371346 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -1,6 +1,17 @@
import { z } from "zod";
import { removeEmptyEnvVariables } from "./utils/environment";
+// Per-segment byte budget for S3 event keys. Off by default (2048 > 800-byte
+// idSchema cap). Lower to 255 for MinIO on ext4. Affects only new writes β€”
+// existing objects are read by recorded path, not reconstructed.
+// Shared with worker/src/env.ts to keep validation rules identical.
+export const langfuseS3EventKeyMaxSegmentBytesSchema = z.coerce
+ .number()
+ .int()
+ .min(64)
+ .max(2048)
+ .default(2048);
+
const EnvSchema = z.object({
NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: z.string().optional(),
// Dev-only override: set to an ISO datetime string to shift the legacy blob
@@ -229,6 +240,8 @@ const EnvSchema = z.object({
.default("false"),
LANGFUSE_S3_EVENT_UPLOAD_SSE: z.enum(["AES256", "aws:kms"]).optional(),
LANGFUSE_S3_EVENT_UPLOAD_SSE_KMS_KEY_ID: z.string().optional(),
+ LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES:
+ langfuseS3EventKeyMaxSegmentBytesSchema,
LANGFUSE_S3_MEDIA_UPLOAD_BUCKET: z.string().optional(),
LANGFUSE_S3_MEDIA_UPLOAD_PREFIX: z.string().default(""),
LANGFUSE_S3_MEDIA_UPLOAD_REGION: z.string().optional(),
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index a3b95c9a0b..3431ffd889 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -1,4 +1,6 @@
export * from "./services/StorageService";
+export * from "./services/safeBlobKeySegment";
+export * from "./ingestion/eventBucketPath";
export * from "./cache";
export * from "./services/BufferedStreamUploader";
export * from "./services/S3ChunkedUploadStrategy";
diff --git a/packages/shared/src/server/ingestion/eventBucketPath.ts b/packages/shared/src/server/ingestion/eventBucketPath.ts
new file mode 100644
index 0000000000..b7541f71e7
--- /dev/null
+++ b/packages/shared/src/server/ingestion/eventBucketPath.ts
@@ -0,0 +1,118 @@
+import { env } from "../../env";
+import { type IngestionEntityTypes } from "../clickhouse/schemaUtils";
+import { safeBlobKeySegment } from "../services/safeBlobKeySegment";
+
+/**
+ * Standard event-upload key: `<projectId>/<entityType>/<eventBodyId>/<eventId>.json`
+ * relative to `LANGFUSE_S3_EVENT_UPLOAD_PREFIX`.
+ *
+ * The `eventBodyId` segment is matched with greedy `(.+)` β€” not `[^/]+` β€”
+ * because the bucket holds two shapes side by side: older keys written
+ * verbatim from the SDK-supplied id (where `idSchema` permits `/`), and
+ * newer keys whose segment has been sanitized via `safeBlobKeySegment`.
+ * Whatever form the segment takes, callers must treat the parsed
+ * `eventBodyId` as an opaque canonical S3-side string and NOT re-sanitize it.
+ */
+export const STANDARD_EVENT_KEY_REGEX =
+ /^([^/]+)\/([^/]+)\/(.+)\/([^/]+)\.json$/;
+
+/**
+ * OTel event-upload key: `otel/<projectId>/<yyyy>/<mm>/<dd>/<hh>/<mm>/<eventId>.json`.
+ */
+export const OTEL_EVENT_KEY_REGEX =
+ /^otel\/([^/]+)\/(\d{4})\/(\d{2})\/(\d{2})\/(\d{2})\/(\d{2})\/([^.]+)\.json$/;
+
+export type ParsedEventKey =
+ | {
+ kind: "standard";
+ projectId: string;
+ entityType: string;
+ eventBodyId: string;
+ eventId: string;
+ }
+ | { kind: "otel"; projectId: string };
+
+/**
+ * Parses an S3 event-upload key (relative to `LANGFUSE_S3_EVENT_UPLOAD_PREFIX`)
+ * into its structured form. Returns `null` if the key matches neither shape.
+ *
+ * Used by the admin replay endpoint and the operator replay script.
+ *
+ * The returned `eventBodyId` is the literal segment as it sits in S3 β€”
+ * whatever form the original producer wrote (raw, sanitized + hashed, or any
+ * future shape). Feed it to `rawEventBucketPrefix` to reconstruct the prefix
+ * verbatim; do NOT pass it through `safeBlobKeySegment` /
+ * `buildEventBucketPrefix`, which would remap it to a different S3 path than
+ * the one this caller observed.
+ *
+ * `entityType` is returned as a raw string and is NOT validated against
+ * `IngestionEntityTypes` here β€” callers that route by entity type (queue
+ * choice, event-type mapping) MUST validate before trusting it.
+ */
+export function parseEventKey(key: string): ParsedEventKey | null {
+ const otel = key.match(OTEL_EVENT_KEY_REGEX);
+ if (otel) {
+ return { kind: "otel", projectId: otel[1]! };
+ }
+ const standard = key.match(STANDARD_EVENT_KEY_REGEX);
+ if (standard) {
+ const [, projectId, entityType, eventBodyId, eventId] = standard;
+ return {
+ kind: "standard",
+ projectId: projectId!,
+ entityType: entityType!,
+ eventBodyId: eventBodyId!,
+ eventId: eventId!,
+ };
+ }
+ return null;
+}
+
+/**
+ * Builds the S3 key prefix (ending in "/") under which all event files for a
+ * given entity ID are stored. Sanitizes the id segment via `safeBlobKeySegment`
+ * so the resulting key is always a valid S3/MinIO path regardless of length
+ * or character set.
+ *
+ * Use this when the caller has the ORIGINAL entity ID β€” e.g. the producer at
+ * write time, populating `bucketPrefix` on the IngestionQueue payload, or the
+ * `clickhouse.ts` upsert path turning a record id into a path. Centralizing
+ * the formula here is what makes producer/consumer drift structurally
+ * impossible: every producer that writes an event file goes through this
+ * exact function.
+ *
+ * When the caller already holds the literal S3-side segment β€” e.g. parsed
+ * out of an existing key via `parseEventKey` β€” use `rawEventBucketPrefix`
+ * instead, so we don't re-sanitize a segment that's already canonical.
+ */
+export function buildEventBucketPrefix(params: {
+ projectId: string;
+ entityType: IngestionEntityTypes;
+ entityId: string;
+}): string {
+ return `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${params.projectId}/${params.entityType}/${safeBlobKeySegment(params.entityId)}/`;
+}
+
+/**
+ * Builds the S3 key prefix (ending in "/") from a path segment that is
+ * ALREADY canonical β€” taken verbatim from an existing S3 key (typically via
+ * `parseEventKey`). Does NOT call `safeBlobKeySegment`: the segment is what
+ * S3 has, and any rewrite would point at the wrong file.
+ *
+ * Works for ANY segment shape: sanitized + hashed (newer producers), raw
+ * SDK-supplied id (older producers), or whatever future producers emit. The
+ * point isn't legacy compatibility β€” it's that the caller has already
+ * observed the literal S3-side string and we must reproduce it byte-for-byte.
+ *
+ * Use this from replay-style call sites that consume `parseEventKey` output
+ * (admin replay endpoint, operator replay script, rolling-deploy consumer
+ * fallback). For fresh writes from a user-supplied entity ID where the path
+ * still needs to be constructed, use `buildEventBucketPrefix`.
+ */
+export function rawEventBucketPrefix(params: {
+ projectId: string;
+ entityType: string;
+ rawEntityIdSegment: string;
+}): string {
+ return `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${params.projectId}/${params.entityType}/${params.rawEntityIdSegment}/`;
+}
diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.ts
index 25efe70fb9..69e8914073 100644
--- a/packages/shared/src/server/ingestion/processEventBatch.ts
+++ b/packages/shared/src/server/ingestion/processEventBatch.ts
@@ -8,7 +8,10 @@ import {
UnauthorizedError,
} from "../../errors";
import { AuthHeaderValidVerificationResultIngestion } from "../auth/types";
-import { getClickhouseEntityType } from "../clickhouse/schemaUtils";
+import {
+ getClickhouseEntityType,
+ type IngestionEntityTypes,
+} from "../clickhouse/schemaUtils";
import {
getCurrentSpan,
instrumentAsync,
@@ -28,6 +31,12 @@ import {
StorageService,
StorageServiceFactory,
} from "../services/StorageService";
+import {
+ HASH_HEX_LENGTH,
+ safeBlobFilenameStem,
+ safeBlobKeySegment,
+} from "../services/safeBlobKeySegment";
+import { buildEventBucketPrefix } from "./eventBucketPath";
import { isTraceIdInSample } from "./sampling";
import {
isS3SlowDownError,
@@ -188,6 +197,18 @@ export const processEventBatch = async (
// We group events by eventBodyId which allows us to store and process them
// as one which reduces infra interactions per event. Only used in the S3 case.
+ //
+ // The dedup struct also caches `entityType` and `bucketPrefix` so the two
+ // downstream loops (S3 upload + IngestionQueue enqueue) read a single
+ // source-of-truth per id instead of recomputing β€” that makes the
+ // producer/consumer-must-agree invariant structural. The sanitization warn
+ // log fires once at the time we resolve the prefix.
+ //
+ // `String(...)` preserves the prior null β†’ "null" coercion of
+ // `authCheck.scope.projectId`. The surrounding function legitimately treats
+ // projectId as nullable elsewhere (metric labels, span attributes); we
+ // don't narrow it in the type system, and a `null` projectId would land
+ // events under an isolated `null/...` path rather than throw.
const sortedBatchByEventBodyId = sortedBatch.reduce(
(
acc: Record<
@@ -197,6 +218,8 @@ export const processEventBatch = async (
key: string;
eventBodyId: string;
type: (typeof eventTypes)[keyof typeof eventTypes];
+ entityType: IngestionEntityTypes;
+ bucketPrefix: string;
}
>,
event,
@@ -204,16 +227,41 @@ export const processEventBatch = async (
if (!event.body?.id) {
return acc;
}
- const key = `${getClickhouseEntityType(event.type)}-${event.body.id}`;
- if (!acc[key]) {
- acc[key] = {
+ const entityType = getClickhouseEntityType(event.type);
+ const dedupKey = `${entityType}-${event.body.id}`;
+ if (!acc[dedupKey]) {
+ const eventBodyId = event.body.id;
+ const safeEventBodyId = safeBlobKeySegment(eventBodyId);
+ if (safeEventBodyId !== eventBodyId) {
+ // Do not log the raw or sanitized ID itself: the prefix can carry
+ // PII (litellm encodes provider/model/request metadata in the ID).
+ // The 16-hex hash is enough to correlate with the stored object
+ // during debugging.
+ logger.warn("Sanitized oversized/invalid entity ID for S3 key", {
+ projectId: authCheck.scope.projectId,
+ entityType,
+ originalIdByteLength: Buffer.byteLength(eventBodyId, "utf8"),
+ originalIdHash16: safeEventBodyId.slice(-HASH_HEX_LENGTH),
+ });
+ }
+ acc[dedupKey] = {
data: [],
- key: event.id,
+ // `event.id` becomes a single-segment filename (`<id>.json`) at S3
+ // write time and rides the queue payload as `fileKey`. Sanitize
+ // here so `/`, `\`, control bytes, and over-budget lengths can't
+ // reroute the write or overflow NAME_MAX.
+ key: safeBlobFilenameStem(event.id, ".json"),
type: event.type,
- eventBodyId: event.body.id,
+ eventBodyId,
+ entityType,
+ bucketPrefix: buildEventBucketPrefix({
+ projectId: String(authCheck.scope.projectId),
+ entityType,
+ entityId: eventBodyId,
+ }),
};
}
- acc[key].data.push(event);
+ acc[dedupKey].data.push(event);
return acc;
},
{},
@@ -232,8 +280,8 @@ export const processEventBatch = async (
// We upload the event in an array to the S3 bucket grouped by the eventBodyId.
// That way we batch updates from the same invocation into a single file and reduce
// write operations on S3.
- const { data, key, type, eventBodyId } = sortedBatchByEventBodyId[id];
- const bucketPath = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${authCheck.scope.projectId}/${getClickhouseEntityType(type)}/${eventBodyId}/${key}.json`;
+ const { data, key, bucketPrefix } = sortedBatchByEventBodyId[id];
+ const bucketPath = `${bucketPrefix}${key}.json`;
return getS3StorageServiceClient(
env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
).uploadJson(bucketPath, data);
@@ -283,10 +331,8 @@ export const processEventBatch = async (
const shardingKey = `${authCheck.scope.projectId}-${eventData.eventBodyId}`;
const queue = IngestionQueue.getInstance({ shardingKey });
- const isDatasetRunItemEvent =
- getClickhouseEntityType(eventData.type) === "dataset_run_item";
- const isObservationEvent =
- getClickhouseEntityType(eventData.type) === "observation";
+ const isDatasetRunItemEvent = eventData.entityType === "dataset_run_item";
+ const isObservationEvent = eventData.entityType === "observation";
const isOtelOrSkipS3Project =
authCheck.scope.projectId !== null &&
@@ -331,6 +377,7 @@ export const processEventBatch = async (
fileKey: eventData.key,
skipS3List: shouldSkipS3List,
forwardToEventsTable,
+ bucketPrefix: eventData.bucketPrefix,
},
authCheck: authCheck as {
validKey: true;
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index b43af3736e..4785c05f3f 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -25,6 +25,12 @@ export const IngestionEvent = z.object({
fileKey: z.string().optional(),
skipS3List: z.boolean().optional(),
forwardToEventsTable: z.boolean().optional(),
+ // Absolute S3 key prefix the producer used (ends with "/"). Set so the
+ // consumer never reconstructs the path and therefore can't drift from
+ // the producer when env values differ across containers. Optional for
+ // backward compatibility with in-flight jobs enqueued before this field
+ // existed β€” the consumer falls back to local reconstruction when absent.
+ bucketPrefix: z.string().optional(),
}),
authCheck: z.object({
validKey: z.literal(true),
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.ts
index b348f96795..01f13f4f7f 100644
--- a/packages/shared/src/server/repositories/clickhouse.ts
+++ b/packages/shared/src/server/repositories/clickhouse.ts
@@ -15,6 +15,7 @@ import {
StorageService,
StorageServiceFactory,
} from "../services/StorageService";
+import { buildEventBucketPrefix } from "../ingestion/eventBucketPath";
import {
ClickHouseSettings,
type RowOrProgress,
@@ -152,7 +153,12 @@ export async function upsertClickhouse<
}
const eventId = randomUUID();
- const bucketPath = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${record.project_id}/${getClickhouseEntityType(eventType)}/${record.id}/${eventId}.json`;
+ const entityType = getClickhouseEntityType(eventType);
+ const bucketPath = `${buildEventBucketPrefix({
+ projectId: String(record.project_id),
+ entityType,
+ entityId: String(record.id),
+ })}${eventId}.json`;
if (env.LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG === "true") {
// Write new file directly to ClickHouse. We don't use the ClickHouse writer here as we expect more limited traffic
@@ -163,7 +169,7 @@ export async function upsertClickhouse<
{
id: randomUUID(),
project_id: record.project_id,
- entity_type: getClickhouseEntityType(eventType),
+ entity_type: entityType,
entity_id: record.id,
event_id: eventId,
bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
diff --git a/packages/shared/src/server/services/safeBlobKeySegment.ts b/packages/shared/src/server/services/safeBlobKeySegment.ts
new file mode 100644
index 0000000000..b8eed7cb43
--- /dev/null
+++ b/packages/shared/src/server/services/safeBlobKeySegment.ts
@@ -0,0 +1,83 @@
+import { createHash } from "crypto";
+
+import { env } from "../../env";
+
+export const HASH_HEX_LENGTH = 16;
+const HASH_SUFFIX_OVERHEAD = HASH_HEX_LENGTH + 1; // hex chars + leading "_"
+
+// Characters that must not appear in a single S3 key path segment: "/" and
+// "\" break path semantics; NUL and other ASCII control chars are rejected by
+// S3/MinIO.
+// eslint-disable-next-line no-control-regex
+const FORBIDDEN_CHAR = /[\x00-\x1f/\\]/;
+// eslint-disable-next-line no-control-regex
+const FORBIDDEN_CHAR_GLOBAL = /[\x00-\x1f/\\]/g;
+
+function sliceUtf8Bytes(input: string, maxBytes: number): string {
+ const buf = Buffer.from(input, "utf8");
+ if (buf.length <= maxBytes) return input;
+ // Walk back from maxBytes to the last UTF-8 codepoint boundary so we never
+ // truncate inside a multi-byte sequence.
+ let end = maxBytes;
+ // skip continuation bytes (0x80–0xBF)
+ while (end > 0 && (buf[end] & 0xc0) === 0x80) end--;
+ return buf.subarray(0, end).toString("utf8");
+}
+
+/**
+ * Returns a path segment that is safe to use as one component of an S3 object
+ * key built from a user-controlled entity ID (observation/trace/score id).
+ *
+ * Guarantees:
+ * - Result is ≀ `maxBytes` UTF-8 bytes.
+ * - Result contains no `/`, `\`, NUL, or other ASCII control characters.
+ * - For inputs already within budget and free of forbidden chars, the
+ * output is byte-identical to the input (no-op fast path β€” keeps
+ * pre-existing S3 keys readable after upgrade).
+ * - For oversized or sanitized inputs, the result is deterministic: the
+ * same `segment` always produces the same output for the same `maxBytes`.
+ * - Distinct inputs map to distinct outputs whenever sanitization fires,
+ * because the appended sha256 prefix is computed over the original bytes
+ * (not the post-replacement string).
+ *
+ * Producers and consumers MUST resolve `maxBytes` from the same source
+ * (`env.LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES` in production).
+ */
+export function safeBlobKeySegment(
+ segment: string,
+ maxBytes: number = env.LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES,
+): string {
+ const overBudget = Buffer.byteLength(segment, "utf8") > maxBytes;
+ const hasForbidden = FORBIDDEN_CHAR.test(segment);
+ if (!overBudget && !hasForbidden) return segment;
+
+ // Any sanitization at all β†’ append a hash suffix derived from the original
+ // bytes. This keeps the mapping injective: two segments that differ only
+ // in forbidden characters (e.g. "a/b" vs "a_b") receive different hashes
+ // and therefore different outputs.
+ const sanitized = segment.replace(FORBIDDEN_CHAR_GLOBAL, "_");
+ const prefixBudget = Math.max(0, maxBytes - HASH_SUFFIX_OVERHEAD);
+ const prefix = sliceUtf8Bytes(sanitized, prefixBudget);
+ const hash = createHash("sha256")
+ .update(segment, "utf8")
+ .digest("hex")
+ .slice(0, HASH_HEX_LENGTH);
+ return `${prefix}_${hash}`;
+}
+
+/**
+ * Sanitize a stem so that `<stem><filenameSuffix>` fits inside
+ * `LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES`. Caller appends the suffix.
+ *
+ * Use when an entity id has to become a single-segment filename
+ * (`<id>.json`), where the suffix steals budget away from the stem.
+ */
+export function safeBlobFilenameStem(
+ stem: string,
+ filenameSuffix: string,
+): string {
+ return safeBlobKeySegment(
+ stem,
+ env.LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES - filenameSuffix.length,
+ );
+}
diff --git a/web/src/__tests__/server/unit/blobStorageKey.servertest.ts b/web/src/__tests__/server/unit/blobStorageKey.servertest.ts
new file mode 100644
index 0000000000..8fb4186443
--- /dev/null
+++ b/web/src/__tests__/server/unit/blobStorageKey.servertest.ts
@@ -0,0 +1,287 @@
+import { createHash } from "crypto";
+import { describe, it, expect } from "vitest";
+
+import {
+ buildEventBucketPrefix,
+ parseEventKey,
+ safeBlobFilenameStem,
+ safeBlobKeySegment,
+} from "@langfuse/shared/src/server";
+
+const HEX16 = /^[0-9a-f]{16}$/;
+
+const byteLen = (s: string) => Buffer.byteLength(s, "utf8");
+
+describe("safeBlobKeySegment", () => {
+ const N = 255;
+
+ it("returns short ASCII IDs unchanged (no-op fast path)", () => {
+ for (const s of ["a", "obs_123", "x".repeat(64), "x".repeat(200)]) {
+ expect(safeBlobKeySegment(s, N)).toBe(s);
+ }
+ });
+
+ it("returns IDs at exactly the budget unchanged", () => {
+ const s = "a".repeat(N);
+ expect(safeBlobKeySegment(s, N)).toBe(s);
+ });
+
+ it("hashes IDs that exceed the budget, fits within the budget", () => {
+ const s = "a".repeat(N + 1);
+ const out = safeBlobKeySegment(s, N);
+ expect(byteLen(out)).toBeLessThanOrEqual(N);
+ expect(byteLen(out)).toBe(N); // prefix takes all remaining budget
+ const suffix = out.slice(-16);
+ expect(suffix).toMatch(HEX16);
+ expect(out[out.length - 17]).toBe("_");
+ });
+
+ it("hashes the litellm-style 262-byte case", () => {
+ const s =
+ "time-16-23-03-560977_resp_" +
+ "bGl0ZWxsbTpjdXN0b21fbGxtX3Byb3ZpZGVyOm9wZW5haTttb2RlbF9pZDo" +
+ "x".repeat(262 - "time-16-23-03-560977_resp_".length - 60);
+ expect(byteLen(s)).toBeGreaterThan(N);
+ const out = safeBlobKeySegment(s, N);
+ expect(byteLen(out)).toBeLessThanOrEqual(N);
+ expect(out.slice(-16)).toMatch(HEX16);
+ });
+
+ it("is deterministic across calls", () => {
+ const s = "x".repeat(800);
+ expect(safeBlobKeySegment(s, N)).toBe(safeBlobKeySegment(s, N));
+ });
+
+ it("distinguishes inputs that share a long common prefix", () => {
+ const shared = "x".repeat(250);
+ const a = shared + "AAAAAAAAAAAAAAAAAAAA";
+ const b = shared + "BBBBBBBBBBBBBBBBBBBB";
+ expect(safeBlobKeySegment(a, N)).not.toBe(safeBlobKeySegment(b, N));
+ });
+
+ it("opts out of length hashing at high maxBytes (pure-S3 deployment)", () => {
+ const s = "x".repeat(262);
+ expect(safeBlobKeySegment(s, 800)).toBe(s);
+ });
+
+ it("still sanitizes forbidden characters at high maxBytes", () => {
+ const s = "abc/def\\ghi";
+ const out = safeBlobKeySegment(s, 800);
+ expect(out).not.toBe(s);
+ expect(out).not.toMatch(/[/\\]/);
+ // Forbidden-char sanitization always hashes to preserve injectivity.
+ expect(out.slice(-16)).toMatch(HEX16);
+ expect(out.startsWith("abc_def_ghi_")).toBe(true);
+ });
+
+ it("maps forbidden-char-only inputs to distinct outputs", () => {
+ const a = "a/b";
+ const b = "a_b";
+ expect(safeBlobKeySegment(a, N)).not.toBe(safeBlobKeySegment(b, N));
+ });
+
+ it("replaces NUL and other ASCII control characters", () => {
+ const s = "x\x00y\x01z\x1fw";
+ const out = safeBlobKeySegment(s, N);
+ expect(out).not.toMatch(/[\x00-\x1f]/);
+ expect(out.startsWith("x_y_z_w_")).toBe(true);
+ });
+
+ it("truncates on UTF-8 byte boundaries (no torn codepoints)", () => {
+ // 100 codepoints Γ— 3 bytes each = 300 bytes
+ const s = "あ".repeat(100);
+ expect(byteLen(s)).toBe(300);
+ const out = safeBlobKeySegment(s, N);
+ expect(byteLen(out)).toBeLessThanOrEqual(N);
+ // Result must be valid UTF-8: round-tripping through Buffer preserves it.
+ expect(Buffer.from(out, "utf8").toString("utf8")).toBe(out);
+ expect(out.slice(-16)).toMatch(HEX16);
+ });
+
+ it("preserves UTF-8 boundaries when the prefix budget lands mid-codepoint", () => {
+ // 86 Γ— 3 = 258 bytes β€” overshoots N=255, so we hash.
+ // prefixBudget = N - 17 = 238 bytes. 238 / 3 = 79 r 1, so byte 238 is a
+ // continuation byte; the walk-back must drop to 237 (= 79 complete
+ // 3-byte codepoints) to avoid tearing a codepoint.
+ const s = "あ".repeat(86);
+ expect(byteLen(s)).toBe(258);
+ const out = safeBlobKeySegment(s, N);
+ expect(byteLen(out)).toBe(79 * 3 + 1 + 16); // 254
+ expect(byteLen(out)).toBeLessThan(N);
+ expect(Buffer.from(out, "utf8").toString("utf8")).toBe(out);
+ expect(out.slice(-16)).toMatch(HEX16);
+ });
+
+ it("preserves a trailing extension when the caller reserves room", () => {
+ // Mirrors the eval-scheduler path: sanitize the bare ID with a reduced
+ // budget, then append ".json". Final filename must still fit N bytes.
+ const SUFFIX = ".json";
+ const id = "x".repeat(400);
+ const safe = safeBlobKeySegment(id, N - SUFFIX.length);
+ const filename = `${safe}${SUFFIX}`;
+ expect(byteLen(filename)).toBeLessThanOrEqual(N);
+ expect(filename.endsWith(SUFFIX)).toBe(true);
+ // Hash suffix sits before the extension, not at the end of the filename.
+ expect(safe.slice(-16)).toMatch(HEX16);
+ });
+});
+
+describe("safeBlobFilenameStem", () => {
+ // Pins both producer call sites that build `<id>.json` filenames:
+ // processEventBatch.ts (event.id β†’ file key) and createSchedulerDeps.ts
+ // (observationId β†’ eval snapshot). If either site regresses to raw
+ // interpolation, the assertions below fail.
+
+ it("sanitizes forbidden chars so the stem can never reroute the filename", () => {
+ // event.id = "a/b/c" would otherwise nest the file four levels deeper
+ // than the directory listFiles will scan, and would misparse on replay
+ // (the standard-key regex's filename group is `([^/]+)\.json$`).
+ const stem = safeBlobFilenameStem("a/b/c", ".json");
+ expect(stem).not.toMatch(/[/\\]/);
+ expect(stem.slice(-16)).toMatch(HEX16);
+ expect(stem.startsWith("a_b_c_")).toBe(true);
+ });
+
+ it("budgets the suffix so the final filename fits the env default", () => {
+ // Default LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES is 2048; the stem
+ // helper reserves the suffix length, so `<stem>.json` must be ≀ 2048.
+ const DEFAULT_BUDGET = 2048;
+ const stem = safeBlobFilenameStem(
+ "x".repeat(DEFAULT_BUDGET + 200),
+ ".json",
+ );
+ const filename = `${stem}.json`;
+ expect(byteLen(filename)).toBeLessThanOrEqual(DEFAULT_BUDGET);
+ expect(stem.slice(-16)).toMatch(HEX16);
+ });
+
+ it("is a no-op for safe short IDs (no hash suffix, no replacement)", () => {
+ const stem = safeBlobFilenameStem("event-12345", ".json");
+ expect(stem).toBe("event-12345");
+ });
+});
+
+describe("buildEventBucketPrefix", () => {
+ const projectId = "proj-abc";
+ const entityType = "observation" as const;
+ // `.env.test` pins LANGFUSE_S3_EVENT_UPLOAD_PREFIX to "events/"; reading
+ // it here gives the test a stable, hand-checkable expected value without
+ // going through the same `env` module the helper uses.
+ const envPrefix = process.env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX ?? "";
+
+ it("composes <envPrefix><projectId>/<entityType>/<id>/ for short IDs", () => {
+ // Hand-built constant β€” does not call `safeBlobKeySegment` so a future
+ // change in the fast-path return value would surface here.
+ const id = "obs-12345";
+ expect(
+ buildEventBucketPrefix({ projectId, entityType, entityId: id }),
+ ).toBe(`${envPrefix}${projectId}/${entityType}/${id}/`);
+ });
+
+ it("composes the prefix from sha256-truncated id for oversized inputs", () => {
+ // Pins the full layout β€” env, projectId, entityType, sanitized middle
+ // segment, trailing slash β€” against a value built without calling
+ // `safeBlobKeySegment`. We compute the sha256 prefix directly so a
+ // future change in hash algorithm, truncation length, separator, or
+ // budget arithmetic in `safeBlobKeySegment` fails this test rather
+ // than passing silently along with a synchronized "expected" copy.
+ //
+ // Budget tracks the `LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES` default in
+ // `packages/shared/src/env.ts`. If the default changes intentionally,
+ // update this constant β€” the failure is the early-warning system.
+ const DEFAULT_BUDGET = 2048;
+ const id = "x".repeat(DEFAULT_BUDGET + 200); // > default budget
+ const PREFIX_BUDGET = DEFAULT_BUDGET - 17; // budget - len("_<16 hex>")
+ const expectedMiddle =
+ "x".repeat(PREFIX_BUDGET) +
+ "_" +
+ createHash("sha256").update(id, "utf8").digest("hex").slice(0, 16);
+ expect(
+ buildEventBucketPrefix({ projectId, entityType, entityId: id }),
+ ).toBe(`${envPrefix}${projectId}/${entityType}/${expectedMiddle}/`);
+ });
+
+ it("is deterministic", () => {
+ const id = "obs-deterministic";
+ const a = buildEventBucketPrefix({ projectId, entityType, entityId: id });
+ const b = buildEventBucketPrefix({ projectId, entityType, entityId: id });
+ expect(a).toBe(b);
+ });
+});
+
+describe("parseEventKey", () => {
+ it("parses a standard event key into structured pieces", () => {
+ const parsed = parseEventKey("proj-1/observation/obs-123/abc-def.json");
+ expect(parsed).toEqual({
+ kind: "standard",
+ projectId: "proj-1",
+ entityType: "observation",
+ eventBodyId: "obs-123",
+ eventId: "abc-def",
+ });
+ });
+
+ it("accepts legacy unsanitized eventBodyId containing /", () => {
+ const parsed = parseEventKey("proj-1/score/a/b/c/event-x.json");
+ expect(parsed).toEqual({
+ kind: "standard",
+ projectId: "proj-1",
+ entityType: "score",
+ eventBodyId: "a/b/c",
+ eventId: "event-x",
+ });
+ });
+
+ it("parses an otel key and exposes the projectId only", () => {
+ const parsed = parseEventKey("otel/proj-1/2026/05/13/12/30/evt-9.json");
+ expect(parsed).toEqual({ kind: "otel", projectId: "proj-1" });
+ });
+
+ it("returns null for unrecognized shapes", () => {
+ expect(parseEventKey("not-a-key")).toBeNull();
+ expect(parseEventKey("proj-1/obs/123.json")).toBeNull();
+ expect(parseEventKey("")).toBeNull();
+ });
+});
+
+describe("buildEventBucketPrefix / parseEventKey round-trip", () => {
+ // Pins the parse/build co-evolution: any key the helper produces must
+ // parse back via parseEventKey into the original components. This is
+ // the single test that catches a future regex change that desyncs from
+ // the helper template (or vice versa).
+ const envPrefix = process.env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX ?? "";
+ const projectId = "proj-rt";
+ const entityType = "score" as const;
+ const eventId = "event-rt";
+
+ const cases: { name: string; entityId: string }[] = [
+ { name: "short ID (no-op fast path)", entityId: "obs-short" },
+ // Must exceed the default `LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES`
+ // (2048) so the helper actually exercises the hash-suffix path; a
+ // smaller value would hit the no-op fast path and stop testing the
+ // sanitized-middle branch.
+ { name: "oversized ID (sanitized middle)", entityId: "x".repeat(2200) },
+ ];
+
+ for (const { name, entityId } of cases) {
+ it(`round-trips ${name}`, () => {
+ const prefix = buildEventBucketPrefix({
+ projectId,
+ entityType,
+ entityId,
+ });
+ const fullKey = `${prefix}${eventId}.json`;
+ // parseEventKey expects keys relative to LANGFUSE_S3_EVENT_UPLOAD_PREFIX.
+ const relativeKey = fullKey.startsWith(envPrefix)
+ ? fullKey.slice(envPrefix.length)
+ : fullKey;
+ expect(parseEventKey(relativeKey)).toEqual({
+ kind: "standard",
+ projectId,
+ entityType,
+ eventBodyId: safeBlobKeySegment(entityId),
+ eventId,
+ });
+ });
+ }
+});
diff --git a/web/src/pages/api/admin/ingestion-replay.ts b/web/src/pages/api/admin/ingestion-replay.ts
index 8a46e6682b..bdcef76c7d 100644
--- a/web/src/pages/api/admin/ingestion-replay.ts
+++ b/web/src/pages/api/admin/ingestion-replay.ts
@@ -4,7 +4,9 @@ import { randomUUID } from "crypto";
import {
eventTypes,
logger,
+ parseEventKey,
QueueJobs,
+ rawEventBucketPrefix,
SecondaryIngestionQueue,
OtelIngestionQueue,
} from "@langfuse/shared/src/server";
@@ -15,10 +17,6 @@ const IngestionReplayBody = z.object({
keys: z.array(z.string()).min(1).max(1000),
});
-const OTEL_KEY_REGEX =
- /^otel\/([^/]+)\/(\d{4})\/(\d{2})\/(\d{2})\/(\d{2})\/(\d{2})\/([^.]+)\.json$/;
-const STANDARD_KEY_REGEX = /^([^/]+)\/([^/]+)\/(.+)\/([^/]+)\.json$/;
-
type StandardReplayJob = TQueueJobTypes[QueueName.IngestionSecondaryQueue];
type OtelReplayJob = TQueueJobTypes[QueueName.OtelIngestionQueue];
@@ -143,9 +141,8 @@ export default async function handler(
const errors: string[] = [];
for (const key of body.data.keys) {
- const otelMatch = key.match(OTEL_KEY_REGEX);
- if (otelMatch) {
- const [, projectId] = otelMatch;
+ const parsed = parseEventKey(key);
+ if (parsed?.kind === "otel") {
otelJobs.push({
timestamp: new Date(),
id: randomUUID(),
@@ -153,7 +150,7 @@ export default async function handler(
data: { fileKey: key },
authCheck: {
validKey: true,
- scope: { projectId: projectId!, accessLevel: "project" },
+ scope: { projectId: parsed.projectId, accessLevel: "project" },
},
},
name: QueueJobs.OtelIngestionJob,
@@ -161,29 +158,40 @@ export default async function handler(
continue;
}
- const standardMatch = key.match(STANDARD_KEY_REGEX);
- if (standardMatch) {
- const [, projectId, type, eventBodyId, eventId] = standardMatch;
- const replayEventType = getStandardReplayEventType(type!);
+ if (parsed?.kind === "standard") {
+ const { projectId, entityType, eventBodyId, eventId } = parsed;
+ const replayEventType = getStandardReplayEventType(entityType);
if (!replayEventType) {
skipped++;
- errors.push(`Unsupported replay type: ${type}`);
+ errors.push(`Unsupported replay type: ${entityType}`);
continue;
}
+ // The parsed eventBodyId is the literal segment as it sits in S3 β€”
+ // could be sanitized + hashed (newer producer), raw SDK id (older
+ // producer), or any future shape. Pass it through verbatim via
+ // rawEventBucketPrefix so the worker reads from the same key the
+ // original write produced, regardless of which producer wrote it.
+ const bucketPrefix = rawEventBucketPrefix({
+ projectId,
+ entityType,
+ rawEntityIdSegment: eventBodyId,
+ });
+
standardJobs.push({
timestamp: new Date(),
id: randomUUID(),
payload: {
data: {
type: replayEventType,
- eventBodyId: eventBodyId!,
- fileKey: eventId!,
+ eventBodyId,
+ fileKey: eventId,
+ bucketPrefix,
},
authCheck: {
validKey: true,
- scope: { projectId: projectId! },
+ scope: { projectId },
},
},
name: QueueJobs.IngestionJob,
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 1c7577446e..68fce0a654 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -1,4 +1,5 @@
import { removeEmptyEnvVariables } from "@langfuse/shared";
+import { langfuseS3EventKeyMaxSegmentBytesSchema } from "@langfuse/shared/src/env";
import { z } from "zod";
const EnvSchema = z.object({
@@ -51,6 +52,12 @@ const EnvSchema = z.object({
.default("false"),
LANGFUSE_S3_EVENT_UPLOAD_SSE: z.enum(["AES256", "aws:kms"]).optional(),
LANGFUSE_S3_EVENT_UPLOAD_SSE_KMS_KEY_ID: z.string().optional(),
+ // Validation rules live in `@langfuse/shared/src/env` so producer and
+ // consumer agree on what values are accepted. Must match the web container's
+ // resolved value at deploy time; otherwise web and worker can write/read
+ // different S3 keys for the same id.
+ LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES:
+ langfuseS3EventKeyMaxSegmentBytesSchema,
BATCH_EXPORT_PAGE_SIZE: z.coerce.number().positive().default(500),
BATCH_EXPORT_ROW_LIMIT: z.coerce.number().positive().default(1_500_000),
diff --git a/worker/src/features/evaluation/evalExecutionDeps.ts b/worker/src/features/evaluation/evalExecutionDeps.ts
index 55db56ef26..982bcd0ee1 100644
--- a/worker/src/features/evaluation/evalExecutionDeps.ts
+++ b/worker/src/features/evaluation/evalExecutionDeps.ts
@@ -2,6 +2,7 @@ import { randomUUID } from "crypto";
import { JobExecutionStatus } from "@prisma/client";
import { prisma } from "@langfuse/shared/src/db";
import {
+ buildEventBucketPrefix,
DefaultEvalModelService,
fetchLLMCompletion,
IngestionQueue,
@@ -9,7 +10,6 @@ import {
QueueJobs,
ScoreEventType,
} from "@langfuse/shared/src/server";
-import { env } from "../../env";
import { buildEvalMessages } from "./evalRuntime";
import { getEvalS3StorageClient } from "./s3StorageClient";
import { createInternalEventsWriter } from "../internal-tracing/createInternalEventsWriter";
@@ -144,7 +144,12 @@ export function createProductionEvalExecutionDeps(): EvalExecutionDeps {
},
uploadScore: async (params) => {
- const bucketPath = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${params.projectId}/score/${params.scoreId}/${params.eventId}.json`;
+ const bucketPrefix = buildEventBucketPrefix({
+ projectId: params.projectId,
+ entityType: "score",
+ entityId: params.scoreId,
+ });
+ const bucketPath = `${bucketPrefix}${params.eventId}.json`;
await getEvalS3StorageClient().uploadJson(bucketPath, [
params.event as unknown as Record<string, unknown>,
@@ -158,6 +163,12 @@ export function createProductionEvalExecutionDeps(): EvalExecutionDeps {
throw new Error("Ingestion queue not available");
}
+ const bucketPrefix = buildEventBucketPrefix({
+ projectId: params.projectId,
+ entityType: "score",
+ entityId: params.scoreId,
+ });
+
await queue.add(QueueJobs.IngestionJob, {
id: randomUUID(),
timestamp: new Date(),
@@ -167,6 +178,7 @@ export function createProductionEvalExecutionDeps(): EvalExecutionDeps {
type: "score-create",
eventBodyId: params.scoreId,
fileKey: params.eventId,
+ bucketPrefix,
},
authCheck: {
validKey: true,
diff --git a/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts b/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts
index a705eb2593..46dcde4017 100644
--- a/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts
+++ b/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts
@@ -4,6 +4,8 @@ import {
LLMAsJudgeExecutionQueue,
QueueJobs,
QueueName,
+ safeBlobFilenameStem,
+ safeBlobKeySegment,
} from "@langfuse/shared/src/server";
import { env } from "../../../env";
import { getEvalS3StorageClient } from "../s3StorageClient";
@@ -50,7 +52,16 @@ export function createObservationEvalSchedulerDeps(): ObservationEvalSchedulerDe
},
uploadObservationToS3: async (params) => {
- const path = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}evals/${params.projectId}/traces/${params.traceId}/observations/${params.observationId}.json`;
+ // traceId is a directory segment; observationId is a filename stem
+ // (`.json` reserved out of the budget). Both come from user-supplied
+ // ids and must be sanitized so the resulting key never overflows
+ // NAME_MAX or contains path-breaking characters.
+ const safeTraceId = safeBlobKeySegment(params.traceId);
+ const safeObservationId = safeBlobFilenameStem(
+ params.observationId,
+ ".json",
+ );
+ const path = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}evals/${params.projectId}/traces/${safeTraceId}/observations/${safeObservationId}.json`;
const s3Client = getEvalS3StorageClient();
await s3Client.uploadJson(path, params.data);
diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.ts
index 0ecd962d69..a31c0437ab 100644
--- a/worker/src/queues/ingestionQueue.ts
+++ b/worker/src/queues/ingestionQueue.ts
@@ -10,6 +10,7 @@ import {
logger,
markProjectS3Slowdown,
QueueName,
+ rawEventBucketPrefix,
recordDistribution,
recordHistogram,
recordIncrement,
@@ -59,28 +60,27 @@ export const ingestionQueueProcessorBuilder = (
// We write the new file into the ClickHouse event log to keep track for retention and deletions
const clickhouseWriter = ClickhouseWriter.getInstance();
- if (
- env.LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG === "true" &&
- job.data.payload.data.fileKey &&
- job.data.payload.data.fileKey
- ) {
- const fileName = `${job.data.payload.data.fileKey}.json`;
- clickhouseWriter.addToQueue(TableName.BlobStorageFileLog, {
- id: randomUUID(),
- project_id: job.data.payload.authCheck.scope.projectId,
- entity_type: getClickhouseEntityType(job.data.payload.data.type),
- entity_id: job.data.payload.data.eventBodyId,
- event_id: job.data.payload.data.fileKey,
- bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
- bucket_path: `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${job.data.payload.authCheck.scope.projectId}/${getClickhouseEntityType(job.data.payload.data.type)}/${job.data.payload.data.eventBodyId}/${fileName}`,
- created_at: new Date().getTime(),
- updated_at: new Date().getTime(),
- event_ts: new Date().getTime(),
- is_deleted: 0,
+ // Prefer the producer-supplied bucket prefix so writer and reader
+ // never disagree, even if `LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES`
+ // (or other env values that feed the key) drifts between web and
+ // worker. Fall back to local reconstruction for in-flight jobs that
+ // predate the payload field (rolling deploy).
+ //
+ // The fallback uses `rawEventBucketPrefix` because the producer that
+ // enqueued without a `bucketPrefix` field is the pre- sanitization
+ // code path, which wrote S3 with verbatim `${eventBodyId}` interpolation.
+ // The queue-payload `eventBodyId` is therefore the literal S3-side segment.
+ const bucketPrefix =
+ job.data.payload.data.bucketPrefix ??
+ rawEventBucketPrefix({
+ projectId: job.data.payload.authCheck.scope.projectId,
+ entityType: getClickhouseEntityType(job.data.payload.data.type),
+ rawEntityIdSegment: job.data.payload.data.eventBodyId,
});
- }
// If fileKey was processed within the last minutes, i.e. has a match in redis, we skip processing.
+ // `eventBodyId` is the raw (un-sanitized) ID; for legacy pre-fix data
+ // it may contain "/" which is unusual but valid in a Redis key.
if (
env.LANGFUSE_ENABLE_REDIS_SEEN_EVENT_CACHE === "true" &&
redis &&
@@ -158,7 +158,7 @@ export const ingestionQueueProcessorBuilder = (
const shouldSkipS3List =
// The producer sets skipS3List to true if it's an OTel observation
job.data.payload.data.skipS3List && job.data.payload.data.fileKey;
- const s3Prefix = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${job.data.payload.authCheck.scope.projectId}/${clickhouseEntityType}/${job.data.payload.data.eventBodyId}/`;
+ const s3Prefix = bucketPrefix;
let totalS3DownloadSizeBytes = 0;
@@ -270,6 +270,38 @@ export const ingestionQueueProcessorBuilder = (
job.data.payload.data.forwardToEventsTable ??
v4WritesToEventsTable(env);
+ // Recover the canonical entity id from the downloaded event body, not
+ // from the queue payload. On replay, `payload.data.eventBodyId` is the
+ // literal S3-side segment (sanitized + hashed for any post-PR write
+ // where safeBlobKeySegment fired); using it as the ClickHouse row id
+ // would write a divergent row. `event.body.id` is the raw SDK id that
+ // the original producer stored, so it always matches normal-ingest's
+ // row id. The producer's reducer in `processEventBatch.ts` filters out
+ // events without `body.id`, so this is non-null in practice; the
+ // fallback handles any defensive edge case.
+ const canonicalEntityId =
+ events[0].body?.id ?? job.data.payload.data.eventBodyId;
+
+ if (
+ env.LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG === "true" &&
+ job.data.payload.data.fileKey
+ ) {
+ const fileName = `${job.data.payload.data.fileKey}.json`;
+ clickhouseWriter.addToQueue(TableName.BlobStorageFileLog, {
+ id: randomUUID(),
+ project_id: job.data.payload.authCheck.scope.projectId,
+ entity_type: clickhouseEntityType,
+ entity_id: canonicalEntityId,
+ event_id: job.data.payload.data.fileKey,
+ bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ bucket_path: `${bucketPrefix}${fileName}`,
+ created_at: new Date().getTime(),
+ updated_at: new Date().getTime(),
+ event_ts: new Date().getTime(),
+ is_deleted: 0,
+ });
+ }
+
await new IngestionService(
redis,
prisma,
@@ -278,7 +310,7 @@ export const ingestionQueueProcessorBuilder = (
).mergeAndWrite(
getClickhouseEntityType(events[0].type),
job.data.payload.authCheck.scope.projectId,
- job.data.payload.data.eventBodyId,
+ canonicalEntityId,
firstS3WriteTime,
events,
forwardToEventsTable,
diff --git a/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts b/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts
index 36e7f22724..e657e772cd 100644
--- a/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts
+++ b/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts
@@ -17,8 +17,10 @@ import { parse } from "csv-parse";
import { randomUUID } from "crypto";
import {
OtelIngestionQueue,
+ parseEventKey,
QueueJobs,
QueueName,
+ rawEventBucketPrefix,
SecondaryIngestionQueue,
TQueueJobTypes,
} from "@langfuse/shared/src/server";
@@ -55,6 +57,7 @@ interface JsonOutputItem {
eventBodyId: string;
fileKey: string;
type: string;
+ bucketPrefix: string;
};
}
@@ -331,26 +334,16 @@ async function convertCsvToJsonl(
}
// Handle two S3 key path formats:
- // 1. projectId/type/eventBodyId/eventId.json (original)
+ // 1. projectId/entityType/eventBodyId/eventId.json (original)
// 2. otel/projectId/yyyy/mm/dd/hh/mm/eventId.json (OTEL-style)
+ const parsed = parseEventKey(keyValue);
- // Match OTEL-style: otel/projectId/yyyy/mm/dd/hh/mm/eventId.json
- const otelMatch = keyValue.match(
- /^otel\/([^/]+)\/(\d{4})\/(\d{2})\/(\d{2})\/(\d{2})\/(\d{2})\/([^.]+)\.json$/,
- );
-
- // Match original format
- const regularMatch = keyValue.match(
- /^([^/]+)\/([^/]+)\/(.+)\/([^/]+)\.json$/,
- );
-
- if (otelMatch) {
- const [, projectId] = otelMatch;
+ if (parsed?.kind === "otel") {
const otelJsonObject: OTelJsonOutputItem = {
authCheck: {
validKey: true,
scope: {
- projectId,
+ projectId: parsed.projectId,
accessLevel: "project",
},
},
@@ -362,8 +355,18 @@ async function convertCsvToJsonl(
// Write each OTEL JSON object as a single line (JSONL format)
otelOutputStream.write(JSON.stringify(otelJsonObject) + "\n");
writtenOtelObjects++;
- } else if (regularMatch) {
- const [, projectId, type, eventBodyId, eventId] = regularMatch;
+ } else if (parsed?.kind === "standard") {
+ const { projectId, entityType, eventBodyId, eventId } = parsed;
+
+ // The parsed eventBodyId is the literal segment in S3, whatever
+ // form the original producer wrote (sanitized + hashed, or raw).
+ // rawEventBucketPrefix passes it through verbatim so replay finds
+ // the file at the same key it was originally written to.
+ const bucketPrefix = rawEventBucketPrefix({
+ projectId,
+ entityType,
+ rawEntityIdSegment: eventBodyId,
+ });
const jsonObject: JsonOutputItem = {
useS3EventStore: true,
@@ -377,7 +380,8 @@ async function convertCsvToJsonl(
data: {
eventBodyId,
fileKey: eventId,
- type: `${type}-create`,
+ type: `${entityType}-create`,
+ bucketPrefix,
},
};
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index b78bd4e3c4..790ae43969 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -148,20 +148,20 @@ export class IngestionService {
public async mergeAndWrite(
eventType: IngestionEntityTypes,
projectId: string,
- eventBodyId: string,
+ entityId: string,
createdAtTimestamp: Date,
events: IngestionEventType[],
forwardToEventsTable: boolean,
): Promise<void> {
logger.debug(
- `Merging ingestion ${eventType} event for project ${projectId} and event ${eventBodyId}`,
+ `Merging ingestion ${eventType} event for project ${projectId} and event ${entityId}`,
);
switch (eventType) {
case "trace":
return await this.processTraceEventList({
projectId,
- entityId: eventBodyId,
+ entityId,
createdAtTimestamp,
traceEventList: events as TraceEventType[],
createEventTraceRecord: forwardToEventsTable,
@@ -169,7 +169,7 @@ export class IngestionService {
case "observation":
return await this.processObservationEventList({
projectId,
- entityId: eventBodyId,
+ entityId,
createdAtTimestamp,
observationEventList: events as ObservationEvent[],
writeToStagingTables: forwardToEventsTable,
@@ -177,7 +177,7 @@ export class IngestionService {
case "score": {
return await this.processScoreEventList({
projectId,
- entityId: eventBodyId,
+ entityId,
createdAtTimestamp,
scoreEventList: events as ScoreEventType[],
});
@@ -185,7 +185,7 @@ export class IngestionService {
case "dataset_run_item": {
return await this.processDatasetRunItemEventList({
projectId,
- entityId: eventBodyId,
+ entityId,
createdAtTimestamp,
datasetRunItemEventList: events as DatasetRunItemEventType[],
});