🪢 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: switch the dual write to a locked partition mode based on timestamps (#9885)
Steffen Schmitzc2c397ebb1f7
diff --git a/worker/src/features/eventPropagation/handleEventPropagationJob.ts b/worker/src/features/eventPropagation/handleEventPropagationJob.tsindex 23b9fafc59..b5a1d7b802 100644--- a/worker/src/features/eventPropagation/handleEventPropagationJob.ts+++ b/worker/src/features/eventPropagation/handleEventPropagationJob.ts@@ -125,13 +125,15 @@ export const handleEventPropagationJob = async (partition: partition,});- // Step 1: Get list of partitions ordered by time+ // Step 1: Get list of partitions ordered by time, filtering for those older than 4 minutes+ // Filter in ClickHouse for better performance - only return partitions older than 4 minutesconst partitions = await queryClickhouse<{ partition: string }>({query: `SELECT DISTINCT partitionFROM system.partsWHERE table = 'observations_batch_staging'AND active = 1+ AND toDateTime(partition) < now() - INTERVAL 4 MINUTEORDER BY partition DESC`,tags: {@@ -140,13 +142,17 @@ export const handleEventPropagationJob = async (},});- if (partitions.length < 3) {+ if (partitions.length === 0) {logger.info(- `[DUAL WRITE] Not enough partitions for processing. Found ${partitions.length} partition(s), need at least 3`,+ `[DUAL WRITE] No partitions older than 4 minutes available for processing`,);return;}+ logger.info(+ `[DUAL WRITE] Found ${partitions.length} partition(s) older than 4 minutes to process`,+ );+// Determine which partition to processlet partitionToProcess: string | null = null;if (partition) {@@ -165,12 +171,12 @@ export const handleEventPropagationJob = async (}// If no partition was processed yet (either no partition specified or it was locked),- // fall back to discovery mode - process oldest safe partition+ // fall back to discovery mode - process oldest partition that is unlockedif (!partitionToProcess) {// We sort partitions from newest to oldest and then remove elements from the back.- // This means that the oldest, unlocked element will be processed.- // Later, we can continue to process from the back until two elements remain.- while (partitionToProcess === null && partitions.length > 2) {+ // This means that the oldest, unlocked partition will be processed.+ // All partitions in the list are already verified to be older than 4 minutes.+ while (partitionToProcess === null && partitions.length > 0) {const internalPartition = partitions.pop()!;const lockAcquired = await acquirePartitionLock(internalPartition.partition,@@ -290,7 +296,7 @@ export const handleEventPropagationJob = async (-- When the observation IS the trace itself (id = trace_id), parent should be NULL-- Otherwise, use standard wrapper logic: parent_observation_id or prefixed trace_id as fallbackCASE- WHEN obs.id = obs.trace_id THEN NULL+ WHEN obs.id = concat('t-', obs.trace_id) THEN NULLELSE coalesce(obs.parent_observation_id, concat('t-', obs.trace_id))END AS parent_span_id,-- Convert timestamps from DateTime64(3) to DateTime64(6) via implicit conversion@@ -369,66 +375,14 @@ export const handleEventPropagationJob = async (`[DUAL WRITE] Successfully propagated observations from partition ${partitionToProcess} to events table`,);- // Step 3: Detach the processed partition (fast, synchronous operation)- await commandClickhouse({- query: `- ALTER TABLE observations_batch_staging- DETACH PARTITION '${partitionToProcess}'- `,- tags: {- feature: "ingestion",- partition: partitionToProcess,- operation_name: "detachPartition",- },- clickhouseConfigs: {- request_timeout: 180000, // 3 minutes timeout- },- });-- logger.info(- `[DUAL WRITE] Detached partition ${partitionToProcess} after successful processing`,- );-- // Step 4: Drop the detached partition asynchronously (no await for better throughput)- commandClickhouse({- query: `- ALTER TABLE observations_batch_staging- DROP DETACHED PARTITION '${partitionToProcess}'- `,- tags: {- feature: "ingestion",- partition: partitionToProcess,- operation_name: "dropDetachedPartition",- },- clickhouseConfigs: {- request_timeout: 60000 * 15, // 15 minutes timeout- clickhouse_settings: {- allow_drop_detached: 1,- },- },- })- .then(() => {- logger.info(- `[DUAL WRITE] Successfully dropped detached partition ${partitionToProcess}`,- );- })- .catch((error) => {- logger.error(- `[DUAL WRITE] Failed to drop detached partition ${partitionToProcess}`,- error,- );- traceException(error);- });-- logger.info(- `[DUAL WRITE] Scheduled async drop for detached partition ${partitionToProcess}`,- );-- if (partitions.length > 3) {+ // Step 3: Schedule additional jobs for remaining partitions (all are already verified to be >4 minutes old).+ // We do this before the drop as this is a fast operation that shouldn't wait for the slow dropping call.+ // We're only running this if there are more than one left to be processed as this means we have some catch-up to do.+ if (partitions.length > 1) {let additionalSchedules =env.LANGFUSE_EVENT_PROPAGATION_WORKER_GLOBAL_CONCURRENCY;const queue = EventPropagationQueue.getInstance();- while (queue && partitions.length > 3 && additionalSchedules > 0) {+ while (queue && partitions.length > 1 && additionalSchedules > 0) {const internalPartition = partitions.pop()!;// Check if partition is locked before scheduling@@ -454,6 +408,26 @@ export const handleEventPropagationJob = async ();}}++ // Step 4: Drop the processed partition (single synchronous operation)+ await commandClickhouse({+ query: `+ ALTER TABLE observations_batch_staging+ DROP PARTITION '${partitionToProcess}'+ `,+ tags: {+ feature: "ingestion",+ partition: partitionToProcess,+ operation_name: "dropPartition",+ },+ clickhouseConfigs: {+ request_timeout: 60000 * 20, // 20 minutes timeout+ },+ });++ logger.info(+ `[DUAL WRITE] Successfully dropped partition ${partitionToProcess}`,+ );} catch (error) {logger.error("[DUAL WRITE] Failed to process event propagation batch",diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 9ce150767c..3188753869 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -671,7 +671,7 @@ export class IngestionService {if (createEventTraceRecord) {const traceAsStagingObservation = convertTraceToStagingObservation(finalTraceRecord,- createdAtTimestamp.getTime(),+ this.getPartitionAwareTimestamp(createdAtTimestamp),);this.clickHouseWriter.addToQueue(TableName.ObservationsBatchStaging,@@ -826,10 +826,17 @@ export class IngestionService {);// Dual-write to staging table for batch propagation to events table+ // Here, we add some additional logic around the first seen timestamp.+ // We "lock" partitions 4min after their creation, i.e. the 15:00:00 partition+ // should stop receiving updates at 15:04:00.+ // This means that we keep the createdAtTimestamp as-is if it is within the last+ // 3.5 minutes (incl. a 30s buffer around writes) and otherwise,+ // we set the current timestamp for the event.if (writeToStagingTables) {const stagingRecord = {...finalObservationRecord,- s3_first_seen_timestamp: createdAtTimestamp.getTime(),+ s3_first_seen_timestamp:+ this.getPartitionAwareTimestamp(createdAtTimestamp),};this.clickHouseWriter.addToQueue(TableName.ObservationsBatchStaging,@@ -1593,6 +1600,25 @@ export class IngestionService {return timestamp ? new Date(timestamp).getTime() : Date.now();}+ /**+ * Returns a partition-aware timestamp for staging table writes.+ * If the createdAtTimestamp is within the last 3.5 minutes, returns it as-is.+ * Otherwise, returns the current timestamp to prevent updates to old partitions.+ *+ * This implements the partition locking strategy where partitions are "locked"+ * 4 minutes after creation (3.5 min + 30s buffer for writes).+ */+ private getPartitionAwareTimestamp(createdAtTimestamp: Date): number {+ const now = Date.now();+ const createdAt = createdAtTimestamp.getTime();+ const ageInMs = now - createdAt;+ const threeAndHalfMinutesInMs = 3.5 * 60 * 1000;++ // If the createdAtTimestamp is within the last 3.5 minutes, use it+ // Otherwise, use the current timestamp to avoid updating old partitions+ return ageInMs < threeAndHalfMinutesInMs ? createdAt : now;+ }+/*** Flattens a nested JSON object into path-based names and values.* For example: {foo: {bar: "baz"}} becomes: