🪢 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
feat: replay ingestion events v2 (#12319)
Steffen Schmitz9e9d9488eb67
diff --git a/web/src/pages/api/admin/ingestion-replay.ts b/web/src/pages/api/admin/ingestion-replay.tsnew file mode 100644index 0000000000..17da2cd555--- /dev/null+++ b/web/src/pages/api/admin/ingestion-replay.ts@@ -0,0 +1,159 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { z } from "zod/v4";+import { randomUUID } from "crypto";+import {+ logger,+ QueueJobs,+ SecondaryIngestionQueue,+ OtelIngestionQueue,+} from "@langfuse/shared/src/server";+import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";++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$/;++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ try {+ if (req.method !== "POST") {+ res.status(405).json({ error: "Method Not Allowed" });+ return;+ }++ if (+ !AdminApiAuthService.handleAdminAuth(req, res, {+ isAllowedOnLangfuseCloud: true,+ })+ ) {+ return;+ }++ const body = IngestionReplayBody.safeParse(req.body);+ if (!body.success) {+ res.status(400).json({ error: body.error });+ return;+ }++ const standardJobs: Array<{+ name: QueueJobs.IngestionJob;+ data: {+ timestamp: Date;+ id: string;+ payload: {+ data: { type: any; eventBodyId: string; fileKey: string };+ authCheck: {+ validKey: true;+ scope: { projectId: string };+ };+ };+ name: QueueJobs.IngestionJob;+ };+ }> = [];++ const otelJobs: Array<{+ name: QueueJobs.OtelIngestionJob;+ data: {+ timestamp: Date;+ id: string;+ payload: {+ data: { fileKey: string };+ authCheck: {+ validKey: true;+ scope: { projectId: string; accessLevel: "project" };+ };+ };+ name: QueueJobs.OtelIngestionJob;+ };+ }> = [];++ let skipped = 0;+ const errors: string[] = [];++ for (const key of body.data.keys) {+ const otelMatch = key.match(OTEL_KEY_REGEX);+ if (otelMatch) {+ const [, projectId] = otelMatch;+ otelJobs.push({+ name: QueueJobs.OtelIngestionJob,+ data: {+ timestamp: new Date(),+ id: randomUUID(),+ payload: {+ data: { fileKey: key },+ authCheck: {+ validKey: true,+ scope: { projectId: projectId!, accessLevel: "project" },+ },+ },+ name: QueueJobs.OtelIngestionJob,+ },+ });+ continue;+ }++ const standardMatch = key.match(STANDARD_KEY_REGEX);+ if (standardMatch) {+ const [, projectId, type, eventBodyId, eventId] = standardMatch;+ standardJobs.push({+ name: QueueJobs.IngestionJob,+ data: {+ timestamp: new Date(),+ id: randomUUID(),+ payload: {+ data: {+ type: `${type}-create`,+ eventBodyId: eventBodyId!,+ fileKey: eventId!,+ },+ authCheck: {+ validKey: true,+ scope: { projectId: projectId! },+ },+ },+ name: QueueJobs.IngestionJob,+ },+ });+ continue;+ }++ skipped++;+ errors.push(`Invalid key format: ${key}`);+ }++ if (standardJobs.length > 0) {+ const queue = SecondaryIngestionQueue.getInstance();+ if (!queue) {+ throw new Error("Failed to get SecondaryIngestionQueue");+ }+ await queue.addBulk(standardJobs);+ }++ if (otelJobs.length > 0) {+ const queue = OtelIngestionQueue.getInstance({});+ if (!queue) {+ throw new Error("Failed to get OtelIngestionQueue");+ }+ await queue.addBulk(otelJobs);+ }++ const queued = standardJobs.length + otelJobs.length;++ logger.info(+ `Ingestion replay: queued ${queued}, skipped ${skipped}, errors ${errors.length}`,+ );++ return res.status(200).json({ queued, skipped, errors });+ } catch (e) {+ logger.error("Failed to replay ingestion events", e);+ res+ .status(500)+ .json({ error: e instanceof Error ? e.message : "Unknown error" });+ }+}diff --git a/worker/src/scripts/replayIngestionEventsV2/README.md b/worker/src/scripts/replayIngestionEventsV2/README.mdnew file mode 100644index 0000000000..6f566e247f--- /dev/null+++ b/worker/src/scripts/replayIngestionEventsV2/README.md@@ -0,0 +1,258 @@+# Replay Ingestion Events from S3 (v2)++Replays failed ingestion events by reading S3 keys from a CSV and submitting them to Langfuse via an admin API endpoint. This replaces the [v1 script](../replayIngestionEvents/README.md), which required direct Redis, ClickHouse, and PostgreSQL access plus a full repo clone.++v2 only requires the Langfuse host URL, an admin API key, and a CSV file exported from Athena.++```+Athena (S3 access logs)+ │+ ▼+events.csv ──► replay script ──► POST /api/admin/ingestion-replay+ │+ ▼+ Redis queues (IngestionSecondaryQueue / OtelIngestionQueue)+ │+ ▼+ Worker processing+```++## Prerequisites++- **S3 server access logging** enabled on the Langfuse events bucket (see [Initial setup](#1-initial-setup-one-time))+- **Athena** configured to query the access logs (see [Initial setup](#1-initial-setup-one-time))+- **Node.js 18+** with `npx tsx` available (no repo clone or `pnpm` needed)+- **`events.csv`** exported from Athena (see [Export events](#2-export-events-from-athena))+- **`LANGFUSE_HOST`** URL of the target Langfuse instance (e.g. `https://cloud.langfuse.com`)+- **`ADMIN_API_KEY`** for authenticating against the admin API+- Network access from your machine to the Langfuse host++## 1. Initial setup (one-time, on AWS)++Before you can query S3 access logs via Athena, you need to configure S3 server access logging and set up Athena.+Skip this section if your environment already has Athena configured for the events bucket.+If you're not using AWS as a cloud vendor, consult your cloud provider's documentation on how to store blob storage access logs and efficiently retrieve the events.csv.++### 1a. Enable S3 server access logging++Create a dedicated S3 bucket to store access logs for your Langfuse events bucket.+Then enable server access logging on the events bucket with the new bucket as the destination.++AWS docs: [Enabling Amazon S3 server access logging](https://docs.aws.amazon.com/AmazonS3/latest/userguide/enable-server-access-logging.html)++Set a key prefix (e.g. `logs/<events-bucket-name>/`) to keep logs organized if you reuse the bucket for multiple sources.++### 1b. Set up Athena query result location++Athena requires an S3 location to store query results. Configure this in the Athena console under **Settings → Query result location**.++AWS docs: [Specifying a query result location](https://docs.aws.amazon.com/athena/latest/ug/querying.html#query-results-specify-location)++### 1c. Create an Athena database++```sql+CREATE DATABASE s3_access_logs_db+```++### 1d. Create the S3 access logs table++Create an external table that maps the S3 server access log format. Replace the `LOCATION` with the S3 URI of your access log bucket and prefix from step 1a.++AWS docs: [Querying access logs for requests using Amazon Athena](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-s3-access-logs-to-identify-requests.html)++```sql+CREATE EXTERNAL TABLE `s3_access_logs_db.events_bucket_logs`(+ `bucketowner` STRING,+ `bucket_name` STRING,+ `requestdatetime` STRING,+ `remoteip` STRING,+ `requester` STRING,+ `requestid` STRING,+ `operation` STRING,+ `key` STRING,+ `request_uri` STRING,+ `httpstatus` STRING,+ `errorcode` STRING,+ `bytessent` BIGINT,+ `objectsize` BIGINT,+ `totaltime` STRING,+ `turnaroundtime` STRING,+ `referrer` STRING,+ `useragent` STRING,+ `versionid` STRING,+ `hostid` STRING,+ `sigv` STRING,+ `ciphersuite` STRING,+ `authtype` STRING,+ `endpoint` STRING,+ `tlsversion` STRING,+ `accesspointarn` STRING,+ `aclrequired` STRING)+ROW FORMAT SERDE+ 'org.apache.hadoop.hive.serde2.RegexSerDe'+WITH SERDEPROPERTIES (+ 'input.regex'='([^ ]*) ([^ ]*) \\[(.*?)\\] ([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*) (\"[^\"]*\"|-) (-|[0-9]*) ([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*) (\"[^\"]*\"|-) ([^ ]*)(?: ([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*))?.*$')+STORED AS INPUTFORMAT+ 'org.apache.hadoop.mapred.TextInputFormat'+OUTPUTFORMAT+ 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'+LOCATION+ 's3://<your-access-log-bucket>/logs/<your-events-bucket>/'+```++### 1e. Verify the setup++Run a simple query to confirm logs are being collected and the table is configured correctly:++```sql+SELECT key, operation, httpstatus, requestdatetime+FROM s3_access_logs_db.events_bucket_logs+WHERE operation = 'REST.PUT.OBJECT'+LIMIT 10+```++If this returns results, the setup is complete. Note that it may take some time after enabling access logging for the first logs to appear.++## 2. Export events from Athena++Query S3 access logs to identify the events that need to be replayed. Adjust the time range, table name, and bucket name to match your environment and incident window.++```sql+SELECT operation, key+FROM s3_access_logs_db.events_bucket_logs+WHERE operation = 'REST.PUT.OBJECT'+ AND bucket_name = '<your-events-bucket>'+ AND parse_datetime(requestdatetime, 'dd/MMM/yyyy:HH:mm:ss Z')+ BETWEEN parse_datetime('2025-07-09:00:30:00', 'yyyy-MM-dd:HH:mm:ss')+ AND parse_datetime('2025-07-09:07:45:00', 'yyyy-MM-dd:HH:mm:ss')+```++Download the result as CSV. The expected format:++```csv+"operation","key"+"REST.PUT.OBJECT","projectId/trace/eventBodyId/eventId.json"+"REST.PUT.OBJECT","otel/projectId/2025/07/09/14/30/some-uuid.json"+```++Two S3 key formats are supported:++| Format | Pattern | Target queue |+|--------|---------|-------------|+| Standard | `{projectId}/{type}/{eventBodyId}/{eventId}.json` | `IngestionSecondaryQueue` |+| OTEL | `otel/{projectId}/{yyyy}/{mm}/{dd}/{hh}/{mm}/{eventId}.json` | `OtelIngestionQueue` |++Keys that don't match either pattern are skipped and logged.++## 3. Run the replay script++```bash+LANGFUSE_HOST=https://cloud.langfuse.com \+ADMIN_API_KEY=your-admin-api-key \+npx tsx replay.ts --file events.csv+```++## Configuration++| Flag / env var | Default | Description |+|----------------|---------|-------------|+| `--file` | `events.csv` | Path to the CSV file |+| `--batch-size` | `500` | Number of keys per API request |+| `--concurrency` | `4` | Maximum parallel API requests |+| `--rate-limit` | `50` | Maximum requests per second |+| `--dry-run` | `false` | Parse and validate without sending requests |+| `--resume` | `false` | Resume from the last checkpoint (skips already-processed rows) |+| `LANGFUSE_HOST` | - | Target Langfuse instance URL (required) |+| `ADMIN_API_KEY` | - | Admin API key for authentication (required) |++## Admin API endpoint++### `POST /api/admin/ingestion-replay`++Accepts a batch of S3 keys and enqueues them for reprocessing.++**Authentication**: `Authorization: Bearer {ADMIN_API_KEY}` header, validated by `AdminApiAuthService`.++**Request**:++```json+{+ "keys": [+ "projectId/trace/eventBodyId/eventId.json",+ "otel/projectId/2025/07/09/14/30/some-uuid.json"+ ]+}+```++**Response** (`200 OK`):++```json+{+ "queued": 498,+ "skipped": 2,+ "errors": []+}+```++| Status | Meaning |+|--------|---------|+| `200` | Batch accepted (check `skipped`/`errors` for partial failures) |+| `401` | Missing or invalid `ADMIN_API_KEY` |+| `400` | Malformed request body |+| `429` | Rate limited, retry after backoff |++## Event transformation++The endpoint parses each S3 key and constructs the queue payload:++**Standard keys** (`{projectId}/{type}/{eventBodyId}/{eventId}.json`):++```json+{+ "authCheck": {+ "validKey": true,+ "scope": { "projectId": "<projectId>" }+ },+ "data": {+ "eventBodyId": "<eventBodyId>",+ "fileKey": "<eventId>",+ "type": "<type>-create"+ }+}+```++Enqueued to `IngestionSecondaryQueue`.++**OTEL keys** (`otel/{projectId}/{yyyy}/{mm}/{dd}/{hh}/{mm}/{eventId}.json`):++```json+{+ "authCheck": {+ "validKey": true,+ "scope": { "projectId": "<projectId>", "accessLevel": "project" }+ },+ "data": {+ "fileKey": "otel/<projectId>/<yyyy>/<mm>/<dd>/<hh>/<mm>/<eventId>.json"+ }+}+```++Enqueued to `OtelIngestionQueue`.++## Progress tracking and error handling++- **Progress**: The script logs progress after each batch (e.g. `[1200/45000] 2.7% — 498 queued, 2 skipped`).+- **Checkpoints**: After each successful batch, the current CSV row offset is written to a `.checkpoint` file next to the input CSV. Use `--resume` to continue from the last checkpoint after a failure.+- **Rate limiting**: The script respects `--rate-limit` locally and backs off on `429` responses from the server using exponential backoff with jitter.+- **Retries**: Transient failures (`429`, `5xx`) are retried up to 3 times per batch. Permanent failures (`4xx` other than `429`) are logged and skipped.+- **Error log**: Failed keys are appended to `errors.csv` next to the input file for manual inspection.++## Differences from v1++| | v1 | v2 |+|-|----|----|+| Infrastructure access | Redis, ClickHouse, PostgreSQL, S3 | Langfuse host URL only |+| Setup | Full repo clone, `pnpm install`, `.env` file | `npx tsx` + env vars |+| Event delivery | Direct BullMQ `addBulk` to Redis | HTTP POST to admin API |+| Resume support | Manual (split files, rerun) | Built-in checkpoint/resume |+| Rate limiting | None (can overwhelm Redis) | Client-side + server-side rate limiting |diff --git a/worker/src/scripts/replayIngestionEventsV2/replay.ts b/worker/src/scripts/replayIngestionEventsV2/replay.tsnew file mode 100644index 0000000000..882a0073fc--- /dev/null+++ b/worker/src/scripts/replayIngestionEventsV2/replay.ts@@ -0,0 +1,401 @@+#!/usr/bin/env node++/* eslint-disable turbo/no-undeclared-env-vars */++/**+ * Standalone replay script for Langfuse ingestion events.+ * Reads S3 keys from a CSV (exported from Athena) and sends them+ * in batches to POST /api/admin/ingestion-replay.+ *+ * Usage:+ * LANGFUSE_HOST=https://cloud.langfuse.com \+ * ADMIN_API_KEY=your-key \+ * npx tsx replay.ts --file events.csv+ *+ * No monorepo dependencies — only Node.js built-ins + global fetch.+ */++import {+ createReadStream,+ readFileSync,+ writeFileSync,+ existsSync,+ appendFileSync,+} from "node:fs";+import { resolve, dirname } from "node:path";+import { createInterface } from "node:readline";+import { parseArgs } from "node:util";++// ---------------------------------------------------------------------------+// CLI args+// ---------------------------------------------------------------------------++const { values: args } = parseArgs({+ options: {+ file: { type: "string", default: "events.csv" },+ "batch-size": { type: "string", default: "500" },+ concurrency: { type: "string", default: "4" },+ "rate-limit": { type: "string", default: "50" },+ "dry-run": { type: "boolean", default: false },+ resume: { type: "boolean", default: false },+ },+ strict: true,+});++const FILE = resolve(args.file!);+const BATCH_SIZE = parseInt(args["batch-size"]!, 10);+const CONCURRENCY = parseInt(args.concurrency!, 10);+const RATE_LIMIT = parseInt(args["rate-limit"]!, 10);+const DRY_RUN = args["dry-run"]!;+const RESUME = args.resume!;++// ---------------------------------------------------------------------------+// Env vars+// ---------------------------------------------------------------------------++const LANGFUSE_HOST = process.env.LANGFUSE_HOST;+const ADMIN_API_KEY = process.env.ADMIN_API_KEY;++if (!LANGFUSE_HOST) {+ console.error("Error: LANGFUSE_HOST environment variable is required");+ process.exit(1);+}+if (!ADMIN_API_KEY) {+ console.error("Error: ADMIN_API_KEY environment variable is required");+ process.exit(1);+}++const API_URL = `${LANGFUSE_HOST.replace(/\/+$/, "")}/api/admin/ingestion-replay`;++// ---------------------------------------------------------------------------+// Checkpoint+// ---------------------------------------------------------------------------++const CHECKPOINT_FILE = `${FILE}.checkpoint`;+const ERRORS_FILE = resolve(dirname(FILE), `errors.csv`);++function readCheckpoint(): number {+ if (!RESUME || !existsSync(CHECKPOINT_FILE)) return 0;+ const content = readFileSync(CHECKPOINT_FILE, "utf-8").trim();+ const offset = parseInt(content, 10);+ return isNaN(offset) ? 0 : offset;+}++function writeCheckpoint(offset: number): void {+ writeFileSync(CHECKPOINT_FILE, String(offset), "utf-8");+}++function appendErrors(keys: string[]): void {+ const lines = keys.map((k) => `"${k.replace(/"/g, '""')}"\n`).join("");+ appendFileSync(ERRORS_FILE, lines, "utf-8");+}++// ---------------------------------------------------------------------------+// CSV parsing — extract `key` column+// ---------------------------------------------------------------------------++function parseCSVField(field: string): string {+ const trimmed = field.trim();+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {+ return trimmed.slice(1, -1).replace(/""/g, '"');+ }+ return trimmed;+}++async function readKeys(): Promise<string[]> {+ const keys: string[] = [];+ const rl = createInterface({+ input: createReadStream(FILE, "utf-8"),+ crlfDelay: Infinity,+ });++ let headerParsed = false;+ let keyIndex = -1;+ const startOffset = readCheckpoint();+ let rowNumber = 0;++ for await (const line of rl) {+ if (!headerParsed) {+ const headers = line.split(",").map(parseCSVField);+ keyIndex = headers.findIndex((h) => h.toLowerCase() === "key");+ if (keyIndex === -1) {+ console.error(+ `Error: CSV must have a "key" column. Found headers: ${headers.join(", ")}`,+ );+ process.exit(1);+ }+ headerParsed = true;+ continue;+ }++ rowNumber++;+ if (rowNumber <= startOffset) continue;++ const fields = splitCSVLine(line);+ const key = parseCSVField(fields[keyIndex] ?? "");+ if (key) keys.push(key);+ }++ return keys;+}++/**+ * Split a CSV line respecting quoted fields.+ */+function splitCSVLine(line: string): string[] {+ const fields: string[] = [];+ let current = "";+ let inQuotes = false;++ for (let i = 0; i < line.length; i++) {+ const char = line[i]!;+ if (inQuotes) {+ if (char === '"') {+ if (i + 1 < line.length && line[i + 1] === '"') {+ current += '"';+ i++;+ } else {+ inQuotes = false;+ }+ } else {+ current += char;+ }+ } else {+ if (char === '"') {+ inQuotes = true;+ } else if (char === ",") {+ fields.push(current);+ current = "";+ } else {+ current += char;+ }+ }+ }+ fields.push(current);+ return fields;+}++// ---------------------------------------------------------------------------+// Rate limiter (token bucket)+// ---------------------------------------------------------------------------++class TokenBucket {+ private tokens: number;+ private lastRefill: number;++ constructor(private readonly rate: number) {+ this.tokens = rate;+ this.lastRefill = Date.now();+ }++ async acquire(): Promise<void> {+ while (true) {+ this.refill();+ if (this.tokens >= 1) {+ this.tokens -= 1;+ return;+ }+ // Wait until at least one token is available+ const waitMs = Math.ceil(1000 / this.rate);+ await sleep(waitMs);+ }+ }++ private refill(): void {+ const now = Date.now();+ const elapsed = now - this.lastRefill;+ const newTokens = (elapsed / 1000) * this.rate;+ this.tokens = Math.min(this.rate, this.tokens + newTokens);+ this.lastRefill = now;+ }+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++// ---------------------------------------------------------------------------+// Semaphore for concurrency control+// ---------------------------------------------------------------------------++class Semaphore {+ private waiting: Array<() => void> = [];+ private count: number;++ constructor(private readonly max: number) {+ this.count = max;+ }++ async acquire(): Promise<void> {+ if (this.count > 0) {+ this.count--;+ return;+ }+ return new Promise((resolve) => {+ this.waiting.push(resolve);+ });+ }++ release(): void {+ const next = this.waiting.shift();+ if (next) {+ next();+ } else {+ this.count++;+ }+ }+}++// ---------------------------------------------------------------------------+// HTTP client with retries+// ---------------------------------------------------------------------------++interface ReplayResponse {+ queued: number;+ skipped: number;+ errors: string[];+}++async function sendBatch(keys: string[]): Promise<ReplayResponse> {+ const maxRetries = 3;++ for (let attempt = 0; attempt <= maxRetries; attempt++) {+ const resp = await fetch(API_URL, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${ADMIN_API_KEY}`,+ },+ body: JSON.stringify({ keys }),+ });++ if (resp.ok) {+ return (await resp.json()) as ReplayResponse;+ }++ // Retry on 429 and 5xx+ if (resp.status === 429 || resp.status >= 500) {+ if (attempt < maxRetries) {+ const baseDelay = Math.pow(2, attempt) * 1000;+ const jitter = Math.random() * 1000;+ const delay = baseDelay + jitter;+ console.warn(+ ` Retry ${attempt + 1}/${maxRetries} after ${resp.status} (waiting ${Math.round(delay)}ms)`,+ );+ await sleep(delay);+ continue;+ }+ }++ // Non-retryable error or exhausted retries+ const body = await resp.text().catch(() => "");+ throw new Error(`HTTP ${resp.status}: ${body.slice(0, 200)}`);+ }++ // Should not reach here+ throw new Error("Exhausted retries");+}++// ---------------------------------------------------------------------------+// Main+// ---------------------------------------------------------------------------++async function main() {+ console.log(`Replay ingestion events`);+ console.log(` File: ${FILE}`);+ console.log(` Batch size: ${BATCH_SIZE}`);+ console.log(` Concurrency: ${CONCURRENCY}`);+ console.log(` Rate limit: ${RATE_LIMIT} req/s`);+ console.log(` Dry run: ${DRY_RUN}`);+ console.log(` Resume: ${RESUME}`);+ console.log(` API URL: ${API_URL}`);+ console.log();++ const keys = await readKeys();+ const totalKeys = keys.length;++ if (totalKeys === 0) {+ console.log("No keys to process.");+ return;+ }++ console.log(`Loaded ${totalKeys} keys to replay.`);+ if (DRY_RUN) {+ console.log("Dry run — no requests will be sent.");+ console.log(`Would send ${Math.ceil(totalKeys / BATCH_SIZE)} batches.`);+ return;+ }++ const startOffset = readCheckpoint();+ const bucket = new TokenBucket(RATE_LIMIT);+ const semaphore = new Semaphore(CONCURRENCY);++ let totalQueued = 0;+ let totalSkipped = 0;+ let totalErrors = 0;+ let processedKeys = 0;+ const batches: string[][] = [];++ for (let i = 0; i < keys.length; i += BATCH_SIZE) {+ batches.push(keys.slice(i, i + BATCH_SIZE));+ }++ const promises: Promise<void>[] = [];++ for (let batchIdx = 0; batchIdx < batches.length; batchIdx++) {+ const batch = batches[batchIdx]!;+ const batchNumber = batchIdx + 1;++ await semaphore.acquire();+ await bucket.acquire();++ const promise = (async () => {+ try {+ const result = await sendBatch(batch);+ totalQueued += result.queued;+ totalSkipped += result.skipped;++ if (result.errors.length > 0) {+ totalErrors += result.errors.length;+ console.warn(+ ` Batch ${batchNumber}: ${result.errors.length} errors`,+ );+ }+ } catch (err) {+ totalErrors += batch.length;+ appendErrors(batch);+ console.error(+ ` Batch ${batchNumber} failed: ${err instanceof Error ? err.message : String(err)}`,+ );+ } finally {+ processedKeys += batch.length;+ const pct = ((processedKeys / totalKeys) * 100).toFixed(1);+ const currentRow = startOffset + processedKeys;+ console.log(+ `[${currentRow}/${startOffset + totalKeys}] ${pct}% — ${totalQueued} queued, ${totalSkipped} skipped`,+ );+ writeCheckpoint(currentRow);+ semaphore.release();+ }+ })();++ promises.push(promise);+ }++ await Promise.all(promises);++ console.log();+ console.log(`Done.`);+ console.log(` Queued: ${totalQueued}`);+ console.log(` Skipped: ${totalSkipped}`);+ console.log(` Errors: ${totalErrors}`);++ if (totalErrors > 0) {+ console.log(` See ${ERRORS_FILE} for failed keys.`);+ }+}++main().catch((err) => {+ console.error("Fatal error:", err);+ process.exit(1);+});