🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
perf: split batch to be processed on string length errors in CH writer (#8615)
Steffen Schmitz63a066c9bdb5
diff --git a/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts b/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.tsindex e00f9e869d..86dbad6eef 100644--- a/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts+++ b/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts@@ -523,5 +523,44 @@ describe("ClickhouseWriter", () => {"[TRUNCATED: Field exceeded size limit]",);});++ it("should handle string length errors with batch splitting", async () => {+ const mockInsert = vi+ .spyOn(clickhouseClientMock, "insert")+ .mockRejectedValueOnce(new Error("invalid string length"))+ .mockResolvedValue();++ // Add 4 records to test splitting+ const records = Array.from({ length: 4 }, (_, i) => ({+ id: `${i}`,+ name: `test${i}`,+ }));++ records.forEach((record) => {+ writer.addToQueue(TableName.Traces, record as any);+ });++ await vi.advanceTimersByTimeAsync(writer.writeInterval);++ // After first interval: should have done initial call + retry with first half+ expect(mockInsert).toHaveBeenCalled();+ expect(logger.warn).toHaveBeenCalledWith(+ expect.stringContaining("Splitting batch and retrying"),+ expect.objectContaining({+ error: "invalid string length",+ batchSize: 4,+ }),+ );++ // Check that queue now has the second half (2 records) at the front+ expect(writer["queue"][TableName.Traces]).toHaveLength(2);+ expect(writer["queue"][TableName.Traces][0].data.id).toBe("2");+ expect(writer["queue"][TableName.Traces][1].data.id).toBe("3");++ // Advance timer again to process the requeued items+ await vi.advanceTimersByTimeAsync(writer.writeInterval);++ expect(writer["queue"][TableName.Traces]).toHaveLength(0);+ });});});diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.tsindex 6622cd5f75..69621e13e2 100644--- a/worker/src/services/ClickhouseWriter/index.ts+++ b/worker/src/services/ClickhouseWriter/index.ts@@ -134,14 +134,64 @@ export class ClickhouseWriter {return (// Check for ClickHouse size errors- (errorMessage.includes("size of json object") &&- errorMessage.includes("extremely large") &&- errorMessage.includes("expected not greater than")) ||- // Node.js string size errors- errorMessage.includes("invalid string length")+ errorMessage.includes("size of json object") &&+ errorMessage.includes("extremely large") &&+ errorMessage.includes("expected not greater than"));}+ private isStringLengthError(error: unknown): boolean {+ if (!error || typeof error !== "object") return false;++ const errorMessage = (error as Error).message?.toLowerCase() || "";++ // Node.js string size errors+ return errorMessage.includes("invalid string length");+ }++ /**+ * handleStringLength takes the queueItems and splits the queue in half.+ * It returns to lists, one items that are to be retried (first half), and a list that+ * should be re-added to the queue (second half).+ * That way, we should eventually avoid the JS string length error that happens due to the+ * concatenation.+ */+ private handleStringLengthError<T extends TableName>(+ tableName: T,+ queueItems: ClickhouseWriterQueueItem<T>[],+ ): {+ retryItems: ClickhouseWriterQueueItem<T>[];+ requeueItems: ClickhouseWriterQueueItem<T>[];+ } {+ // If batch size is 1, fallback to truncation to prevent infinite loops+ if (queueItems.length === 1) {+ const truncatedRecord = this.truncateOversizedRecord(+ tableName,+ queueItems[0].data,+ );+ logger.warn(+ `String length error with single record for ${tableName}, falling back to truncation`,+ {+ recordId: queueItems[0].data.id,+ },+ );+ return {+ retryItems: [{ ...queueItems[0], data: truncatedRecord }],+ requeueItems: [],+ };+ }++ const splitPoint = Math.floor(queueItems.length / 2);+ const retryItems = queueItems.slice(0, splitPoint);+ const requeueItems = queueItems.slice(splitPoint);++ logger.info(+ `Splitting batch for ${tableName} due to string length error. Retrying ${retryItems.length}, requeueing ${requeueItems.length}`,+ );++ return { retryItems, requeueItems };+ }+private truncateOversizedRecord<T extends TableName>(tableName: T,record: RecordInsertType<T>,@@ -218,7 +268,7 @@ export class ClickhouseWriter {const entityQueue = this.queue[tableName];if (entityQueue.length === 0) return;- const queueItems = entityQueue.splice(+ let queueItems = entityQueue.splice(0,fullQueue ? entityQueue.length : this.batchSize,);@@ -255,6 +305,7 @@ export class ClickhouseWriter {retry: (error: Error, attemptNumber: number) => {const isRetryable = this.isRetryableError(error);const isSizeError = this.isSizeError(error);+ const isStringLengthError = this.isStringLengthError(error);if (isRetryable) {logger.warn(@@ -269,6 +320,37 @@ export class ClickhouseWriter {"retry.error": error.message,});return true;+ } else if (isStringLengthError) {+ logger.warn(+ `ClickHouse Writer failed with string length error for ${tableName} (attempt ${attemptNumber}/${env.LANGFUSE_INGESTION_CLICKHOUSE_MAX_ATTEMPTS}): Splitting batch and retrying`,+ {+ error: error.message,+ attemptNumber,+ batchSize: queueItems.length,+ },+ );++ const { retryItems, requeueItems } = this.handleStringLengthError(+ tableName,+ queueItems,+ );++ // Update records to write with only the retry items+ recordsToWrite = retryItems.map((item) => item.data);+ queueItems = retryItems;++ // Prepend requeue items to the front of the queue to maintain order as much as possible with parallel execution.+ if (requeueItems.length > 0) {+ entityQueue.unshift(...requeueItems);+ }++ currentSpan?.addEvent("clickhouse-query-split-retry", {+ "retry.attempt": attemptNumber,+ "retry.error": error.message,+ "split.retry_count": retryItems.length,+ "split.requeue_count": requeueItems.length,+ });+ return true;} else if (isSizeError && !hasBeenTruncated) {logger.warn(`ClickHouse Writer failed with size error for ${tableName} (attempt ${attemptNumber}/${env.LANGFUSE_INGESTION_CLICKHOUSE_MAX_ATTEMPTS}): Truncating oversized records and retrying`,