Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

fix for filehash missing during worker restart (#1353)

aliaea326384466
diff --git a/backend/workflow_manager/endpoint_v2/dto.py b/backend/workflow_manager/endpoint_v2/dto.py
index d2365a18b..a6bab30de 100644
--- a/backend/workflow_manager/endpoint_v2/dto.py
+++ b/backend/workflow_manager/endpoint_v2/dto.py
@@ -38,6 +38,10 @@ class FileHash:
"file_number": self.file_number,
}
+ def to_serialized_json(self) -> str:
+ """Serialize the FileHash instance to a JSON string."""
+ return json.dumps(self.to_json())
+
@staticmethod
def from_json(json_str_or_dict: Any) -> "FileHash":
"""Deserialize a JSON string or dictionary to a FileHash instance."""
diff --git a/backend/workflow_manager/workflow_v2/file_execution_tasks.py b/backend/workflow_manager/workflow_v2/file_execution_tasks.py
index a6240f514..ee3257ff9 100644
--- a/backend/workflow_manager/workflow_v2/file_execution_tasks.py
+++ b/backend/workflow_manager/workflow_v2/file_execution_tasks.py
@@ -28,6 +28,7 @@ from unstract.core.file_execution_tracker import (
FileExecutionStageStatus,
FileExecutionStatusTracker,
)
+from unstract.core.tool_execution_status import ToolExecutionData, ToolExecutionTracker
from unstract.workflow_execution.enums import LogComponent, LogStage, LogState
from unstract.workflow_execution.exceptions import StopExecution
from workflow_manager.endpoint_v2.destination import DestinationConnector
@@ -142,11 +143,14 @@ class FileExecutionTasks:
- execution_id: ID of execution service
- single_step: Whether to process in single step mode
"""
+ celery_task_id = self.request.id
file_batch_data = FileBatchData.from_dict(file_batch_data)
logger.debug(f"Batch data received: {file_batch_data}")
file_data = file_batch_data.file_data
- logger.info(f"File processing context {file_data}")
+ logger.info(
+ f"[Celery Task: {celery_task_id}] Processing file with context: {file_data}"
+ )
execution_id = file_data.execution_id
workflow_id = file_data.workflow_id
@@ -176,7 +180,9 @@ class FileExecutionTasks:
for file_number, (file_name, file_hash_dict) in enumerate(
file_batch_data.files, 1
):
- logger.info(f"[{file_number}/{total_files}] Processing file '{file_name}'")
+ logger.info(
+ f"[{celery_task_id}][{file_number}/{total_files}] Processing file '{file_name}'"
+ )
file_hash = FileHash(
file_path=file_hash_dict.get("file_path"),
file_name=file_hash_dict.get("file_name"),
@@ -364,6 +370,7 @@ class FileExecutionTasks:
execution_id=str(workflow_execution.id),
file_execution_id=str(workflow_file_execution.id),
organization_id=str(workflow_execution.workflow.organization_id),
+ file_hash=file_hash,
)
# Check if file execution is already in progress
@@ -375,6 +382,11 @@ class FileExecutionTasks:
)
# Not required to prepare file again
# Not required to check processing history again
+
+ # Set file hash from file execution data
+ file_hash = FileHash.from_json(file_execution_data.file_hash)
+ logger.info(f"File hash {file_hash} set from file execution data")
+
if stage.is_before(FileExecutionStage.COMPLETED):
# Core Execution Phase
execution_result = cls._execute_workflow_steps(
@@ -421,6 +433,15 @@ class FileExecutionTasks:
workflow_execution,
)
+ # Update file execution tracker with updated file hash
+ cls._update_file_execution_tracker(
+ execution_id=str(workflow_execution.id),
+ file_execution_id=str(workflow_file_execution.id),
+ stage=FileExecutionStage.INITIALIZATION,
+ status=FileExecutionStageStatus.IN_PROGRESS,
+ file_hash=file_hash,
+ )
+
# History Check Phase
if early_result := cls._check_processing_history(
destination,
@@ -500,6 +521,7 @@ class FileExecutionTasks:
execution_id: str,
file_execution_id: str,
organization_id: str,
+ file_hash: FileHash,
) -> FileExecutionData:
# Initialize file execution tracker
file_execution_tracker = FileExecutionStatusTracker()
@@ -513,6 +535,7 @@ class FileExecutionTasks:
organization_id=str(organization_id),
stage_status=file_execution_stage_data,
status_history=[],
+ file_hash=file_hash.to_serialized_json(),
)
if not file_execution_tracker.exists(execution_id, file_execution_id):
file_execution_tracker.set_data(file_execution_data)
@@ -526,16 +549,27 @@ class FileExecutionTasks:
return file_execution_data
@classmethod
- def _mark_file_execution_tracker_finalization_status(
+ def _update_file_execution_tracker(
cls,
execution_id: str,
file_execution_id: str,
+ stage: FileExecutionStage,
status: FileExecutionStageStatus,
error: str | None = None,
+ file_hash: FileHash | None = None,
) -> None:
+ if file_hash:
+ # Convert file hash to serialized json for storage
+ file_hash = file_hash.to_serialized_json()
+
+ ttl_in_second = (
+ settings.FILE_EXECUTION_TRACKER_COMPLETED_TTL_IN_SECOND
+ if stage == FileExecutionStage.COMPLETED
+ else None
+ )
file_execution_tracker = FileExecutionStatusTracker()
stage_data = FileExecutionStageData(
- stage=FileExecutionStage.FINALIZATION,
+ stage=stage,
status=status,
error=error,
)
@@ -543,34 +577,24 @@ class FileExecutionTasks:
execution_id=execution_id,
file_execution_id=file_execution_id,
stage_status=stage_data,
+ ttl_in_second=ttl_in_second,
+ file_hash=file_hash,
)
@classmethod
- def _mark_file_execution_tracker_completed_status(
+ def delete_tool_execution_tracker(
cls,
execution_id: str,
file_execution_id: str,
- status: FileExecutionStageStatus,
- error: str | None = None,
) -> None:
- logger.info(
- f"Marking file execution tracker completed status for execution_id: {execution_id}, file_execution_id: {file_execution_id}, stage: {FileExecutionStage.COMPLETED.value}, status: {status.value}, error: {error}"
- )
- # This is the cache ttl for completed file execution to prevent long term cache
- COMPLETED_EXECUTION_CACHE_TTL_IN_SECOND = (
- settings.FILE_EXECUTION_TRACKER_COMPLETED_TTL_IN_SECOND
- )
- file_execution_tracker = FileExecutionStatusTracker()
- stage_data = FileExecutionStageData(
- stage=FileExecutionStage.COMPLETED,
- status=status,
- error=error,
- )
- file_execution_tracker.update_stage_status(
+ tool_execution_tracker = ToolExecutionTracker()
+ tool_execution_data = ToolExecutionData(
execution_id=execution_id,
file_execution_id=file_execution_id,
- stage_status=stage_data,
- ttl_in_second=COMPLETED_EXECUTION_CACHE_TTL_IN_SECOND,
+ )
+ tool_execution_tracker.delete_status(tool_execution_data=tool_execution_data)
+ logger.info(
+ f"Deleted tool execution tracker for execution_id: {execution_id}, file_execution_id: {file_execution_id}"
)
@classmethod
@@ -941,9 +965,10 @@ class FileExecutionTasks:
if not error
else FileExecutionStageStatus.FAILED
)
- cls._mark_file_execution_tracker_finalization_status(
+ cls._update_file_execution_tracker(
execution_id=str(workflow_file_execution.workflow_execution.id),
file_execution_id=str(workflow_file_execution.id),
+ stage=FileExecutionStage.FINALIZATION,
status=file_execution_tracker_status,
error=error,
)
@@ -990,11 +1015,19 @@ class FileExecutionTasks:
if not error
else FileExecutionStageStatus.FAILED
)
- cls._mark_file_execution_tracker_completed_status(
+ logger.info(
+ f"Marking file execution tracker completed status for execution_id: {workflow_execution.id}, file_execution_id: {workflow_file_execution.id}, stage: {FileExecutionStage.COMPLETED.value}, status: {status.value}, error: {error}"
+ )
+ cls._update_file_execution_tracker(
execution_id=str(workflow_execution.id),
file_execution_id=str(workflow_file_execution.id),
+ stage=FileExecutionStage.COMPLETED,
status=status,
error=error,
)
+ cls.delete_tool_execution_tracker(
+ execution_id=str(workflow_execution.id),
+ file_execution_id=str(workflow_file_execution.id),
+ )
return final_result
diff --git a/unstract/core/src/unstract/core/file_execution_tracker.py b/unstract/core/src/unstract/core/file_execution_tracker.py
index cdd3ef1de..e6eb01e43 100644
--- a/unstract/core/src/unstract/core/file_execution_tracker.py
+++ b/unstract/core/src/unstract/core/file_execution_tracker.py
@@ -63,6 +63,7 @@ class FileExecutionField:
STAGE_STATUS = "stage_status"
TOOL_CONTAINER_NAME = "tool_container_name"
STATUS_HISTORY = "status_history"
+ FILE_HASH = "file_hash"
@dataclass
@@ -100,6 +101,7 @@ class FileExecutionData:
status_history: list[FileExecutionStageData]
tool_container_name: str | None = None
error: str | None = None
+ file_hash: str | None = None # File hash in serialized format
def __post_init__(self):
self.validate()
@@ -124,10 +126,22 @@ class FileExecutionData:
),
FileExecutionField.TOOL_CONTAINER_NAME: self.tool_container_name,
FileExecutionField.ERROR: self.error,
+ FileExecutionField.FILE_HASH: self.file_hash,
}
# Remove any keys with value None (Redis doesn't support None in HSET)
return {k: v for k, v in data.items() if v is not None}
+ def __str__(self) -> str:
+ return (
+ f"Execution ID: {self.execution_id}, "
+ f"File Execution ID: {self.file_execution_id}, "
+ f"Organization ID: {self.organization_id}, "
+ f"Stage Status: {self.stage_status}, "
+ f"Status History: {self.status_history}, "
+ f"Tool Container Name: {self.tool_container_name}, "
+ f"Error: {self.error}, "
+ )
+
class FileExecutionStatusTracker:
"""File execution status tracker.
@@ -177,7 +191,7 @@ class FileExecutionStatusTracker:
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)
- logger.info(f"Setting file execution data for {key}: {data.to_serializable()}")
+ logger.info(f"Setting file execution data for {key}: {data}")
self.redis_client.hset(key, mapping=data.to_serializable())
ttl = ttl_in_second or self.CACHE_TTL_IN_SECOND
logger.info(f"Setting file execution data for {key} to expire in {ttl} seconds")
@@ -194,6 +208,7 @@ class FileExecutionStatusTracker:
file_execution_id: str,
stage_status: FileExecutionStageData,
ttl_in_second: int | None = None,
+ file_hash: str | None = None,
) -> None:
key = self.get_cache_key(execution_id, file_execution_id)
@@ -206,6 +221,7 @@ class FileExecutionStatusTracker:
organization_id="",
stage_status=stage_status,
status_history=[stage_status],
+ file_hash=file_hash,
)
)
@@ -240,6 +256,10 @@ class FileExecutionStatusTracker:
] + existing_data.status_history
# Update error
existing_data.error = stage_status.error or existing_data.error
+
+ # Update file hash
+ existing_data.file_hash = file_hash or existing_data.file_hash
+
self.set_data(existing_data, ttl_in_second)
def update_tool_container_name(
@@ -299,6 +319,7 @@ class FileExecutionStatusTracker:
for entry in status_history_list
],
error=data.get(FileExecutionField.ERROR) or None,
+ file_hash=data.get(FileExecutionField.FILE_HASH),
)
def delete_data(self, execution_id: str, file_execution_id: str) -> None:
diff --git a/unstract/core/src/unstract/core/tool_execution_status.py b/unstract/core/src/unstract/core/tool_execution_status.py
index edd561f3c..cf29d32f0 100644
--- a/unstract/core/src/unstract/core/tool_execution_status.py
+++ b/unstract/core/src/unstract/core/tool_execution_status.py
@@ -52,6 +52,12 @@ class ToolExecutionTracker:
os.environ.get("TOOL_EXECUTION_CACHE_TTL_IN_SECOND", 60 * 60 * 24)
)
+ TOOL_EXECUTION_TRACKER_COMPLETED_TTL_IN_SECOND = int(
+ os.environ.get(
+ "TOOL_EXECUTION_TRACKER_COMPLETED_TTL_IN_SECOND", CACHE_TTL_IN_SECOND
+ )
+ )
+
def __init__(self):
self.redis_client = redis.Redis(
host=os.environ.get("REDIS_HOST"),
@@ -172,3 +178,20 @@ class ToolExecutionTracker:
self.redis_client.delete(self.get_cache_key(tool_execution_data))
except ToolExecutionValueException:
return
+
+ def update_ttl(
+ self, tool_execution_data: ToolExecutionData, ttl_in_second: int
+ ) -> None:
+ """Update the TTL of a tool execution.
+
+ Args:
+ tool_execution_data (ToolExecutionData): Status of the tool execution
+ ttl_in_second (int): TTL in seconds
+ """
+ try:
+ tool_execution_data.validate()
+ self.redis_client.expire(
+ self.get_cache_key(tool_execution_data), ttl_in_second
+ )
+ except ToolExecutionValueException:
+ return
diff --git a/unstract/tool-sandbox/src/unstract/tool_sandbox/helper.py b/unstract/tool-sandbox/src/unstract/tool_sandbox/helper.py
index 89b3308f4..fbb72eb87 100644
--- a/unstract/tool-sandbox/src/unstract/tool_sandbox/helper.py
+++ b/unstract/tool-sandbox/src/unstract/tool_sandbox/helper.py
@@ -536,4 +536,10 @@ class ToolSandboxHelper:
return str(error)
finally:
# Delete the status from cache since it is no longer needed
- tool_execution_tracker.delete_status(tool_execution_data)
+ # Note: Instead of deleting the status, we are updating the TTL to a lower value
+ # to avoid deleting the status from cache when the file is still processing
+ # TODO: Remove this if not required since it delete after completion
+ tool_execution_tracker.update_ttl(
+ tool_execution_data,
+ ToolExecutionTracker.TOOL_EXECUTION_TRACKER_COMPLETED_TTL_IN_SECOND,
+ )