πͺ’ 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: increase throughput for s3 replay script (#10872)
Steffen Schmitz451b49396083
diff --git a/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts b/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.tsindex 148c6c6916..862b7952e6 100644--- a/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts+++ b/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts@@ -12,24 +12,14 @@import * as fs from "fs";import * as path from "path";+import * as readline from "readline";import { parse } from "csv-parse";import { randomUUID } from "crypto";-import {- getClickhouseEntityType,- getQueue,- QueueJobs,- QueueName,-} from "@langfuse/shared/src/server";-import { env } from "../../env";-import {- DeleteObjectCommand,- ListObjectVersionsCommand,- S3Client,-} from "@aws-sdk/client-s3";+import { getQueue, QueueJobs, QueueName } from "@langfuse/shared/src/server";const INPUT_FILE = "events.csv";const OUTPUT_FILE = "events_filtered.csv";-const JSON_OUTPUT_FILE = "events_filtered.json";+const JSONL_OUTPUT_FILE = "events_filtered.jsonl";// Redis configuration// eslint-disable-next-line turbo/no-undeclared-env-vars@@ -42,14 +32,6 @@ interface Stats {processingTimeMs: number;}-const client = new S3Client({- requestHandler: {- httpsAgent: {- maxSockets: 300,- },- },-});-interface JsonOutputItem {useS3EventStore: true;authCheck: {@@ -96,6 +78,7 @@ async function filterCsvFile(const outputStream = fs.createWriteStream(outputPath);let operationColumnIndex = -1;+ let keyColumnIndex = -1;let headers: string[] = [];let isHeaderProcessed = false;@@ -154,6 +137,9 @@ async function filterCsvFile(operationColumnIndex = headers.findIndex((header) => header.toLowerCase().trim() === "operation",);+ keyColumnIndex = headers.findIndex(+ (header) => header.toLowerCase().trim() === "key",+ );if (operationColumnIndex === -1) {clearInterval(progressInterval);@@ -161,9 +147,16 @@ async function filterCsvFile(return;}+ if (keyColumnIndex === -1) {+ clearInterval(progressInterval);+ reject(new Error('Could not find "key" column in CSV header'));+ return;+ }+console.log(`π― Found operation column at index ${operationColumnIndex}`,);+ console.log(`ποΈ Found key column at index ${keyColumnIndex}`);console.log(`π Headers: ${headers.slice(0, 5).join(", ")}${headers.length > 5 ? "..." : ""}`,);@@ -226,16 +219,16 @@ async function filterCsvFile(});}-async function convertCsvToJson(+async function convertCsvToJsonl(csvPath: string,- jsonPath: string,+ jsonlPath: string,): Promise<void> {- console.log(`π Converting ${csvPath} to JSON format...`);- console.log(`π JSON output will be written to ${jsonPath}`);+ console.log(`π Converting ${csvPath} to JSONL format...`);+ console.log(`π JSONL output will be written to ${jsonlPath}`);const startTime = Date.now();let processedRows = 0;- const jsonObjects: JsonOutputItem[] = [];+ let writtenObjects = 0;// Check if CSV file existsif (!fs.existsSync(csvPath)) {@@ -244,6 +237,7 @@ async function convertCsvToJson(return new Promise<void>((resolve, reject) => {const inputStream = fs.createReadStream(csvPath);+ const outputStream = fs.createWriteStream(jsonlPath);let keyColumnIndex = -1;let headers: string[] = [];@@ -264,7 +258,7 @@ async function convertCsvToJson(const elapsed = (Date.now() - startTime) / 1000;const rowsPerSecond = Math.round(processedRows / elapsed);console.log(- `π Converted ${processedRows.toLocaleString()} rows to JSON (${rowsPerSecond.toLocaleString()} rows/sec)`,+ `π Converted ${processedRows.toLocaleString()} rows to JSONL (${rowsPerSecond.toLocaleString()} rows/sec)`,);}}, 5000);@@ -272,11 +266,12 @@ async function convertCsvToJson(// Handle parsing errorsparser.on("error", (err: Error) => {clearInterval(progressInterval);+ outputStream.end();reject(new Error(`CSV parsing error during conversion: ${err.message}`));});// Process each row- parser.on("data", async (row: string[]) => {+ parser.on("data", (row: string[]) => {// Handle header rowif (!isHeaderProcessed) {headers = row;@@ -286,6 +281,7 @@ async function convertCsvToJson(if (keyColumnIndex === -1) {clearInterval(progressInterval);+ outputStream.end();reject(new Error('Could not find "key" column in CSV header'));return;}@@ -308,7 +304,7 @@ async function convertCsvToJson(// Parse the S3 path: projectId/type/eventBodyId/eventId.jsonconst pathMatch = keyValue.match(- /^([^/]+)\/([^/]+)\/([^/]+)\/([^/]+)\.json$/,+ /^([^/]+)\/([^/]+)\/(.+)\/([^/]+)\.json$/,);if (!pathMatch) {@@ -337,27 +333,27 @@ async function convertCsvToJson(},};- jsonObjects.push(jsonObject);+ // 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();- try {- // Write JSON file- fs.writeFileSync(jsonPath, JSON.stringify(jsonObjects, null, 2));-+ outputStream.on("finish", () => {const processingTimeMs = Date.now() - startTime;- const outputFileStats = fs.statSync(jsonPath);+ const outputFileStats = fs.statSync(jsonlPath);const outputFileSizeGB = (outputFileStats.size / 1024 ** 3).toFixed(2);- console.log("\nπ === JSON Conversion Complete ===");+ console.log("\nπ === JSONL Conversion Complete ===");console.log(`π Total rows converted: ${processedRows.toLocaleString()}`,);console.log(- `π JSON objects created: ${jsonObjects.length.toLocaleString()}`,+ `π JSON objects written: ${writtenObjects.toLocaleString()}`,);console.log(`β±οΈ Conversion time: ${(processingTimeMs / 1000).toFixed(1)} seconds`,@@ -365,14 +361,10 @@ async function convertCsvToJson(console.log(`π Average speed: ${Math.round(processedRows / (processingTimeMs / 1000)).toLocaleString()} rows/second`,);- console.log(`π JSON file size: ${outputFileSizeGB} GB`);+ console.log(`π JSONL file size: ${outputFileSizeGB} GB`);resolve();- } catch (error) {- reject(- new Error(`Failed to write JSON file: ${(error as Error).message}`),- );- }+ });});// Connect streams@@ -380,141 +372,110 @@ async function convertCsvToJson(});}-async function ingestEventsToQueue(jsonPath: string): Promise<void> {- console.log(`π Starting to ingest events from ${jsonPath} to BullMQ...`);+async function ingestEventsToQueue(jsonlPath: string): Promise<void> {+ console.log(`π Starting to ingest events from ${jsonlPath} to BullMQ...`);- // Check if JSON file exists- if (!fs.existsSync(jsonPath)) {- throw new Error(`JSON file not found: ${jsonPath}`);+ // Check if JSONL file exists+ if (!fs.existsSync(jsonlPath)) {+ throw new Error(`JSONL file not found: ${jsonlPath}`);}const startTime = Date.now();let processedEvents = 0;- try {- // Read and parse JSON file- const jsonContent = fs.readFileSync(jsonPath, "utf8");- const events: JsonOutputItem[] = JSON.parse(jsonContent);+ // Set up BullMQ queue with Redis connection+ const queue = getQueue(QueueName.IngestionSecondaryQueue);- console.log(`π Total events to ingest: ${events.length.toLocaleString()}`);+ if (!queue) {+ throw new Error("Failed to get queue");+ }- // Set up BullMQ queue with Redis connection+ console.log(`π Connected to Redis and created queue: ${QUEUE_NAME}`);- const queue = getQueue(QueueName.IngestionSecondaryQueue);+ // Second pass: ingest events into queue in batches+ console.log(`π₯ Starting queue ingestion...`);- if (!queue) {- throw new Error("Failed to get queue");- }+ const BATCH_SIZE = 1000;+ let batch: JsonOutputItem[] = [];+ let batchNumber = 0;- console.log(`π Connected to Redis and created queue: ${QUEUE_NAME}`);+ const ingestStream = fs.createReadStream(jsonlPath);+ const ingestRl = readline.createInterface({+ input: ingestStream,+ crlfDelay: Infinity,+ });- // Process events in batches of 500 for S3 restoration- const S3_BATCH_SIZE = 1000;- let processedCount = 0;+ for await (const line of ingestRl) {+ if (!line.trim()) continue;- for (let i = 0; i < events.length; i += S3_BATCH_SIZE) {- const batch = events.slice(i, i + S3_BATCH_SIZE);- console.log(- `π Processing S3 restoration batch ${Math.ceil((i + 1) / S3_BATCH_SIZE)} (${batch.length} events)`,- );+ try {+ const event: JsonOutputItem = JSON.parse(line);+ batch.push(event);- // Process all events in the batch concurrently- await Promise.all(- batch.map(async (event) => {- const keyValue = `${event.authCheck.scope.projectId}/${getClickhouseEntityType(event.data.type)}/${event.data.eventBodyId}/${event.data.fileKey}.json`;-- try {- // List versions to find the delete marker- const listCommand = new ListObjectVersionsCommand({- Bucket: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,- Prefix: keyValue,- });-- const response = await client.send(listCommand);-- // Find the delete marker- const deleteMarkers = response.DeleteMarkers || [];- const deleteMarker = deleteMarkers.find(- (marker) => marker.Key === keyValue,- );-- if (deleteMarker) {- const deleteCommand = new DeleteObjectCommand({- Bucket: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,- Key: keyValue,- VersionId: deleteMarker.VersionId,- });-- await client.send(deleteCommand);- }- } catch (error) {- console.error(- `β Failed to restore ${keyValue}: ${(error as Error).message}`,- );- }- }),- );-- processedCount += batch.length;- console.log(- `β Completed S3 restoration batch (${processedCount}/${events.length} events processed)`,- );+ // Process queue ingestion in batches+ if (batch.length >= BATCH_SIZE) {+ batchNumber++;+ await processQueueBatch(queue, batch, batchNumber, processedEvents);+ processedEvents += batch.length;+ batch = [];+ }+ } catch {+ // Already warned during first pass}- console.log(`π All delete markers removed`);-- // Ingest events into queue in batches of 1000- const BATCH_SIZE = 1000;- for (let i = 0; i < events.length; i += BATCH_SIZE) {- const batch = events.slice(i, i + BATCH_SIZE);+ }- // Prepare jobs for bulk insertion- const jobs = batch.map((event) => ({- name: JOB_NAME,- data: {- payload: event,- id: randomUUID(),- timestamp: new Date(),- name: JOB_NAME,- },- }));+ // Process remaining batch+ if (batch.length > 0) {+ batchNumber++;+ await processQueueBatch(queue, batch, batchNumber, processedEvents);+ processedEvents += batch.length;+ }- // Add batch to queue- await queue.addBulk(jobs);+ // Close the queue connection+ await queue.close();++ const processingTimeMs = Date.now() - startTime;++ console.log("\nπ === 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: ${QUEUE_NAME}`);+ console.log(`π§ Job name: ${JOB_NAME}`);+}- processedEvents += batch.length;+async function processQueueBatch(+ queue: NonNullable<ReturnType<typeof getQueue>>,+ batch: JsonOutputItem[],+ batchNumber: number,+ processedEvents: number,+): Promise<void> {+ // Prepare jobs for bulk insertion+ const jobs = batch.map((event) => ({+ name: JOB_NAME,+ data: {+ payload: event,+ id: randomUUID(),+ timestamp: new Date(),+ name: JOB_NAME,+ },+ }));- // Log progress every batch- console.log(- `β Added batch ${Math.ceil((i + 1) / BATCH_SIZE)} (${processedEvents}/${events.length} events)`,- );+ // Add batch to queue+ await queue.addBulk(jobs);- // Log sample event from each batch for tracking- if (batch.length > 0) {- console.log(`π Sample event from batch: ${JSON.stringify(batch[0])}`);- }- }+ // Log progress+ console.log(+ `β Added batch ${batchNumber} (${processedEvents + batch.length} events) to queue`,+ );- // Close the queue connection- await queue.close();-- const processingTimeMs = Date.now() - startTime;-- console.log("\nπ === 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: ${QUEUE_NAME}`);- console.log(`π§ Job name: ${JOB_NAME}`);- } catch (error) {- throw new Error(- `Failed to ingest events to queue: ${(error as Error).message}`,- );+ // Log sample event from each batch for tracking+ if (batch.length > 0) {+ console.log(`π Sample event from batch: ${JSON.stringify(batch[0])}`);}}@@ -523,24 +484,24 @@ async function main() {try {const inputPath = path.resolve(INPUT_FILE);const outputPath = path.resolve(OUTPUT_FILE);- const jsonOutputPath = path.resolve(JSON_OUTPUT_FILE);+ const jsonlOutputPath = path.resolve(JSONL_OUTPUT_FILE);console.log(`π Input file: ${inputPath}`);console.log(`π Output file: ${outputPath}`);- console.log(`π JSON output file: ${jsonOutputPath}`);+ console.log(`π JSONL output file: ${jsonlOutputPath}`);// Step 1: Filter the CSV fileawait filterCsvFile(inputPath, outputPath);console.log("\nβ CSV filtering completed successfully!");- // Step 2: Convert filtered CSV to JSON- await convertCsvToJson(outputPath, jsonOutputPath);+ // Step 2: Convert filtered CSV to JSONL+ await convertCsvToJsonl(outputPath, jsonlOutputPath);- console.log("\nβ JSON conversion completed successfully!");+ console.log("\nβ JSONL conversion completed successfully!");// Step 3: Ingest events to BullMQ- await ingestEventsToQueue(jsonOutputPath);+ await ingestEventsToQueue(jsonlOutputPath);console.log("\nβ Script completed successfully!");} catch (error) {