πͺ’ 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
chore: patch backfill for otel (#10873)
Max Deichmann547c406bc5d2
diff --git a/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts b/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.tsindex 862b7952e6..09e8e2ca45 100644--- a/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts+++ b/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts@@ -15,17 +15,27 @@ import * as path from "path";import * as readline from "readline";import { parse } from "csv-parse";import { randomUUID } from "crypto";-import { getQueue, QueueJobs, QueueName } from "@langfuse/shared/src/server";+import {+ getQueue,+ OtelIngestionQueue,+ QueueJobs,+ QueueName,+ TQueueJobTypes,+} from "@langfuse/shared/src/server";const INPUT_FILE = "events.csv";const OUTPUT_FILE = "events_filtered.csv";const JSONL_OUTPUT_FILE = "events_filtered.jsonl";+const OTEL_JSONL_OUTPUT_FILE = "otel_events_filtered.jsonl";// Redis configuration// eslint-disable-next-line turbo/no-undeclared-env-varsconst QUEUE_NAME = QueueName.IngestionSecondaryQueue;const JOB_NAME = QueueJobs.IngestionJob;+const OTEL_NAME = QueueName.OtelIngestionQueue;+const OTEL_JOB_NAME = QueueJobs.OtelIngestionJob;+interface Stats {totalRows: number;filteredRows: number;@@ -48,6 +58,19 @@ interface JsonOutputItem {};}+interface OTelJsonOutputItem {+ authCheck: {+ validKey: true;+ scope: {+ projectId: string;+ accessLevel: "project";+ };+ };+ data: {+ fileKey: string;+ };+}+async function filterCsvFile(inputPath: string,outputPath: string,@@ -222,13 +245,16 @@ async function filterCsvFile(async function convertCsvToJsonl(csvPath: string,jsonlPath: string,+ otelJsonlPath: string,): Promise<void> {console.log(`π Converting ${csvPath} to JSONL format...`);console.log(`π JSONL output will be written to ${jsonlPath}`);+ console.log(`π OTEL JSONL output will be written to ${otelJsonlPath}`);const startTime = Date.now();let processedRows = 0;let writtenObjects = 0;+ let writtenOtelObjects = 0;// Check if CSV file existsif (!fs.existsSync(csvPath)) {@@ -238,6 +264,7 @@ async function convertCsvToJsonl(return new Promise<void>((resolve, reject) => {const inputStream = fs.createReadStream(csvPath);const outputStream = fs.createWriteStream(jsonlPath);+ const otelOutputStream = fs.createWriteStream(otelJsonlPath);let keyColumnIndex = -1;let headers: string[] = [];@@ -267,6 +294,7 @@ async function convertCsvToJsonl(parser.on("error", (err: Error) => {clearInterval(progressInterval);outputStream.end();+ otelOutputStream.end();reject(new Error(`CSV parsing error during conversion: ${err.message}`));});@@ -302,69 +330,114 @@ async function convertCsvToJsonl(return;}- // Parse the S3 path: projectId/type/eventBodyId/eventId.json- const pathMatch = keyValue.match(+ // Handle two S3 key path formats:+ // 1. projectId/type/eventBodyId/eventId.json (original)+ // 2. otel/projectId/yyyy/mm/dd/hh/mm/eventId.json (OTEL-style)++ // 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 (!pathMatch) {+ if (otelMatch) {+ const [, projectId] = otelMatch;+ const otelJsonObject: OTelJsonOutputItem = {+ authCheck: {+ validKey: true,+ scope: {+ projectId,+ accessLevel: "project",+ },+ },+ data: {+ fileKey: keyValue,+ },+ };++ // 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;++ const jsonObject: JsonOutputItem = {+ useS3EventStore: true,+ authCheck: {+ validKey: true,+ scope: {+ projectId,+ accessLevel: "all",+ },+ },+ data: {+ eventBodyId,+ fileKey: eventId,+ type: `${type}-create`,+ },+ };++ // Write each JSON object as a single line (JSONL format)+ outputStream.write(JSON.stringify(jsonObject) + "\n");+ writtenObjects++;+ } else {console.warn(`β οΈ Invalid key format at row ${processedRows}: ${keyValue}, skipping...`,);return;}-- const [, projectId, type, eventBodyId, eventId] = pathMatch;-- // Create JSON object with the specified structure- const jsonObject: JsonOutputItem = {- useS3EventStore: true,- authCheck: {- validKey: true,- scope: {- projectId,- accessLevel: "all",- },- },- data: {- eventBodyId,- fileKey: eventId,- type: `${type}-create`,- },- };-- // Write each JSON object as a single line (JSONL format)- outputStream.write(JSON.stringify(jsonObject) + "\n");- writtenObjects++;});// Handle completionparser.on("end", () => {clearInterval(progressInterval);outputStream.end();+ otelOutputStream.end();++ let finishedStreams = 0;+ const checkComplete = () => {+ finishedStreams++;+ if (finishedStreams === 2) {+ const processingTimeMs = Date.now() - startTime;+ const outputFileStats = fs.statSync(jsonlPath);+ const otelOutputFileStats = fs.statSync(otelJsonlPath);+ const outputFileSizeGB = (outputFileStats.size / 1024 ** 3).toFixed(+ 2,+ );+ const otelOutputFileSizeGB = (+ otelOutputFileStats.size /+ 1024 ** 3+ ).toFixed(2);++ console.log("\nπ === JSONL Conversion Complete ===");+ console.log(+ `π Total rows converted: ${processedRows.toLocaleString()}`,+ );+ console.log(+ `π JSON objects written: ${writtenObjects.toLocaleString()}`,+ );+ console.log(+ `π OTEL objects written: ${writtenOtelObjects.toLocaleString()}`,+ );+ console.log(+ `β±οΈ Conversion time: ${(processingTimeMs / 1000).toFixed(1)} seconds`,+ );+ console.log(+ `π Average speed: ${Math.round(processedRows / (processingTimeMs / 1000)).toLocaleString()} rows/second`,+ );+ console.log(`π JSONL file size: ${outputFileSizeGB} GB`);+ console.log(`π OTEL JSONL file size: ${otelOutputFileSizeGB} GB`);++ resolve();+ }+ };- outputStream.on("finish", () => {- const processingTimeMs = Date.now() - startTime;- const outputFileStats = fs.statSync(jsonlPath);- const outputFileSizeGB = (outputFileStats.size / 1024 ** 3).toFixed(2);-- console.log("\nπ === JSONL Conversion Complete ===");- console.log(- `π Total rows converted: ${processedRows.toLocaleString()}`,- );- console.log(- `π JSON objects written: ${writtenObjects.toLocaleString()}`,- );- console.log(- `β±οΈ Conversion time: ${(processingTimeMs / 1000).toFixed(1)} seconds`,- );- console.log(- `π Average speed: ${Math.round(processedRows / (processingTimeMs / 1000)).toLocaleString()} rows/second`,- );- console.log(`π JSONL file size: ${outputFileSizeGB} GB`);-- resolve();- });+ outputStream.on("finish", checkComplete);+ otelOutputStream.on("finish", checkComplete);});// Connect streams@@ -479,16 +552,130 @@ async function processQueueBatch(}}+async function ingestEventsToOtelQueue(otelJsonlPath: string): Promise<void> {+ console.log(+ `π Starting to ingest OTEL events from ${otelJsonlPath} to BullMQ...`,+ );++ // Check if JSONL file exists+ if (!fs.existsSync(otelJsonlPath)) {+ throw new Error(`JSONL file not found: ${otelJsonlPath}`);+ }++ const startTime = Date.now();+ let processedEvents = 0;++ // Set up BullMQ queue with Redis connection+ const queue = OtelIngestionQueue.getInstance({});++ if (!queue) {+ throw new Error("Failed to get queue");+ }++ console.log(`π Connected to Redis and created queue: ${OTEL_NAME}`);++ // Second pass: ingest events into queue in batches+ console.log(`π₯ Starting OTEL queue ingestion...`);++ const BATCH_SIZE = 1000;+ let batch: OTelJsonOutputItem[] = [];+ let batchNumber = 0;++ const ingestStream = fs.createReadStream(otelJsonlPath);+ const ingestRl = readline.createInterface({+ input: ingestStream,+ crlfDelay: Infinity,+ });++ for await (const line of ingestRl) {+ if (!line.trim()) continue;++ try {+ const event: OTelJsonOutputItem = JSON.parse(line);+ batch.push(event);++ // Process queue ingestion in batches+ if (batch.length >= BATCH_SIZE) {+ batchNumber++;+ await processOtelQueueBatch(queue, batch, batchNumber, processedEvents);+ processedEvents += batch.length;+ batch = [];+ }+ } catch {+ // Already warned during first pass+ }+ }++ // Process remaining batch+ if (batch.length > 0) {+ batchNumber++;+ await processOtelQueueBatch(queue, batch, batchNumber, processedEvents);+ processedEvents += batch.length;+ }++ // Close the queue connection+ await queue.close();++ const processingTimeMs = Date.now() - startTime;++ console.log("\nπ === OTEL Event Ingestion Complete ===");+ console.log(`π Total events ingested: ${processedEvents.toLocaleString()}`);+ console.log(+ `β±οΈ Ingestion time: ${(processingTimeMs / 1000).toFixed(1)} seconds`,+ );+ console.log(+ `π Average speed: ${Math.round(processedEvents / (processingTimeMs / 1000)).toLocaleString()} events/second`,+ );+ console.log(`ποΈ Queue name: ${OTEL_NAME}`);+ console.log(`π§ Job name: ${OTEL_JOB_NAME}`);+}++async function processOtelQueueBatch(+ queue: NonNullable<ReturnType<typeof getQueue>>,+ batch: OTelJsonOutputItem[],+ batchNumber: number,+ processedEvents: number,+): Promise<void> {+ // Prepare jobs for bulk insertion+ const jobs: Array<{+ name: QueueJobs.OtelIngestionJob;+ data: TQueueJobTypes[QueueName.OtelIngestionQueue];+ }> = batch.map((event) => ({+ name: QueueJobs.OtelIngestionJob,+ data: {+ payload: event,+ id: randomUUID(),+ timestamp: new Date(),+ name: QueueJobs.OtelIngestionJob,+ },+ }));++ // Add batch to queue+ await queue.addBulk(jobs);++ // Log progress+ console.log(+ `β Added OTEL batch ${batchNumber} (${processedEvents + batch.length} events) to queue`,+ );++ // Log sample event from each batch for tracking+ if (batch.length > 0) {+ console.log(`π Sample OTEL event from batch: ${JSON.stringify(batch[0])}`);+ }+}+// Main executionasync function main() {try {const inputPath = path.resolve(INPUT_FILE);const outputPath = path.resolve(OUTPUT_FILE);const jsonlOutputPath = path.resolve(JSONL_OUTPUT_FILE);+ const otelJsonlOutputPath = path.resolve(OTEL_JSONL_OUTPUT_FILE);console.log(`π Input file: ${inputPath}`);console.log(`π Output file: ${outputPath}`);console.log(`π JSONL output file: ${jsonlOutputPath}`);+ console.log(`π OTEL JSONL output file: ${otelJsonlOutputPath}`);// Step 1: Filter the CSV fileawait filterCsvFile(inputPath, outputPath);@@ -496,13 +683,15 @@ async function main() {console.log("\nβ CSV filtering completed successfully!");// Step 2: Convert filtered CSV to JSONL- await convertCsvToJsonl(outputPath, jsonlOutputPath);+ await convertCsvToJsonl(outputPath, jsonlOutputPath, otelJsonlOutputPath);console.log("\nβ JSONL conversion completed successfully!");// Step 3: Ingest events to BullMQawait ingestEventsToQueue(jsonlOutputPath);+ await ingestEventsToOtelQueue(otelJsonlOutputPath);+console.log("\nβ Script completed successfully!");} catch (error) {console.error("\nβ Error:", (error as Error).message);