Skip to content

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

feat: Date range preset based filtering for execution / file_execution (#1173)

Chandrasekharan M27b5123cf8c4
diff --git a/backend/usage_v2/dto.py b/backend/usage_v2/dto.py
deleted file mode 100644
index 67170ada2..000000000
--- a/backend/usage_v2/dto.py
+++ /dev/null
@@ -1,16 +0,0 @@
-import datetime
-from dataclasses import dataclass
-
-
-@dataclass
-class DateRange:
- """
- Represents a validated date range with start and end dates.
-
- Attributes:
- start_date: Beginning of the date range
- end_date: End of the date range
- """
-
- start_date: datetime
- end_date: datetime
diff --git a/backend/usage_v2/enums.py b/backend/usage_v2/enums.py
deleted file mode 100644
index 1e9274af5..000000000
--- a/backend/usage_v2/enums.py
+++ /dev/null
@@ -1,35 +0,0 @@
-from datetime import timedelta
-from enum import Enum
-
-from django.utils import timezone
-from usage_v2.exceptions import InvalidDateRange
-
-
-class DateRangePresets(Enum):
- LAST_7_DAYS = ("last_7_days", 7, "Last 7 Days")
- LAST_30_DAYS = ("last_30_days", 30, "Last 30 Days")
-
- def __init__(self, key: str, days: int, display_name: str):
- self.key = key
- self.days = days
- self.display_name = display_name
-
- def get_start_date(self):
- return timezone.now() - timedelta(days=self.days)
-
- def get_end_date(self):
- return timezone.now()
-
- def get_date_range(self):
- return self.get_start_date(), self.get_end_date()
-
- @classmethod
- def from_value(cls, value: str):
- try:
- return next(preset for preset in cls if preset.key == value)
- except StopIteration:
- valid_values = [preset.key for preset in cls]
- raise InvalidDateRange(
- f"Invalid date range value: '{value}'. "
- f"Valid values are: {', '.join(valid_values)}"
- )
diff --git a/backend/usage_v2/filter.py b/backend/usage_v2/filter.py
index 72e7ff37a..0a895a095 100644
--- a/backend/usage_v2/filter.py
+++ b/backend/usage_v2/filter.py
@@ -3,7 +3,7 @@ from typing import Any
from django.db.models import Q, QuerySet
from django_filters import rest_framework as filters
from usage_v2.models import Usage, UsageType
-from usage_v2.utils import DateTimeProcessor
+from utils.date import DateTimeProcessor
from workflow_manager.file_execution.models import WorkflowFileExecution
from workflow_manager.workflow_v2.models.execution import WorkflowExecution
diff --git a/backend/usage_v2/views.py b/backend/usage_v2/views.py
index 03cffc800..a2d929a1d 100644
--- a/backend/usage_v2/views.py
+++ b/backend/usage_v2/views.py
@@ -9,7 +9,7 @@ from rest_framework.filters import OrderingFilter
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from usage_v2.filter import UsageFilter
-from usage_v2.utils import DateTimeProcessor
+from utils.date import DateTimeProcessor
from utils.pagination import CustomPagination
from utils.user_context import UserContext
diff --git a/backend/utils/date/__init__.py b/backend/utils/date/__init__.py
index faf94e125..67b76dc70 100644
--- a/backend/utils/date/__init__.py
+++ b/backend/utils/date/__init__.py
@@ -1,2 +1,5 @@
from .constants import DateRangeKeys # noqa: F401
+from .enums import DateRangePresets # noqa: F401
+from .exceptions import InvalidDateRange, InvalidDatetime # noqa: F401
+from .processor import DateRange, DateTimeProcessor # noqa: F401
from .serializer import DateRangeSerializer # noqa: F401
diff --git a/backend/utils/date/enums.py b/backend/utils/date/enums.py
new file mode 100644
index 000000000..dc1c07989
--- /dev/null
+++ b/backend/utils/date/enums.py
@@ -0,0 +1,58 @@
+from datetime import datetime, timedelta
+from enum import Enum
+from typing import Optional
+
+from django.utils import timezone
+from utils.date.exceptions import InvalidDateRange
+
+
+class DateRangePresets(Enum):
+ """Represents relative time presets.
+
+ Can be used for filtering entities
+ """
+
+ TODAY = ("today", 0, "Today")
+ YESTERDAY = ("yesterday", 1, "Yesterday")
+ LAST_2_DAYS = ("last_2_days", 2, "Last 2 Days")
+ LAST_7_DAYS = ("last_7_days", 7, "Last 7 Days")
+ LAST_30_DAYS = ("last_30_days", 30, "Last 30 Days")
+
+ def __init__(self, key: str, days: int, display_name: str):
+ self.key = key
+ self.days = days
+ self.display_name = display_name
+
+ def get_start_date(self) -> datetime:
+ now = timezone.now()
+ if self == DateRangePresets.TODAY:
+ return now.replace(hour=0, minute=0, second=0, microsecond=0)
+ elif self == DateRangePresets.YESTERDAY:
+ return (now - timedelta(days=1)).replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ return now - timedelta(days=self.days)
+
+ def get_end_date(self) -> datetime:
+ now = timezone.now()
+ if self == DateRangePresets.YESTERDAY:
+ return now.replace(hour=0, minute=0, second=0, microsecond=0)
+ return now
+
+ def get_date_range(self) -> tuple[datetime, datetime]:
+ return self.get_start_date(), self.get_end_date()
+
+ @classmethod
+ def from_value(cls, value: str) -> Optional["DateRangePresets"]:
+ try:
+ return next(preset for preset in cls if preset.key == value)
+ except StopIteration as e:
+ valid_values = [preset.key for preset in cls]
+ raise InvalidDateRange(
+ f"Invalid date range value: '{value}'. "
+ f"Valid values are: {', '.join(valid_values)}"
+ ) from e
+
+ @classmethod
+ def choices(cls) -> list[tuple[str, str]]:
+ return [(preset.key, preset.display_name) for preset in cls]
diff --git a/backend/usage_v2/exceptions.py b/backend/utils/date/exceptions.py
similarity index 100%
rename from backend/usage_v2/exceptions.py
rename to backend/utils/date/exceptions.py
index 80444989f..ec5f51202 100644
--- a/backend/usage_v2/exceptions.py
+++ b/backend/utils/date/exceptions.py
@@ -1,11 +1,11 @@
from rest_framework.exceptions import APIException
-class InvalidDatetime(APIException):
+class InvalidDateRange(APIException):
status_code = 400
- default_detail = "Invalid datetime format"
+ default_detail = "Invalid date range"
-class InvalidDateRange(APIException):
+class InvalidDatetime(APIException):
status_code = 400
- default_detail = "Invalid date range"
+ default_detail = "Invalid datetime format"
diff --git a/backend/usage_v2/utils.py b/backend/utils/date/processor.py
similarity index 93%
rename from backend/usage_v2/utils.py
rename to backend/utils/date/processor.py
index 0ad0d3443..612aaf3e3 100644
--- a/backend/usage_v2/utils.py
+++ b/backend/utils/date/processor.py
@@ -1,17 +1,31 @@
import logging
+from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional, Union
from dateutil.parser import parse
from django.utils import timezone
from isodate import parse_datetime
-from usage_v2.dto import DateRange
-from usage_v2.enums import DateRangePresets
-from usage_v2.exceptions import InvalidDatetime
+from utils.date.enums import DateRangePresets
+from utils.date.exceptions import InvalidDatetime
logger = logging.getLogger(__name__)
+@dataclass
+class DateRange:
+ """
+ Represents a validated date range with start and end dates.
+
+ Attributes:
+ start_date: Beginning of the date range
+ end_date: End of the date range
+ """
+
+ start_date: datetime
+ end_date: datetime
+
+
class DateTimeProcessor:
DEFAULT_DAYS_RANGE = 1
MAX_DAYS_RANGE = 60
diff --git a/backend/workflow_manager/execution/filter.py b/backend/workflow_manager/execution/filter.py
new file mode 100644
index 000000000..414ac4098
--- /dev/null
+++ b/backend/workflow_manager/execution/filter.py
@@ -0,0 +1,73 @@
+from api_v2.models import APIDeployment
+from django.db.models import QuerySet
+from django_filters import rest_framework as filters
+from pipeline_v2.models import Pipeline
+from utils.date import DateRangePresets, DateTimeProcessor
+from workflow_manager.execution.enum import ExecutionEntity
+from workflow_manager.workflow_v2.enums import ExecutionStatus
+from workflow_manager.workflow_v2.models import Workflow, WorkflowExecution
+
+
+class ExecutionFilter(filters.FilterSet):
+ execution_entity = filters.ChoiceFilter(
+ choices=[
+ (ExecutionEntity.API.value, "API"),
+ (ExecutionEntity.ETL.value, "ETL"),
+ (ExecutionEntity.TASK.value, "TASK"),
+ (ExecutionEntity.WORKFLOW.value, "WF"),
+ ],
+ method="filter_execution_entity",
+ )
+ # Lookup with query params: created_at_after, created_at_before
+ created_at = filters.DateTimeFromToRangeFilter()
+ status = filters.MultipleChoiceFilter(
+ field_name="status", choices=ExecutionStatus.choices
+ )
+ date_range = filters.ChoiceFilter(
+ choices=DateRangePresets.choices(),
+ method="filter_by_date_range",
+ )
+
+ class Meta:
+ model = WorkflowExecution
+ fields = []
+
+ def filter_execution_entity(
+ self, queryset: QuerySet, name: str, value: str
+ ) -> QuerySet:
+ if value == ExecutionEntity.API.value:
+ return queryset.filter(
+ pipeline_id__in=APIDeployment.objects.values_list("id", flat=True)
+ )
+ elif value == ExecutionEntity.ETL.value:
+ return queryset.filter(
+ pipeline_id__in=Pipeline.objects.filter(
+ pipeline_type=Pipeline.PipelineType.ETL
+ ).values_list("id", flat=True)
+ )
+ elif value == ExecutionEntity.TASK.value:
+ return queryset.filter(
+ pipeline_id__in=Pipeline.objects.filter(
+ pipeline_type=Pipeline.PipelineType.TASK
+ ).values_list("id", flat=True)
+ )
+ elif value == ExecutionEntity.WORKFLOW.value:
+ return queryset.filter(
+ pipeline_id=None,
+ workflow_id__in=Workflow.objects.values_list("id", flat=True),
+ )
+ return queryset
+
+ def filter_by_date_range(
+ self, queryset: QuerySet, name: str, value: str
+ ) -> QuerySet:
+ """
+ Filters Usages based on the provided date range.
+ """
+ date_span = DateTimeProcessor.filter_date_range(value)
+ if date_span:
+ queryset = queryset.filter(
+ created_at__gte=date_span.start_date,
+ created_at__lte=date_span.end_date,
+ )
+ return queryset
diff --git a/backend/workflow_manager/execution/views/execution.py b/backend/workflow_manager/execution/views/execution.py
index c5fe3ae60..8cede247d 100644
--- a/backend/workflow_manager/execution/views/execution.py
+++ b/backend/workflow_manager/execution/views/execution.py
@@ -1,17 +1,13 @@
import logging
-from typing import Optional
-from api_v2.models import APIDeployment
-from django.db.models import Q, QuerySet
-from pipeline_v2.models import Pipeline
+from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
from rest_framework.filters import OrderingFilter
from rest_framework.permissions import IsAuthenticated
-from utils.date import DateRangeKeys, DateRangeSerializer
from utils.pagination import CustomPagination
-from workflow_manager.execution.enum import ExecutionEntity
+from workflow_manager.execution.filter import ExecutionFilter
from workflow_manager.execution.serializer import ExecutionSerializer
-from workflow_manager.workflow_v2.models import Workflow, WorkflowExecution
+from workflow_manager.workflow_v2.models import WorkflowExecution
logger = logging.getLogger(__name__)
@@ -20,50 +16,8 @@ class ExecutionViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = [IsAuthenticated]
serializer_class = ExecutionSerializer
pagination_class = CustomPagination
- filter_backends = [OrderingFilter]
- ordering_fields = ["created_at"]
+ filter_backends = [DjangoFilterBackend, OrderingFilter]
+ ordering_fields = ["created_at", "execution_time"]
ordering = ["-created_at"]
-
- def get_queryset(self) -> Optional[QuerySet]:
- execution_entity = self.request.query_params.get("execution_entity")
-
- queryset = WorkflowExecution.objects.all()
-
- # Filter based on execution entity
- if execution_entity == ExecutionEntity.API.value:
- queryset = queryset.filter(
- pipeline_id__in=APIDeployment.objects.values_list("id", flat=True)
- )
- elif execution_entity == ExecutionEntity.ETL.value:
- queryset = queryset.filter(
- pipeline_id__in=Pipeline.objects.filter(
- pipeline_type=Pipeline.PipelineType.ETL
- ).values_list("id", flat=True)
- )
- elif execution_entity == ExecutionEntity.TASK.value:
- queryset = queryset.filter(
- pipeline_id__in=Pipeline.objects.filter(
- pipeline_type=Pipeline.PipelineType.TASK
- ).values_list("id", flat=True)
- )
- elif execution_entity == ExecutionEntity.WORKFLOW.value:
- queryset = queryset.filter(
- pipeline_id=None,
- workflow_id__in=Workflow.objects.values_list("id", flat=True),
- )
-
- # Parse and apply date filters
- date_range_serializer = DateRangeSerializer(data=self.request.query_params)
- date_range_serializer.is_valid(raise_exception=True)
-
- filters = Q()
- if start_date := date_range_serializer.validated_data.get(
- DateRangeKeys.START_DATE
- ):
- filters &= Q(created_at__gte=start_date)
- if end_date := date_range_serializer.validated_data.get(DateRangeKeys.END_DATE):
- filters &= Q(created_at__lte=end_date)
-
- queryset = queryset.filter(filters)
-
- return queryset
+ filterset_class = ExecutionFilter
+ queryset = WorkflowExecution.objects.all()
diff --git a/backend/workflow_manager/file_execution/filter.py b/backend/workflow_manager/file_execution/filter.py
new file mode 100644
index 000000000..ba4a49340
--- /dev/null
+++ b/backend/workflow_manager/file_execution/filter.py
@@ -0,0 +1,17 @@
+import django_filters
+from django_filters import rest_framework as filters
+from workflow_manager.file_execution.models import WorkflowFileExecution
+from workflow_manager.workflow_v2.enums import ExecutionStatus
+
+
+class FileExecutionFilter(filters.FilterSet):
+ status = django_filters.MultipleChoiceFilter(
+ field_name="status", choices=ExecutionStatus.choices
+ )
+ file_name = django_filters.CharFilter(
+ field_name="file_name", lookup_expr="icontains"
+ )
+
+ class Meta:
+ model = WorkflowFileExecution
+ fields = ["status", "file_name"]
diff --git a/backend/workflow_manager/file_execution/migrations/0004_alter_workflowfileexecution_status.py b/backend/workflow_manager/file_execution/migrations/0004_alter_workflowfileexecution_status.py
new file mode 100644
index 000000000..c3cc02ff2
--- /dev/null
+++ b/backend/workflow_manager/file_execution/migrations/0004_alter_workflowfileexecution_status.py
@@ -0,0 +1,27 @@
+# Generated by Django 4.2.1 on 2025-03-13 08:58
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("file_execution", "0003_alter_workflowfileexecution_status_and_more"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="workflowfileexecution",
+ name="status",
+ field=models.TextField(
+ choices=[
+ ("PENDING", "Pending"),
+ ("EXECUTING", "Executing"),
+ ("COMPLETED", "Completed"),
+ ("STOPPED", "Stopped"),
+ ("ERROR", "Error"),
+ ],
+ db_comment="Current status of the execution",
+ ),
+ ),
+ ]
diff --git a/backend/workflow_manager/file_execution/models.py b/backend/workflow_manager/file_execution/models.py
index 1d052db02..9c58a9158 100644
--- a/backend/workflow_manager/file_execution/models.py
+++ b/backend/workflow_manager/file_execution/models.py
@@ -23,7 +23,7 @@ class WorkflowFileExecutionManager(models.Manager):
file_hash: str,
file_path: Optional[str] = None,
mime_type: Optional[str] = None,
- ):
+ ) -> "WorkflowFileExecution":
"""
Retrieves or creates a new input file record for a workflow execution.
diff --git a/backend/workflow_manager/file_execution/serializers.py b/backend/workflow_manager/file_execution/serializers.py
index 68b73725f..41a4f33c8 100644
--- a/backend/workflow_manager/file_execution/serializers.py
+++ b/backend/workflow_manager/file_execution/serializers.py
@@ -19,7 +19,7 @@ class FileCentricExecutionSerializer(serializers.ModelSerializer):
INIT_STATUS_MSG = "Waiting for a worker to pick up file's execution..."
DEFAULT_STATUS_MSG = (
- "No status message available, please check again after a few minutes."
+ "No status message available yet, please check again after a few minutes."
)
status_msg = serializers.SerializerMethodField()
@@ -31,7 +31,7 @@ class FileCentricExecutionSerializer(serializers.ModelSerializer):
exclude = ["file_hash"]
def get_status_msg(self, obj: FileExecution) -> Optional[dict[str, any]]:
- if obj.status in [ExecutionStatus.PENDING, ExecutionStatus.QUEUED]:
+ if obj.status in [ExecutionStatus.PENDING]:
return self.INIT_STATUS_MSG
elif obj.status == ExecutionStatus.ERROR:
return obj.execution_error
diff --git a/backend/workflow_manager/file_execution/views.py b/backend/workflow_manager/file_execution/views.py
index cf304a5b1..7a64a25e5 100644
--- a/backend/workflow_manager/file_execution/views.py
+++ b/backend/workflow_manager/file_execution/views.py
@@ -3,6 +3,7 @@ from rest_framework import viewsets
from rest_framework.filters import OrderingFilter
from rest_framework.permissions import IsAuthenticated
from utils.pagination import CustomPagination
+from workflow_manager.file_execution.filter import FileExecutionFilter
from workflow_manager.file_execution.models import (
WorkflowFileExecution as FileExecution,
)
@@ -14,9 +15,9 @@ class FileCentricExecutionViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = FileCentricExecutionSerializer
pagination_class = CustomPagination
filter_backends = [DjangoFilterBackend, OrderingFilter]
- ordering_fields = ["created_at"]
+ ordering_fields = ["created_at", "execution_time"]
ordering = ["created_at"]
- filterset_fields = ["status"]
+ filterset_class = FileExecutionFilter
def get_queryset(self):
execution_id = self.kwargs.get("pk")
diff --git a/backend/workflow_manager/workflow_v2/enums.py b/backend/workflow_manager/workflow_v2/enums.py
index 377dc1d1a..8cb77e9ae 100644
--- a/backend/workflow_manager/workflow_v2/enums.py
+++ b/backend/workflow_manager/workflow_v2/enums.py
@@ -14,9 +14,6 @@ class ExecutionStatus(TextChoices):
Statuses:
PENDING: The execution's entry has been created in the database.
- QUEUED: The execution task is queued for asynchronous execution
- INITIATED: The execution has been initiated.
- READY: The execution is ready for the build phase.
EXECUTING: The execution is currently in progress.
COMPLETED: The execution has been successfully completed.
STOPPED: The execution was stopped by the user
@@ -29,9 +26,6 @@ class ExecutionStatus(TextChoices):
"""
PENDING = "PENDING"
- INITIATED = "INITIATED"
- QUEUED = "QUEUED"
- READY = "READY"
EXECUTING = "EXECUTING"
COMPLETED = "COMPLETED"
STOPPED = "STOPPED"
diff --git a/backend/workflow_manager/workflow_v2/execution.py b/backend/workflow_manager/workflow_v2/execution.py
index 31f2cb90f..b009e5076 100644
--- a/backend/workflow_manager/workflow_v2/execution.py
+++ b/backend/workflow_manager/workflow_v2/execution.py
@@ -82,7 +82,7 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):
execution_mode=mode,
execution_method=self.execution_method,
execution_type=self.execution_type,
- status=ExecutionStatus.INITIATED,
+ status=ExecutionStatus.EXECUTING,
execution_log_id=self.execution_log_id,
)
workflow_execution.save()
@@ -219,7 +219,7 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):
def build(self) -> None:
if self.compilation_result["success"] is True:
self.build_workflow()
- self.update_execution(status=ExecutionStatus.READY)
+ self.update_execution(status=ExecutionStatus.EXECUTING)
else:
logger.error(
"Errors while compiling workflow "
diff --git a/backend/workflow_manager/workflow_v2/execution_log_utils.py b/backend/workflow_manager/workflow_v2/execution_log_utils.py
index 21bcf1b38..0e5d6c622 100644
--- a/backend/workflow_manager/workflow_v2/execution_log_utils.py
+++ b/backend/workflow_manager/workflow_v2/execution_log_utils.py
@@ -1,6 +1,7 @@
import logging
import sys
from collections import defaultdict
+from typing import Optional
from celery import shared_task
from django.db import IntegrityError
@@ -10,44 +11,75 @@ from utils.cache_service import CacheService
from utils.constants import ExecutionLogConstants
from utils.dto import LogDataDTO
from workflow_manager.file_execution.models import WorkflowFileExecution
-from workflow_manager.workflow_v2.models.execution_log import ExecutionLog
+from workflow_manager.workflow_v2.models import ExecutionLog, WorkflowExecution
logger = logging.getLogger(__name__)
-@shared_task(bind=True, name=ExecutionLogConstants.TASK_V2)
-def consume_log_history(self):
+@shared_task(name=ExecutionLogConstants.TASK_V2)
+def consume_log_history() -> None:
organization_logs = defaultdict(list)
logs_count = 0
+ logs_to_process = []
+ # Collect logs from cache (batch retrieval)
while logs_count < ExecutionLogConstants.LOGS_BATCH_LIMIT:
log = CacheService.lpop(ExecutionLogConstants.LOG_QUEUE_NAME)
if not log:
break
- log_data = LogDataDTO.from_json(log)
- if not log_data:
- continue
+ log_data: Optional[LogDataDTO] = LogDataDTO.from_json(log)
+ if log_data:
+ logs_to_process.append(log_data)
+ logs_count += 1
+
+ if not logs_to_process:
+ return # No logs to process
+
+ logger.info(f"Logs count: {logs_count}")
+
+ # Preload required WorkflowExecution and WorkflowFileExecution objects
+ execution_ids = {log.execution_id for log in logs_to_process}
+ file_execution_ids = {
+ log.file_execution_id for log in logs_to_process if log.file_execution_id
+ }
+
+ execution_map = {
+ str(obj.id): obj
+ for obj in WorkflowExecution.objects.filter(id__in=execution_ids)
+ }
+ file_execution_map = {
+ str(obj.id): obj
+ for obj in WorkflowFileExecution.objects.filter(id__in=file_execution_ids)
+ }
+
+ # Process logs with preloaded data
+ for log_data in logs_to_process:
+ execution = execution_map.get(log_data.execution_id)
+ if not execution:
+ logger.warning(
+ f"Execution not found for execution_id: {log_data.execution_id}, "
+ "skipping log push"
+ )
+ continue # Skip logs with missing execution reference
- # Create ExecutionLog instance
execution_log = ExecutionLog(
- execution_id=log_data.execution_id,
+ wf_execution=execution,
data=log_data.data,
event_time=log_data.event_time,
)
- # Conditionally set file_execution if file_execution_id is present
if log_data.file_execution_id:
- execution_log.file_execution = WorkflowFileExecution(
- id=log_data.file_execution_id
+ execution_log.file_execution = file_execution_map.get(
+ log_data.file_execution_id
)
- organization_id = log_data.organization_id
- organization_logs[organization_id].append(execution_log)
- logs_count += 1
- logger.info(f"Logs count: {logs_count}")
+ organization_logs[log_data.organization_id].append(execution_log)
+
+ # Bulk insert logs for each organization
for organization_id, logs in organization_logs.items():
- store_to_db(organization_id, logs)
+ logger.info(f"Storing '{len(logs)}' logs for org: {organization_id}")
+ ExecutionLog.objects.bulk_create(objs=logs, ignore_conflicts=True)
def create_log_consumer_scheduler_if_not_exists() -> None:
@@ -92,24 +124,3 @@ def create_log_consumer_scheduler_if_not_exists() -> None:
logger.info("Log consumer scheduler created successfully.")
except IntegrityError as error:
logger.error(f"Error occurred while creating log consumer scheduler: {error}")
-
-
-def store_to_db(organization_id: str, execution_logs: list[ExecutionLog]) -> None:
-
- # Store the log data in the database within tenant context
- ExecutionLog.objects.bulk_create(objs=execution_logs, ignore_conflicts=True)
-
-
-class ExecutionLogUtils:
-
- @staticmethod
- def get_execution_logs_by_execution_id(execution_id) -> list[ExecutionLog]:
- """Get all execution logs for a given execution ID.
-
- Args:
- execution_id (int): The ID of the execution.
-
- Returns:
- list[ExecutionLog]: A list of ExecutionLog objects.
- """
- return ExecutionLog.objects.filter(execution_id=execution_id)
diff --git a/backend/workflow_manager/workflow_v2/execution_log_view.py b/backend/workflow_manager/workflow_v2/execution_log_view.py
index 711789e8f..849bc6adc 100644
--- a/backend/workflow_manager/workflow_v2/execution_log_view.py
+++ b/backend/workflow_manager/workflow_v2/execution_log_view.py
@@ -1,10 +1,14 @@
import logging
+from django.db.models import Q
from django.db.models.query import QuerySet
+from django_filters.rest_framework import DjangoFilterBackend
from permissions.permission import IsOwner
from rest_framework import viewsets
+from rest_framework.filters import OrderingFilter
from rest_framework.versioning import URLPathVersioning
from utils.pagination import CustomPagination
+from workflow_manager.workflow_v2.filters import ExecutionLogFilter
from workflow_manager.workflow_v2.models.execution_log import ExecutionLog
from workflow_manager.workflow_v2.serializers import WorkflowExecutionLogSerializer
@@ -16,25 +20,18 @@ class WorkflowExecutionLogViewSet(viewsets.ModelViewSet):
permission_classes = [IsOwner]
serializer_class = WorkflowExecutionLogSerializer
pagination_class = CustomPagination
-
- EVENT_TIME_FIELD_ASC = "event_time"
+ filter_backends = [DjangoFilterBackend, OrderingFilter]
+ ordering_fields = ["event_time"]
+ ordering = ["event_time"]
+ filterset_class = ExecutionLogFilter
def get_queryset(self) -> QuerySet:
# Get the execution_id:pk from the URL path
execution_id = self.kwargs.get("pk")
- filter_param = {"execution_id": execution_id}
-
- file_execution_id = self.request.query_params.get("file_execution_id")
- if file_execution_id and file_execution_id == "null":
- filter_param["file_execution_id"] = None
- elif file_execution_id:
- filter_param["file_execution_id"] = file_execution_id
-
- log_level = self.request.query_params.get("log_level")
- if log_level:
- filter_param["data__level"] = log_level.upper()
- queryset = ExecutionLog.objects.filter(**filter_param).order_by(
- self.EVENT_TIME_FIELD_ASC
+ # Query by execution_id for backward compatiblity
+ # Remove filter after execution_id is removed
+ queryset = ExecutionLog.objects.filter(
+ Q(wf_execution_id=execution_id) | Q(execution_id=execution_id)
)
return queryset
diff --git a/backend/workflow_manager/workflow_v2/filters/__init__.py b/backend/workflow_manager/workflow_v2/filters/__init__.py
new file mode 100644
index 000000000..2b1f3291c
--- /dev/null
+++ b/backend/workflow_manager/workflow_v2/filters/__init__.py
@@ -0,0 +1 @@
+from .execution_log import ExecutionLogFilter # noqa: F401
diff --git a/backend/workflow_manager/workflow_v2/filters/execution_log.py b/backend/workflow_manager/workflow_v2/filters/execution_log.py
new file mode 100644
index 000000000..e5806baf8
--- /dev/null
+++ b/backend/workflow_manager/workflow_v2/filters/execution_log.py
@@ -0,0 +1,48 @@
+from typing import Optional
+
+from django.db.models.query import QuerySet
+from django_filters import CharFilter, FilterSet, ModelChoiceFilter
+from rest_framework.request import Request
+from unstract.sdk.constants import LogLevel
+from workflow_manager.file_execution.models import WorkflowFileExecution
+from workflow_manager.workflow_v2.models.execution_log import ExecutionLog
+
+
+def get_file_executions(request: Optional[Request]) -> QuerySet:
+ """Callable for ModelChoiceFilter to dynamically filter file_execution_id."""
+ if request is None or not hasattr(request, "parser_context"):
+ return WorkflowFileExecution.objects.none()
+
+ # Extract execution_id from URL kwargs
+ execution_id = request.parser_context["kwargs"].get("pk")
+ if not execution_id:
+ return WorkflowFileExecution.objects.none()
+
+ return WorkflowFileExecution.objects.filter(workflow_execution_id=execution_id)
+
+
+class ExecutionLogFilter(FilterSet):
+ file_execution_id = ModelChoiceFilter(
+ queryset=get_file_executions,
+ null_label="null",
+ )
+
+ log_level = CharFilter(field_name="data__level", method="filter_logs")
+
+ class Meta:
+ model = ExecutionLog
+ fields = ["file_execution_id", "log_level"]
+
+ def filter_logs(self, queryset: QuerySet, name: str, value: str) -> QuerySet:
+ levels = {
+ LogLevel.DEBUG.value: 0,
+ LogLevel.INFO.value: 1,
+ LogLevel.WARN.value: 2,
+ LogLevel.ERROR.value: 3,
+ }
+ min_level = levels.get(value, 1) # Default to INFO if not found
+ return queryset.filter(
+ data__level__in=[
+ level for level, severity in levels.items() if severity >= min_level
+ ]
+ )
diff --git a/backend/workflow_manager/workflow_v2/migrations/0009_update_total_files.py b/backend/workflow_manager/workflow_v2/migrations/0009_update_total_files.py
new file mode 100644
index 000000000..8fd7e8a82
--- /dev/null
+++ b/backend/workflow_manager/workflow_v2/migrations/0009_update_total_files.py
@@ -0,0 +1,41 @@
+# Generated by Django 4.2.1 on 2025-03-12 08:34
+
+from typing import Any
+
+from django.db import migrations
+
+
+def update_total_files(apps: Any, schema_editor: Any) -> None:
+ """Update total_files column in WorkflowExecution model
+
+ Obtained by counting the number of associated WorkflowFileExecution records
+ """
+ WorkflowExecution = apps.get_model( # pylint: disable=invalid-name # NOSONAR
+ "workflow_v2", "WorkflowExecution"
+ )
+
+ # Update total_files for older executions with a count of zero
+ for execution in WorkflowExecution.objects.filter(total_files=0):
+ count = execution.file_executions.count()
+ execution.total_files = count
+ execution.save(update_fields=["total_files"])
+
+
+def reverse_update_total_files(apps: Any, schema_editor: Any) -> None:
+ """Reverse the update by setting total_files back to zero for all file executions"""
+ WorkflowExecution = apps.get_model( # pylint: disable=invalid-name # NOSONAR
+ "workflow_v2", "WorkflowExecution"
+ )
+
+ WorkflowExecution.objects.update(total_files=0)
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("workflow_v2", "0008_workflowexecution_total_files_and_more"),
+ ]
+
+ operations = [
+ migrations.RunPython(update_total_files, reverse_update_total_files),
+ ]
diff --git a/backend/workflow_manager/workflow_v2/migrations/0010_executionlog_wf_execution_and_more.py b/backend/workflow_manager/workflow_v2/migrations/0010_executionlog_wf_execution_and_more.py
new file mode 100644
index 000000000..9b97e545d
--- /dev/null
+++ b/backend/workflow_manager/workflow_v2/migrations/0010_executionlog_wf_execution_and_more.py
@@ -0,0 +1,64 @@
+# Generated by Django 4.2.1 on 2025-03-18 12:39
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("workflow_v2", "0009_update_total_files"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="executionlog",
+ name="wf_execution",
+ field=models.ForeignKey(
+ blank=True,
+ db_comment="Foreign key from WorkflowExecution model",
+ editable=False,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="execution_logs",
+ to="workflow_v2.workflowexecution",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="executionlog",
+ name="execution_id",
+ field=models.UUIDField(
+ db_comment="Execution ID (deprecated, refer wf_execution instead)",
+ editable=False,
+ null=True,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="filehistory",
+ name="status",
+ field=models.TextField(
+ choices=[
+ ("PENDING", "Pending"),
+ ("EXECUTING", "Executing"),
+ ("COMPLETED", "Completed"),
+ ("STOPPED", "Stopped"),
+ ("ERROR", "Error"),
+ ],
+ db_comment="Latest status of execution",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="workflowexecution",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("PENDING", "Pending"),
+ ("EXECUTING", "Executing"),
+ ("COMPLETED", "Completed"),
+ ("STOPPED", "Stopped"),
+ ("ERROR", "Error"),
+ ],
+ db_comment="Current status of the execution",
+ ),
+ ),
+ ]
diff --git a/backend/workflow_manager/workflow_v2/models/__init__.py b/backend/workflow_manager/workflow_v2/models/__init__.py
index 817f43b21..cd3a65e18 100644
--- a/backend/workflow_manager/workflow_v2/models/__init__.py
+++ b/backend/workflow_manager/workflow_v2/models/__init__.py
@@ -2,6 +2,6 @@
# Do not change the order of the imports below to avoid circular dependency issues
from .workflow import Workflow # noqa: F401
-from .execution_log import ExecutionLog # noqa: F401
from .execution import WorkflowExecution # noqa: F401
+from .execution_log import ExecutionLog # noqa: F401
from .file_history import FileHistory # noqa: F401
diff --git a/backend/workflow_manager/workflow_v2/models/execution_log.py b/backend/workflow_manager/workflow_v2/models/execution_log.py
index c3d5ebfa4..0093d6529 100644
--- a/backend/workflow_manager/workflow_v2/models/execution_log.py
+++ b/backend/workflow_manager/workflow_v2/models/execution_log.py
@@ -3,13 +3,27 @@ import uuid
from django.db import models
from utils.models.base_model import BaseModel
from workflow_manager.file_execution.models import WorkflowFileExecution
+from workflow_manager.workflow_v2.models import WorkflowExecution
class ExecutionLog(BaseModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
+ # TODO: Deprecated field, retained for backward compatibility
+ # Remove after old logs are rotated from the system
+ # Will be NULL for new records, use `wf_execution` instead
execution_id = models.UUIDField(
editable=False,
- db_comment="Execution ID",
+ db_comment="Execution ID (deprecated, refer wf_execution instead)",
+ null=True,
+ )
+ wf_execution = models.ForeignKey(
+ WorkflowExecution,
+ on_delete=models.CASCADE,
+ editable=False,
+ db_comment="Foreign key from WorkflowExecution model",
+ related_name="execution_logs",
+ null=True,
+ blank=True,
)
file_execution = models.ForeignKey(
WorkflowFileExecution,
@@ -25,7 +39,10 @@ class ExecutionLog(BaseModel):
event_time = models.DateTimeField(db_comment="Execution log event time")
def __str__(self):
- return f"Execution ID: {self.execution_id}, Message: {self.data}"
+ return (
+ f"Execution ID: {str(self.wf_execution)}, Message: {self.data}, "
+ f"Event time: {self.event_time}"
+ )
class Meta:
verbose_name = "Execution Log"
diff --git a/backend/workflow_manager/workflow_v2/workflow_helper.py b/backend/workflow_manager/workflow_v2/workflow_helper.py
index c6e899637..adcfd5e3f 100644
--- a/backend/workflow_manager/workflow_v2/workflow_helper.py
+++ b/backend/workflow_manager/workflow_v2/workflow_helper.py
@@ -247,7 +247,7 @@ class WorkflowHelper:
execution_service.initiate_tool_execution(
current_file_idx, total_files, file_name, single_step
)
- workflow_file_execution.update_status(status=ExecutionStatus.INITIATED)
+ workflow_file_execution.update_status(status=ExecutionStatus.EXECUTING)
if not file_hash.is_executed:
execution_service.execute_input_file(
file_execution_id=file_execution_id,