Skip to content

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

UN-2476 [FEAT] Improved file deduplication in ETL/Task pipelines to ensure all unique files are processed (#1369)

ali36d7e8203e27
diff --git a/backend/workflow_manager/endpoint_v2/source.py b/backend/workflow_manager/endpoint_v2/source.py
index 0da12bbf1..29fe05ab9 100644
--- a/backend/workflow_manager/endpoint_v2/source.py
+++ b/backend/workflow_manager/endpoint_v2/source.py
@@ -11,6 +11,7 @@ import fsspec
from connector_processor.constants import ConnectorKeys
from connector_v2.models import ConnectorInstance
from django.core.files.uploadedfile import UploadedFile
+from django.db.models import Q
from utils.user_context import UserContext
from workflow_manager.endpoint_v2.base_connector import BaseConnector
from workflow_manager.endpoint_v2.constants import (
@@ -204,12 +205,12 @@ class SourceConnector(BaseConnector):
total_files_to_process = 0
total_matched_files = {}
- unique_file_hashes: set[str] = set()
+ unique_file_paths: set[str] = set()
for input_directory in valid_directories:
logger.debug(f"Listing files from: {input_directory}")
matched_files, count = self._get_matched_files(
- source_fs, input_directory, patterns, recursive, limit, unique_file_hashes
+ source_fs, input_directory, patterns, recursive, limit, unique_file_paths
)
self.publish_user_sys_log(f"Matched '{count}' files from '{input_directory}'")
total_matched_files.update(matched_files)
@@ -274,7 +275,7 @@ class SourceConnector(BaseConnector):
patterns: list[str],
recursive: bool,
limit: int,
- unique_file_hashes: set[str],
+ unique_file_paths: set[str],
) -> tuple[dict[str, FileHash], int]:
"""Get a dictionary of matched files based on patterns in a directory.
@@ -312,7 +313,7 @@ class SourceConnector(BaseConnector):
fs_metadata_list=fs_metadata_list,
count=count,
limit=limit,
- unique_file_hashes=unique_file_hashes,
+ unique_file_paths=unique_file_paths,
matched_files=matched_files,
patterns=patterns,
source_fs=source_fs,
@@ -325,7 +326,7 @@ class SourceConnector(BaseConnector):
fs_metadata_list: list[dict[str, Any]],
count: int,
limit: int,
- unique_file_hashes: set[str],
+ unique_file_paths: set[str],
matched_files: dict[str, FileHash],
patterns: list[str],
source_fs: UnstractFileSystem,
@@ -346,23 +347,22 @@ class SourceConnector(BaseConnector):
):
continue
- if self._should_skip_file(file_path, fs_metadata, patterns, source_fs):
- continue
-
file_hash = self._create_file_hash(
file_path=file_path,
source_fs=source_fs,
file_size=file_size,
fs_metadata=fs_metadata,
)
+ if self._should_skip_file(file_hash, patterns):
+ continue
# Skip duplicate files
- if self._is_duplicate(file_hash, unique_file_hashes):
+ if self._is_duplicate(file_hash, unique_file_paths):
msg = f"Skipping execution of duplicate file '{file_path}'"
self.workflow_log.publish_log(msg)
logger.info(msg)
continue
- self._update_unique_file_hashes(file_hash, unique_file_hashes)
+ self._update_unique_file_paths(file_hash, unique_file_paths)
matched_files[file_path] = file_hash
count += 1
@@ -370,46 +370,39 @@ class SourceConnector(BaseConnector):
def _should_skip_file(
self,
- file_path: str,
- fs_metadata: dict[str, Any],
+ file_hash: FileHash,
patterns: list[str],
- source_fs: UnstractFileSystem,
) -> bool:
"""Check if the given file should be skipped.
Args:
- file_path (str): The path of the file.
- fs_metadata (dict[str, Any]): The metadata of the file.
+ file_hash (FileHash): The hash of the file.
patterns (list[str]): The patterns to match against file names.
- source_fs (UnstractFileSystem): The file system object used for
- reading the file.
Returns:
bool: True if the file should be skipped, False otherwise.
"""
- file_name = os.path.basename(file_path)
+ file_name = os.path.basename(file_hash.file_path)
return not self._should_process_file(
file_name, patterns
) or not self._is_new_file(
- file_path=file_path,
- fs_metadata=fs_metadata,
+ file_hash=file_hash,
workflow=self.endpoint.workflow,
- source_fs=source_fs,
)
- def _is_duplicate(self, file_hash: FileHash, unique_file_hashes: set[str]) -> bool:
+ def _is_duplicate(self, file_hash: FileHash, unique_file_paths: set[str]) -> bool:
return (
- file_hash.provider_file_uuid in unique_file_hashes
- or file_hash.file_hash in unique_file_hashes
+ file_hash.file_path in unique_file_paths
+ or file_hash.file_name in unique_file_paths
)
- def _update_unique_file_hashes(
- self, file_hash: FileHash, unique_file_hashes: set[str]
+ def _update_unique_file_paths(
+ self, file_hash: FileHash, unique_file_paths: set[str]
) -> None:
- if file_hash.provider_file_uuid:
- unique_file_hashes.add(file_hash.provider_file_uuid)
- elif file_hash.file_hash:
- unique_file_hashes.add(file_hash.file_hash)
+ if file_hash.file_path:
+ unique_file_paths.add(file_hash.file_path)
+ elif file_hash.file_name:
+ unique_file_paths.add(file_hash.file_name)
def _is_directory(
self,
@@ -518,41 +511,86 @@ class SourceConnector(BaseConnector):
def _is_new_file(
self,
- file_path: str,
- fs_metadata: dict[str, Any],
+ file_hash: FileHash,
workflow: Workflow,
- source_fs: UnstractFileSystem,
) -> bool:
"""Check if the file is new or already processed."""
- file_history = self._get_file_history(fs_metadata, workflow, source_fs, file_path)
- # In case of ETL pipelines, its necessary to skip files which have
- # already been processed
- if self.use_file_history and file_history and file_history.is_completed():
- msg = f"Skipping file '{file_path}' as it has already been processed."
- self.workflow_log.publish_log(
- msg + " Clear the file markers to process it again."
- )
- logger.info(msg)
- return False
+ # Always treat the file as new if history usage is not enforced
+ if not self.use_file_history:
+ return True
- return True
+ # Always treat the file as new if neither identifier is available
+ if not file_hash.provider_file_uuid and not file_hash.file_hash:
+ return True
+
+ current_file_path = file_hash.file_path
+ file_history = self._get_file_history(file_hash=file_hash, workflow=workflow)
+
+ # No history or incomplete history means the file is new
+ if not file_history or not file_history.is_completed():
+ return True
+
+ # Note: To enforce content-only deduplication (ignoring file path), introduce a
+ # `use_content_deduplication_only` flag. If enabled, apply the check here and return False accordingly.
+
+ # Compare file paths
+ if file_history.file_path and file_history.file_path != current_file_path:
+ return True
+
+ # Default: file has been processed with the same path
+ self._log_file_skipped(current_file_path)
+ return False
+
+ def _log_file_skipped(self, file_path: str):
+ """Log a message indicating that a file has been skipped.
+
+ Args:
+ file_path (str): The path of the file.
+ """
+ msg = f"Skipping file '{file_path}' as it has already been processed."
+ self.workflow_log.publish_log(
+ msg + " Clear the file markers to process it again."
+ )
+ logger.info(msg)
def _get_file_history(
self,
- fs_metadata: dict[str, Any],
+ file_hash: FileHash,
workflow: Workflow,
- source_fs: UnstractFileSystem,
- file_path: str,
) -> FileHistory | None:
"""Retrieve file history using provider UUID or legacy cache key."""
- provider_file_uuid = source_fs.get_file_system_uuid(file_path, fs_metadata)
+ provider_file_uuid = file_hash.provider_file_uuid
+ # Note: For content-only deduplication, use the `use_content_deduplication_only` flag to fetch file history
+ # without including file path as a filter.
if provider_file_uuid:
logger.info(f"Checking file history for provider UUID: {provider_file_uuid}")
- file_history = FileHistoryHelper.get_file_history(
- workflow=workflow, provider_file_uuid=provider_file_uuid
+ return FileHistoryHelper.get_file_history(
+ workflow=workflow,
+ provider_file_uuid=provider_file_uuid,
+ file_path=file_hash.file_path,
)
- return file_history
+ return None
+
+ def _get_file_execution_by_file_hash(
+ self,
+ file_hash: FileHash,
+ workflow: Workflow,
+ ) -> WorkflowFileExecution | None:
+ """Retrieve file execution by file hash."""
+ # Build base query conditions
+ base_conditions = Q(workflow_execution__workflow=workflow)
+ content_conditions = Q()
+ if file_hash.provider_file_uuid:
+ content_conditions |= Q(provider_file_uuid=file_hash.provider_file_uuid)
+ if file_hash.file_hash:
+ content_conditions |= Q(file_hash=file_hash.file_hash)
+
+ # Filter file executions based on conditions
+ conditions = base_conditions & content_conditions
+ file_execution = WorkflowFileExecution.objects.filter(conditions).first()
+ if file_execution:
+ return file_execution
return None
def _create_file_hash(
diff --git a/backend/workflow_manager/workflow_v2/file_execution_tasks.py b/backend/workflow_manager/workflow_v2/file_execution_tasks.py
index ee3257ff9..60adb880b 100644
--- a/backend/workflow_manager/workflow_v2/file_execution_tasks.py
+++ b/backend/workflow_manager/workflow_v2/file_execution_tasks.py
@@ -445,6 +445,7 @@ class FileExecutionTasks:
# History Check Phase
if early_result := cls._check_processing_history(
destination,
+ source,
workflow_execution.workflow,
content_hash,
file_hash,
@@ -688,6 +689,7 @@ class FileExecutionTasks:
def _check_processing_history(
cls,
destination: DestinationConnector,
+ source: SourceConnector,
workflow: Workflow,
content_hash: str,
file_hash: FileHash,
@@ -700,14 +702,21 @@ class FileExecutionTasks:
# Check for existing file processing history by content hash
file_history = FileHistoryHelper.get_file_history(
- workflow=workflow, cache_key=content_hash
+ workflow=workflow, cache_key=content_hash, file_path=file_hash.file_path
)
- if not file_history:
+ if cls._is_new_file(
+ file_history=file_history,
+ file_hash=file_hash,
+ workflow=workflow,
+ ):
+ logger.info(
+ f"File '{file_hash.file_path}' is treated as *new* in workflow '{workflow}'."
+ )
return None
workflow_log.log_info(
logger=logger,
- message=f"Skipping duplicate file: '{file_hash.file_name}' in workflow '{workflow}' (content hash match)",
+ message=f"Skipping duplicate file: '{file_hash.file_path}' in workflow '{workflow}' (content hash match)",
)
# Check for provider_file_uuid consistency
@@ -735,6 +744,30 @@ class FileExecutionTasks:
metadata=file_history.metadata,
)
+ @classmethod
+ def _is_new_file(
+ cls,
+ file_history: FileHistory,
+ file_hash: FileHash,
+ workflow: Workflow,
+ ) -> bool:
+ """Check if the file is new based on file history and source configuration."""
+ # No history or incomplete history means the file is new
+ if not file_history or not file_history.is_completed():
+ return True
+
+ # Note: To enforce content-only deduplication (ignoring file path), use the `source.use_content_deduplication_only` flag
+ # If enabled, skip the file path comparison and return False here to treat the file as already processed.
+
+ if file_history.file_path and file_hash.file_path != file_history.file_path:
+ logger.info(
+ f"[File Path Mismatch] Existing file path '{file_history.file_path}' does not match expected path "
+ f"'{file_hash.file_path}' for file '{file_hash.file_name}' in workflow '{workflow}'. Marking as new."
+ )
+ return True
+
+ return False
+
@classmethod
def _execute_workflow_steps(
cls,
@@ -859,9 +892,10 @@ class FileExecutionTasks:
try:
if destination.use_file_history:
+ file_path = file_hash.file_path if not destination.is_api else None
# Collect metadata from file history if available
file_history = FileHistoryHelper.get_file_history(
- workflow=workflow, cache_key=file_hash.file_hash
+ workflow=workflow, cache_key=file_hash.file_hash, file_path=file_path
)
else:
file_history = None
@@ -886,12 +920,12 @@ class FileExecutionTasks:
processing_error=processing_error,
):
FileHistoryHelper.create_file_history(
+ is_api=destination.is_api,
file_hash=file_hash,
workflow=workflow,
status=ExecutionStatus.COMPLETED,
result=output_result,
metadata=execution_metadata,
- file_name=file_hash.file_name,
)
except Exception as e:
error_msg = f"Final output processing failed: {str(e)}"
diff --git a/backend/workflow_manager/workflow_v2/file_history_helper.py b/backend/workflow_manager/workflow_v2/file_history_helper.py
index b4632a94b..0761f56a7 100644
--- a/backend/workflow_manager/workflow_v2/file_history_helper.py
+++ b/backend/workflow_manager/workflow_v2/file_history_helper.py
@@ -1,9 +1,11 @@
import logging
from typing import Any
+from django.db.models import Q
from django.db.utils import IntegrityError
from workflow_manager.endpoint_v2.dto import FileHash
+from workflow_manager.file_execution.models import WorkflowFileExecution
from workflow_manager.workflow_v2.enums import ExecutionStatus
from workflow_manager.workflow_v2.models.file_history import FileHistory
from workflow_manager.workflow_v2.models.workflow import Workflow
@@ -14,17 +16,21 @@ logger = logging.getLogger(__name__)
class FileHistoryHelper:
"""A helper class for managing file history related operations."""
- @staticmethod
+ @classmethod
def get_file_history(
+ cls,
workflow: Workflow,
cache_key: str | None = None,
provider_file_uuid: str | None = None,
+ file_path: str | None = None,
) -> FileHistory | None:
"""Retrieve a file history record based on the cache key.
Args:
+ workflow (Workflow): The workflow associated with the file history.
cache_key (Optional[str]): The cache key to search for.
provider_file_uuid (Optional[str]): The provider file UUID to search for.
+ file_path (Optional[str]): The file path to search for.
Returns:
Optional[FileHistory]: The matching file history record, if found.
@@ -35,20 +41,83 @@ class FileHistoryHelper:
f"while fetching file history for {workflow}"
)
return None
+ filters = Q(workflow=workflow)
+ if cache_key:
+ filters &= Q(cache_key=cache_key)
+ elif provider_file_uuid:
+ filters &= Q(provider_file_uuid=provider_file_uuid)
+
try:
- if not cache_key:
- return FileHistory.objects.get(
- provider_file_uuid=provider_file_uuid, workflow=workflow
+ if file_path:
+ return FileHistory.objects.get(filters & Q(file_path=file_path))
+ return FileHistory.objects.get(filters & Q(file_path__isnull=True))
+ except FileHistory.DoesNotExist:
+ if file_path:
+ # Legacy fallback: file_path was not stored in older file history records; fallback ensures backward compatibility.
+ return cls._fallback_file_history_lookup(
+ workflow=workflow, filters=filters, cache_key=cache_key
)
- return FileHistory.objects.get(cache_key=cache_key, workflow=workflow)
+ logger.info(
+ f"File history not found for cache key: {cache_key}, "
+ f"provider_file_uuid: {provider_file_uuid}, "
+ f"file_path={file_path}, workflow={workflow}"
+ )
+ return None
+
+ @classmethod
+ def _fallback_file_history_lookup(
+ cls,
+ workflow: Workflow,
+ filters: Q,
+ cache_key: str | None,
+ ) -> FileHistory | None:
+ """Handle fallback for workflows where file_path was not stored (e.g., API deployments or older records)."""
+ try:
+ file_history: FileHistory = FileHistory.objects.get(
+ filters & Q(file_path__isnull=True)
+ )
+ file_execution = cls.get_file_execution_by_file_hash(
+ workflow=workflow,
+ cache_key=file_history.cache_key,
+ provider_file_uuid=file_history.provider_file_uuid,
+ )
+ if file_execution and file_execution.file_path:
+ file_history.file_path = file_execution.file_path
+ file_history.save(update_fields=["file_path"])
+ logger.info(
+ f"[FileHistory] Backfilled file_path {file_history.file_path} for file history (workflow={workflow}, cache_key={cache_key})"
+ )
+ return file_history
except FileHistory.DoesNotExist:
- logger.debug(
+ logger.info(
f"File history not found for cache key: {cache_key}, "
- f"provider_file_uuid: {provider_file_uuid} while fetching "
- f"file history for {workflow}"
+ f"workflow={workflow}"
)
return None
+ @classmethod
+ def get_file_execution_by_file_hash(
+ cls,
+ workflow: Workflow,
+ cache_key: str | None = None,
+ provider_file_uuid: str | None = None,
+ ) -> WorkflowFileExecution | None:
+ """Retrieve file execution by file hash."""
+ # Build base query conditions
+ base_conditions = Q(workflow_execution__workflow=workflow)
+ content_conditions = Q()
+ if cache_key:
+ content_conditions |= Q(cache_key=cache_key)
+ if provider_file_uuid:
+ content_conditions |= Q(provider_file_uuid=provider_file_uuid)
+
+ # Filter file executions based on conditions
+ conditions = base_conditions & content_conditions
+ file_execution = WorkflowFileExecution.objects.filter(conditions).first()
+ if file_execution:
+ return file_execution
+ return None
+
@staticmethod
def create_file_history(
file_hash: FileHash,
@@ -57,17 +126,20 @@ class FileHistoryHelper:
result: Any,
metadata: str | None,
error: str | None = None,
- file_name: str | None = None,
+ is_api: bool = False,
) -> None:
"""Create a new file history record.
Args:
- cache_key (str): The cache key for the file.
+ file_hash (FileHash): The file hash for the file.
workflow (Workflow): The associated workflow.
status (ExecutionStatus): The execution status.
result (Any): The result from the execution.
+ metadata (str | None): The metadata from the execution.
+ error (str | None): The error from the execution.
"""
try:
+ file_path = file_hash.file_path if not is_api else None
FileHistory.objects.create(
workflow=workflow,
cache_key=file_hash.file_hash,
@@ -76,11 +148,12 @@ class FileHistoryHelper:
result=str(result),
metadata=str(metadata) if metadata else "",
error=str(error) if error else "",
+ file_path=file_path,
)
except IntegrityError as e:
# TODO: Need to find why duplicate insert is coming
logger.warning(
- f"Trying to insert duplication data for filename {file_name} "
+ f"Trying to insert duplication data for filename {file_hash.file_name} "
f"for workflow {workflow}. Error: {str(e)} with metadata {metadata}",
)
diff --git a/backend/workflow_manager/workflow_v2/migrations/0014_remove_filehistory_unique_workflow_cachekey_and_more.py b/backend/workflow_manager/workflow_v2/migrations/0014_remove_filehistory_unique_workflow_cachekey_and_more.py
new file mode 100644
index 000000000..747ee6f56
--- /dev/null
+++ b/backend/workflow_manager/workflow_v2/migrations/0014_remove_filehistory_unique_workflow_cachekey_and_more.py
@@ -0,0 +1,67 @@
+# Generated by Django 4.2.1 on 2025-06-18 04:45
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("workflow_v2", "0013_remove_workflowexecution_workflow_id_and_more"),
+ ]
+
+ operations = [
+ migrations.RemoveConstraint(
+ model_name="filehistory",
+ name="unique_workflow_cacheKey",
+ ),
+ migrations.RemoveConstraint(
+ model_name="filehistory",
+ name="unique_workflow_providerFileUUID",
+ ),
+ migrations.AddField(
+ model_name="filehistory",
+ name="file_path",
+ field=models.CharField(
+ db_comment="Full Path of the file", max_length=1000, null=True
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="filehistory",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(
+ ("cache_key__isnull", False), ("file_path__isnull", True)
+ ),
+ fields=("workflow", "cache_key"),
+ name="unique_workflow_cacheKey",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="filehistory",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(
+ ("file_path__isnull", True), ("provider_file_uuid__isnull", False)
+ ),
+ fields=("workflow", "provider_file_uuid"),
+ name="unique_workflow_providerFileUUID",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="filehistory",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(
+ ("cache_key__isnull", False), ("file_path__isnull", False)
+ ),
+ fields=("workflow", "cache_key", "file_path"),
+ name="unique_workflow_cacheKey_with_filePath",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="filehistory",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(
+ ("file_path__isnull", False), ("provider_file_uuid__isnull", False)
+ ),
+ fields=("workflow", "provider_file_uuid", "file_path"),
+ name="unique_workflow_providerFileUUID_with_filePath",
+ ),
+ ),
+ ]
diff --git a/backend/workflow_manager/workflow_v2/models/file_history.py b/backend/workflow_manager/workflow_v2/models/file_history.py
index 85e9090fb..d2ccfcc87 100644
--- a/backend/workflow_manager/workflow_v2/models/file_history.py
+++ b/backend/workflow_manager/workflow_v2/models/file_history.py
@@ -1,12 +1,14 @@
import uuid
from django.db import models
+from django.db.models import Q
from utils.models.base_model import BaseModel
from workflow_manager.workflow_v2.enums import ExecutionStatus
from workflow_manager.workflow_v2.models.workflow import Workflow
HASH_LENGTH = 64
+FILE_PATH_LENGTH = 1000
class FileHistory(BaseModel):
@@ -45,20 +47,36 @@ class FileHistory(BaseModel):
result = models.TextField(blank=True, db_comment="Result from execution")
metadata = models.TextField(blank=True, db_comment="MetaData from execution")
+ file_path = models.CharField(
+ max_length=FILE_PATH_LENGTH, null=True, db_comment="Full Path of the file"
+ )
+
class Meta:
verbose_name = "File History"
verbose_name_plural = "File Histories"
db_table = "file_history"
constraints = [
+ # Legacy behavior: file_path is not present or is null
models.UniqueConstraint(
fields=["workflow", "cache_key"],
name="unique_workflow_cacheKey",
- condition=models.Q(cache_key__isnull=False),
+ condition=Q(file_path__isnull=True, cache_key__isnull=False),
),
models.UniqueConstraint(
fields=["workflow", "provider_file_uuid"],
name="unique_workflow_providerFileUUID",
- condition=models.Q(provider_file_uuid__isnull=False),
+ condition=Q(file_path__isnull=True, provider_file_uuid__isnull=False),
+ ),
+ # New behavior: file_path exists and is not null
+ models.UniqueConstraint(
+ fields=["workflow", "cache_key", "file_path"],
+ name="unique_workflow_cacheKey_with_filePath",
+ condition=Q(file_path__isnull=False, cache_key__isnull=False),
+ ),
+ models.UniqueConstraint(
+ fields=["workflow", "provider_file_uuid", "file_path"],
+ name="unique_workflow_providerFileUUID_with_filePath",
+ condition=Q(file_path__isnull=False, provider_file_uuid__isnull=False),
),
]