LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
adding redis lock while DESTINATION_PROCESS stage
ali6867e0381a15
diff --git a/unstract/core/src/unstract/core/file_execution_tracker.py b/unstract/core/src/unstract/core/file_execution_tracker.pyindex f432b3534..d447c7648 100644--- a/unstract/core/src/unstract/core/file_execution_tracker.py+++ b/unstract/core/src/unstract/core/file_execution_tracker.py@@ -190,6 +190,10 @@ class FileExecutionStatusTracker:def get_cache_key(self, execution_id: str, file_execution_id: str) -> str:return f"file_execution:{execution_id}:{file_execution_id}"+ def get_destination_lock_key(self, execution_id: str, file_execution_id: str) -> str:+ """Get the Redis key for destination processing lock."""+ return f"file_execution:{execution_id}:{file_execution_id}:destination_lock"+def set_data(self, data: FileExecutionData, ttl_in_second: int | None = None) -> None:data.validate()key = self.get_cache_key(data.execution_id, data.file_execution_id)diff --git a/workers/sample.env b/workers/sample.envindex 311b72329..8a52ed4d7 100644--- a/workers/sample.env+++ b/workers/sample.env@@ -257,7 +257,12 @@ MAX_PARALLEL_FILE_BATCHES=1# File Execution TTL ConfigurationFILE_EXECUTION_TRACKER_TTL_IN_SECOND=18000FILE_EXECUTION_TRACKER_COMPLETED_TTL_IN_SECOND=300-DESTINATION_PROCESSING_LOCK_TTL_IN_SECOND=300++# Destination Processing TTL Configuration+DESTINATION_PROCESSING_STAGE_TTL_IN_SECOND=600+# Actual Redis lock TTL+DESTINATION_PROCESSING_LOCK_TTL_IN_SECOND=10+EXECUTION_RESULT_TTL_SECONDS=86400EXECUTION_CACHE_TTL_SECONDS=86400INSTANT_WF_POLLING_TIMEOUT=300diff --git a/workers/shared/workflow/destination_connector.py b/workers/shared/workflow/destination_connector.pyindex 8d4980e3e..4a7828efe 100644--- a/workers/shared/workflow/destination_connector.py+++ b/workers/shared/workflow/destination_connector.py@@ -16,6 +16,7 @@ import base64import jsonimport osimport time+import uuidfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Optional@@ -314,29 +315,32 @@ class WorkerDestinationConnector:def _check_and_acquire_destination_lock(self, exec_ctx: ExecutionContext, file_ctx: FileContext) -> bool:- """Check if destination already processed and atomically acquire lock.+ """Check if destination already processed and atomically acquire lock using Redis SET NX.Returns:bool: True if lock acquired successfully, False if already processed (duplicate)- This method provides duplicate prevention using FileExecutionStatusTracker:- 1. Check if DESTINATION_PROCESSING or COMPLETED stage already exists+ This method provides duplicate prevention using Redis SET NX for atomic lock:+ 1. Check if DESTINATION_PROCESSING, FINALIZATION, or COMPLETED stage already exists2. If yes, this is a duplicate attempt (e.g., from worker restart) -> skip- 3. If no, atomically set DESTINATION_PROCESSING stage (acts as distributed lock)- 4. If FileExecutionStageException raised, another worker has the lock -> skip+ 3. If no, atomically acquire lock using Redis SET ... NX (single atomic operation)+ 4. If lock acquisition succeeds, set DESTINATION_PROCESSING stage with longer TTL+ 5. If lock acquisition fails, another worker has the lock -> skip"""try:tracker = FileExecutionStatusTracker()- # Check if destination already processed+ # Check if destination already processed or in progressexisting_data = tracker.get_data(exec_ctx.execution_id, exec_ctx.file_execution_id)if existing_data:current_stage = existing_data.stage_status.stage+ # Check for DESTINATION_PROCESSING, FINALIZATION, or COMPLETEDif current_stage in [FileExecutionStage.DESTINATION_PROCESSING,+ FileExecutionStage.FINALIZATION,FileExecutionStage.COMPLETED,]:logger.warning(@@ -350,16 +354,51 @@ class WorkerDestinationConnector:)return False # Duplicate detected- # Atomically acquire lock by setting DESTINATION_PROCESSING stage- # This prevents race conditions - first worker to set this stage wins- # Use shorter TTL for lock to prevent deadlock if worker crashes (10 min default)+ # Atomically acquire lock using Redis SET NX+ # Use helper method for consistent lock key format+ lock_key = tracker.get_destination_lock_key(+ exec_ctx.execution_id, exec_ctx.file_execution_id+ )+ lock_token = str(uuid.uuid4()) # Unique token for debugging++ # Get TTL values from environmentLOCK_TTL = int(- os.environ.get("DESTINATION_PROCESSING_LOCK_TTL_IN_SECOND", 600)+ os.environ.get("DESTINATION_PROCESSING_LOCK_TTL_IN_SECOND", 120))- try:- logger.info(- f"Acquiring destination processing lock for file '{file_ctx.file_name}' with TTL {LOCK_TTL}s"+ STAGE_TTL = int(+ os.environ.get("DESTINATION_PROCESSING_STAGE_TTL_IN_SECOND", 600)+ )++ logger.info(+ f"Attempting to acquire destination lock for file '{file_ctx.file_name}' "+ f"(lock_key={lock_key}, lock_ttl={LOCK_TTL}s, stage_ttl={STAGE_TTL}s)"+ )++ # Use Redis SET NX (Set if Not eXists) for true atomic lock acquisition+ # Returns True if key was set (lock acquired), False if key already exists+ lock_acquired = tracker.redis_client.set(+ lock_key, lock_token, nx=True, ex=LOCK_TTL+ )++ if not lock_acquired:+ # Another worker already has the lock+ logger.warning(+ f"Lock acquisition failed for file '{file_ctx.file_name}': "+ f"Another worker holds the lock. Skipping duplicate processing."+ )+ log_file_info(+ exec_ctx.workflow_log,+ exec_ctx.file_execution_id,+ f"File '{file_ctx.file_name}' destination lock held by another worker - skipping duplicate",)+ return False++ # Lock acquired successfully - now set DESTINATION_PROCESSING stage+ logger.info(+ f"Lock acquired successfully for file '{file_ctx.file_name}' (token={lock_token})"+ )++ try:tracker.update_stage_status(exec_ctx.execution_id,exec_ctx.file_execution_id,@@ -367,26 +406,24 @@ class WorkerDestinationConnector:stage=FileExecutionStage.DESTINATION_PROCESSING,status=FileExecutionStageStatus.IN_PROGRESS,),- ttl_in_second=LOCK_TTL,+ ttl_in_second=STAGE_TTL, # Use longer TTL for stage tracker)logger.info(- f"Successfully acquired destination processing lock for file '{file_ctx.file_name}'"+ f"Successfully set DESTINATION_PROCESSING stage for file '{file_ctx.file_name}' "+ f"with stage TTL {STAGE_TTL}s")- return True # Lock acquired successfully+ return True # Lock acquired and stage set successfullyexcept FileExecutionStageException as stage_error:- # Another worker already acquired the lock (stage validation failed)- logger.warning(- f"Race condition detected: Another worker acquired destination lock "- f"for file '{file_ctx.file_name}'. Skipping duplicate processing. "- f"Error: {str(stage_error)}"- )- log_file_info(- exec_ctx.workflow_log,- exec_ctx.file_execution_id,- f"File '{file_ctx.file_name}' destination lock acquired by another worker - skipping duplicate",+ # Stage transition failed (shouldn't happen after lock acquired, but handle it)+ logger.error(+ f"Failed to set DESTINATION_PROCESSING stage after lock acquisition "+ f"for file '{file_ctx.file_name}': {str(stage_error)}. "+ f"Releasing lock.")- return False # Another worker has the lock+ # Release the lock since we failed to set the stage+ tracker.redis_client.delete(lock_key)+ return Falseexcept Exception as e:# If Redis fails or other unexpected error, log but allow processing to continuediff --git a/workers/shared/workflow/execution/service.py b/workers/shared/workflow/execution/service.pyindex c16baf1fe..abf267045 100644--- a/workers/shared/workflow/execution/service.py+++ b/workers/shared/workflow/execution/service.py@@ -250,6 +250,7 @@ class WorkerWorkflowExecutionService:logger.info(f"Marked destination processing as successful for {file_name}")+except Exception as tracker_error:logger.warning(f"Failed to mark destination processing success: {tracker_error}"@@ -269,6 +270,22 @@ class WorkerWorkflowExecutionService:f"TIMING: Destination processing END for {file_name} at {destination_end_time:.6f} (took {destination_end_time - destination_start_time:.3f}s)")+ # Always clean up the destination processing lock, whether success or failure+ if workflow_file_execution_id:+ try:+ tracker = FileExecutionStatusTracker()+ lock_key = tracker.get_destination_lock_key(+ execution_id, workflow_file_execution_id+ )+ tracker.redis_client.delete(lock_key)+ logger.debug(+ f"Cleaned up destination lock for '{file_name}' (lock_key={lock_key})"+ )+ except Exception as lock_cleanup_error:+ logger.warning(+ f"Failed to clean up destination lock: {lock_cleanup_error}"+ )+# Step 4: Build Final Resultfinal_time = time.time()execution_time = final_time - start_time