LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
UN-4467 [FEAT] Filters, paging and counts on metrics recent-activity (#2369)
Ritwik G8fa9e5be4513
diff --git a/backend/dashboard_metrics/README.md b/backend/dashboard_metrics/README.mdindex 58c29b4f1..c97a0678c 100644--- a/backend/dashboard_metrics/README.md+++ b/backend/dashboard_metrics/README.md@@ -613,6 +613,7 @@ Base URL: `/api/v1/unstract/<org_id>/metrics/`| `/series/` | GET | Time series for date range | Auto-selected table || `/live-summary/` | GET | Summary from source tables | Source tables directly || `/live-series/` | GET | Time series from source tables | Source tables directly |+| `/recent-activity/` | GET | Latest file executions; paged with counts on request | Source tables directly || `/attention/` | GET | Open items that need attention | Source tables directly || `/attribution/` | GET | Failed pages by source and by day | Source tables directly || `/health/` | GET | Health check | DB + Cache |@@ -686,6 +687,73 @@ Override with `?source=hourly|daily|monthly`}```+### Recent activity (DG-02, DG-03)++`/recent-activity/` has two forms. The contract is this section plus the+`@extend_schema` annotation on `DashboardMetricsViewSet.recent_activity`+(operation `metrics_recent_activity`).++**Default form.** With none of the parameters below, the response is exactly+what it has always been: the latest `limit` file executions (default 10, at+most 50), newest first, and nothing else. The v0 dashboard uses this form.++```json+{+ "activity": [+ {"id": "…", "execution_id": "…", "type": "workflow", "file_name": "inv-01.pdf",+ "status": "COMPLETED", "workflow_name": "Invoices",+ "created_at": "2026-10-21T09:12:03+00:00", "execution_time": 4.2,+ "total_tokens": 1830, "cost": 0.0123}+ ]+}+```++**Paged form.** Passing any of these with a value switches to it; `limit` is then ignored.++| Parameter | Default | Description |+|-----------|---------|-------------|+| `start_date` | 30 days ago | ISO 8601, inclusive. At most 365 days before `end_date` |+| `end_date` | Now | ISO 8601, inclusive |+| `status` | All | File execution statuses, comma-separated: `PENDING`, `EXECUTING`, `COMPLETED`, `STOPPED`, `ERROR` (case-insensitive) |+| `surface` | All | Comma-separated: `api`, `etl`, `task`, `workflow` |+| `page` | 1 | 1-based, at most 10,000. A page past the end returns no rows |+| `page_size` | 20 | At most 100 |++`status` and `surface` take one comma-separated value, not a repeated+parameter, because the response cache keys on the last value of each+parameter. An unknown value, a bad date or an out-of-range page size is a 400.++```json+{+ "start_date": "2026-09-22T00:00:00+00:00",+ "end_date": "2026-10-22T00:00:00+00:00",+ "page": 1,+ "page_size": 20,+ "activity": [+ {"id": "…", "execution_id": "…", "type": "workflow", "surface": "task",+ "file_name": "inv-01.pdf", "status": "ERROR", "workflow_name": "Invoices",+ "created_at": "2026-10-21T09:12:03+00:00", "execution_time": 4.2,+ "total_tokens": 1830, "cost": 0.0123}+ ],+ "count": 1007,+ "status_counts": {"PENDING": 0, "EXECUTING": 2, "COMPLETED": 951,+ "STOPPED": 0, "ERROR": 54}+}+```++- Rows are newest first, ties broken by id. Send the `start_date` and+ `end_date` echoed on page 1 with every later page.+- `count` is the number of rows matching every filter (for "Showing 20 of 1,007").+- `status_counts` counts the range and `surface` but ignores `status`, so each+ status filter chip can show its count while one is selected. Every status is+ present, with 0 when there are none; "All" is the sum.+- `surface` (paged form only) tells Task pipeline runs apart: `api` (API+ deployment), `etl` (ETL pipeline), `task` (Task pipeline) and `workflow`+ (everything else: manual runs, and default and app pipelines). `type` keeps+ its old values, where a Task pipeline run is `workflow`.+- Both forms are cached like the other metrics responses; `?refresh=true`+ bypasses the cache and does not switch forms.+### Attention and attribution (PB-T14)Both take only `start_date` and `end_date` (ISO 8601; default the last 30diff --git a/backend/dashboard_metrics/models.py b/backend/dashboard_metrics/models.pyindex 9125208a3..9c688f119 100644--- a/backend/dashboard_metrics/models.py+++ b/backend/dashboard_metrics/models.py@@ -25,6 +25,19 @@ class MetricType(models.TextChoices):HISTOGRAM = "histogram", "Histogram"+class ActivitySurface(models.TextChoices):+ """Where a run in recent activity came from (DG-03).++ Unlike the older ``type`` field, which reports Task pipeline runs as+ ``workflow``, this tells Task pipelines apart.+ """++ API = "api", "API deployment"+ ETL = "etl", "ETL pipeline"+ TASK = "task", "Task pipeline"+ WORKFLOW = "workflow", "Workflow"++class EventMetricsHourlyManager(DefaultOrganizationManagerMixin, BaseModelManager):"""Manager for EventMetricsHourly with organization filtering."""diff --git a/backend/dashboard_metrics/serializers.py b/backend/dashboard_metrics/serializers.pyindex 602f031cd..143558eb2 100644--- a/backend/dashboard_metrics/serializers.py+++ b/backend/dashboard_metrics/serializers.py@@ -5,8 +5,34 @@ from datetime import timedeltafrom django.utils import timezonefrom rest_framework import serializersfrom workflow_manager.execution.enum import ExecutionEntity+from workflow_manager.workflow_v2.enums import ExecutionStatus-from .models import EventMetricsHourly+from .models import ActivitySurface, EventMetricsHourly+++def _default_date_range(attrs: dict) -> dict:+ """Default the range to the last 30 days and cap it at 365 days."""+ now = timezone.now()++ if not attrs.get("end_date"):+ attrs["end_date"] = now++ if not attrs.get("start_date"):+ attrs["start_date"] = now - timedelta(days=30)++ if attrs["start_date"] > attrs["end_date"]:+ raise serializers.ValidationError(+ {"start_date": "Start date must be before end date"}+ )++ # Limit query range to 365 days (1 year) for monthly data+ max_range = timedelta(days=365)+ if attrs["end_date"] - attrs["start_date"] > max_range:+ raise serializers.ValidationError(+ {"start_date": "Query range cannot exceed 365 days"}+ )++ return attrsclass MetricsQuerySerializer(serializers.Serializer):@@ -50,27 +76,7 @@ class MetricsQuerySerializer(serializers.Serializer):def validate(self, attrs):"""Set defaults and validate date range."""- now = timezone.now()-- if not attrs.get("end_date"):- attrs["end_date"] = now-- if not attrs.get("start_date"):- attrs["start_date"] = now - timedelta(days=30)-- if attrs["start_date"] > attrs["end_date"]:- raise serializers.ValidationError(- {"start_date": "Start date must be before end date"}- )-- # Limit query range to 365 days (1 year) for monthly data- max_range = timedelta(days=365)- if attrs["end_date"] - attrs["start_date"] > max_range:- raise serializers.ValidationError(- {"start_date": "Query range cannot exceed 365 days"}- )-- return attrs+ return _default_date_range(attrs)class DeploymentUsageQuerySerializer(MetricsQuerySerializer):@@ -102,6 +108,88 @@ class DeploymentUsageQuerySerializer(MetricsQuerySerializer):return attrs+class _CommaSeparatedChoicesField(serializers.CharField):+ """A comma-separated list of choices, e.g. ``COMPLETED,ERROR``.++ One comma-separated value rather than a repeated parameter, because the+ response cache keys on the last value of each parameter only.+ """++ def __init__(self, *, choices: list[str], upper: bool, **kwargs):+ self.choices = choices+ self.upper = upper+ super().__init__(**kwargs)++ def to_internal_value(self, data) -> list[str]:+ raw = super().to_internal_value(data)+ values = [+ v.strip().upper() if self.upper else v.strip().lower()+ for v in raw.split(",")+ if v.strip()+ ]+ unknown = sorted(set(values) - set(self.choices))+ if not values or unknown:+ raise serializers.ValidationError(+ f"Use one or more of {', '.join(self.choices)}, comma-separated."+ )+ # Keep the caller's order, without repeats.+ return list(dict.fromkeys(values))+++class RecentActivityQuerySerializer(serializers.Serializer):+ """Query parameters for the paged form of ``recent-activity/`` (DG-02).++ Passing any of these with a value switches the endpoint to the paged+ response. Without them, the endpoint answers exactly as before, from+ ``limit`` alone.+ """++ PAGED_PARAMS = frozenset(+ {"start_date", "end_date", "status", "surface", "page", "page_size"}+ )+ DEFAULT_PAGE_SIZE = 20+ MAX_PAGE_SIZE = 100+ MAX_PAGE = 10_000++ start_date = serializers.DateTimeField(+ required=False,+ help_text="Start of date range (ISO 8601), inclusive. Defaults to 30 days ago.",+ )+ end_date = serializers.DateTimeField(+ required=False,+ help_text="End of date range (ISO 8601), inclusive. Defaults to now.",+ )+ status = _CommaSeparatedChoicesField(+ required=False,+ choices=[s.value for s in ExecutionStatus],+ upper=True,+ help_text="File execution statuses, comma-separated, e.g. COMPLETED,ERROR.",+ )+ surface = _CommaSeparatedChoicesField(+ required=False,+ choices=[s.value for s in ActivitySurface],+ upper=False,+ help_text="Surfaces, comma-separated: api, etl, task, workflow.",+ )+ page = serializers.IntegerField(+ required=False,+ default=1,+ min_value=1,+ max_value=MAX_PAGE,+ help_text=f"1-based page, at most {MAX_PAGE}.",+ )+ page_size = serializers.IntegerField(+ required=False,+ default=DEFAULT_PAGE_SIZE,+ min_value=1,+ max_value=MAX_PAGE_SIZE,+ help_text=f"Rows per page, default {DEFAULT_PAGE_SIZE}, max {MAX_PAGE_SIZE}.",+ )++ def validate(self, attrs):+ return _default_date_range(attrs)++class EventMetricsHourlySerializer(serializers.ModelSerializer):"""Model serializer for EventMetricsHourly records."""diff --git a/backend/dashboard_metrics/services.py b/backend/dashboard_metrics/services.pyindex 0deaf76f4..95967e362 100644--- a/backend/dashboard_metrics/services.py+++ b/backend/dashboard_metrics/services.py@@ -23,7 +23,7 @@ from workflow_manager.file_execution.models import WorkflowFileExecutionfrom workflow_manager.workflow_v2.models.execution import WorkflowExecutionfrom workflow_manager.workflow_v2.models.workflow import Workflow-from dashboard_metrics.models import Granularity+from dashboard_metrics.models import ActivitySurface, Granularityfrom unstract.core.data_models import ExecutionStatus@@ -50,6 +50,139 @@ def _get_usage_queryset():return Usage._base_manager.all()+def _activity_source_ids(organization_id: str) -> dict[str, set]:+ """Pipeline and API deployment ids by the surface they belong to."""+ # Use _base_manager to bypass DefaultOrganizationManagerMixin+ # (UserContext is None in Celery tasks)+ pipelines = Pipeline._base_manager.filter(organization_id=organization_id)+ return {+ ActivitySurface.ETL: set(+ pipelines.filter(pipeline_type=Pipeline.PipelineType.ETL).values_list(+ "id", flat=True+ )+ ),+ ActivitySurface.TASK: set(+ pipelines.filter(pipeline_type=Pipeline.PipelineType.TASK).values_list(+ "id", flat=True+ )+ ),+ ActivitySurface.API: set(+ APIDeployment._base_manager.filter(+ organization_id=organization_id,+ ).values_list("id", flat=True)+ ),+ }+++def _org_file_executions(organization_id: str):+ return WorkflowFileExecution.objects.filter(+ workflow_execution__workflow__organization_id=organization_id,+ ).select_related(+ "workflow_execution",+ "workflow_execution__workflow",+ )+++def _surface_filter(organization_id: str, surfaces: list[str]) -> Q:+ """Rows whose run came from any of ``surfaces``.++ ``workflow`` is every run that is not from an ETL or Task pipeline or an+ API deployment: manual runs, and default and app pipelines.+ """+ pipelines = Pipeline._base_manager.filter(organization_id=organization_id)+ subqueries = {+ ActivitySurface.ETL: pipelines.filter(+ pipeline_type=Pipeline.PipelineType.ETL+ ).values("id"),+ ActivitySurface.TASK: pipelines.filter(+ pipeline_type=Pipeline.PipelineType.TASK+ ).values("id"),+ ActivitySurface.API: APIDeployment._base_manager.filter(+ organization_id=organization_id+ ).values("id"),+ }+ pipeline_id = "workflow_execution__pipeline_id"+ q = Q()+ for surface in surfaces:+ if surface == ActivitySurface.WORKFLOW:+ from_known_source = Q()+ for subquery in subqueries.values():+ from_known_source |= Q(**{f"{pipeline_id}__in": subquery})+ # Django's negation keeps rows whose pipeline_id is NULL.+ q |= ~from_known_source+ else:+ q |= Q(**{f"{pipeline_id}__in": subqueries[surface]})+ return q+++def _activity_rows(+ executions, source_ids: dict[str, set], with_surface: bool+) -> list[dict[str, Any]]:+ """Serialize file executions as activity rows, with tokens and cost.++ ``with_surface`` adds the DG-03 ``surface`` field. The default response+ leaves it out, so it stays byte-identical for existing callers.+ """+ results = []+ for execution in executions:+ pipeline_id = execution.workflow_execution.pipeline_id++ # Determine execution type based on pipeline_id+ if pipeline_id and pipeline_id in source_ids[ActivitySurface.ETL]:+ exec_type = "etl"+ elif pipeline_id and pipeline_id in source_ids[ActivitySurface.API]:+ exec_type = "api"+ else:+ exec_type = "workflow"++ row = {+ "id": str(execution.id),+ "execution_id": str(execution.workflow_execution.id),+ "type": exec_type,+ "file_name": execution.file_name,+ "status": execution.status,+ "workflow_name": execution.workflow_execution.workflow.workflow_name,+ "created_at": execution.created_at.isoformat(),+ "execution_time": execution.execution_time,+ }+ if with_surface:+ row["surface"] = (+ ActivitySurface.TASK.value+ if pipeline_id and pipeline_id in source_ids[ActivitySurface.TASK]+ else exec_type+ )+ results.append(row)++ # Batch query: get aggregated token/cost per file execution+ file_exec_ids = [r["id"] for r in results]+ usage_agg: dict[str, dict[str, Any]] = {}+ if file_exec_ids:+ agg_qs = (+ _get_usage_queryset()+ .filter(run_id__in=file_exec_ids)+ .values("run_id")+ .annotate(+ total_tokens=Sum("total_tokens"),+ cost=Sum("cost_in_dollars"),+ )+ )+ usage_agg = {+ str(row["run_id"]): {+ "total_tokens": row["total_tokens"] or 0,+ "cost": round(row["cost"] or 0, 4),+ }+ for row in agg_qs+ }++ # Enrich results with LLM usage data+ for r in results:+ agg = usage_agg.get(r["id"], {})+ r["total_tokens"] = agg.get("total_tokens", 0)+ r["cost"] = agg.get("cost", 0)++ return results++class MetricsQueryService:"""Service for querying metrics from source tables.@@ -629,86 +762,71 @@ class MetricsQueryService:Returns:List of dicts with execution details including type"""- # Use _base_manager to bypass DefaultOrganizationManagerMixin- # (UserContext is None in Celery tasks)- etl_pipeline_ids = set(- Pipeline._base_manager.filter(- organization_id=organization_id,- pipeline_type="ETL",- ).values_list("id", flat=True)- )-- api_deployment_ids = set(- APIDeployment._base_manager.filter(- organization_id=organization_id,- ).values_list("id", flat=True)- )+ source_ids = _activity_source_ids(organization_id)+ recent = _org_file_executions(organization_id).order_by("-created_at")[:limit]+ return _activity_rows(recent, source_ids, with_surface=False)- # Query recent file executions with related data- recent = (- WorkflowFileExecution.objects.filter(- workflow_execution__workflow__organization_id=organization_id,- )- .select_related(- "workflow_execution",- "workflow_execution__workflow",- )- .order_by("-created_at")[:limit]- )-- results = []- for execution in recent:- pipeline_id = execution.workflow_execution.pipeline_id+ @staticmethod+ def get_activity_page(+ organization_id: str,+ start_date: datetime,+ end_date: datetime,+ statuses: list[str] | None,+ surfaces: list[str] | None,+ page: int,+ page_size: int,+ ) -> dict[str, Any]:+ """Get one page of activity in a date range, with counts (DG-02).- # Determine execution type based on pipeline_id- if pipeline_id and pipeline_id in etl_pipeline_ids:- exec_type = "etl"- elif pipeline_id and pipeline_id in api_deployment_ids:- exec_type = "api"- else:- exec_type = "workflow"+ ``status_counts`` covers the range and surfaces but ignores+ ``statuses``, so every status filter chip can show its count;+ ``count`` is the number of rows matching every filter.- results.append(- {- "id": str(execution.id),- "execution_id": str(execution.workflow_execution.id),- "type": exec_type,- "file_name": execution.file_name,- "status": execution.status,- "workflow_name": execution.workflow_execution.workflow.workflow_name,- "created_at": execution.created_at.isoformat(),- "execution_time": execution.execution_time,- }- )+ Args:+ organization_id: Organization UUID string+ start_date: Start of range, inclusive+ end_date: End of range, inclusive+ statuses: File execution statuses to keep, or None for all+ surfaces: ActivitySurface values to keep, or None for all+ page: 1-based page number+ page_size: Rows per page- # Batch query: get aggregated token/cost per file execution- file_exec_ids = [r["id"] for r in results]- usage_agg: dict[str, dict[str, Any]] = {}- if file_exec_ids:- agg_qs = (- _get_usage_queryset()- .filter(run_id__in=file_exec_ids)- .values("run_id")- .annotate(- total_tokens=Sum("total_tokens"),- cost=Sum("cost_in_dollars"),- )- )- usage_agg = {- str(row["run_id"]): {- "total_tokens": row["total_tokens"] or 0,- "cost": round(row["cost"] or 0, 4),- }- for row in agg_qs- }+ Returns:+ Dict with ``activity`` (rows with ``surface``), ``count`` and+ ``status_counts``+ """+ source_ids = _activity_source_ids(organization_id)+ # Accepted for now: no index leads on created_at, so a wide range scans+ # the org's rows in it. Responses are cached.+ in_range = _org_file_executions(organization_id).filter(+ created_at__gte=start_date,+ created_at__lte=end_date,+ )+ if surfaces:+ in_range = in_range.filter(_surface_filter(organization_id, surfaces))- # Enrich results with LLM usage data- for r in results:- agg = usage_agg.get(r["id"], {})- r["total_tokens"] = agg.get("total_tokens", 0)- r["cost"] = agg.get("cost", 0)+ by_status = {+ row["status"]: row["n"]+ for row in in_range.order_by().values("status").annotate(n=Count("id"))+ }+ status_counts = {s.value: by_status.pop(s.value, 0) for s in ExecutionStatus}+ # Keep any status the enum does not know, so the counts still add up.+ status_counts.update(by_status)++ rows = in_range+ if statuses:+ rows = rows.filter(status__in=statuses)+ count = sum(status_counts.get(s, 0) for s in statuses)+ else:+ count = sum(status_counts.values())- return results+ offset = (page - 1) * page_size+ page_rows = rows.order_by("-created_at", "-id")[offset : offset + page_size]+ return {+ "activity": _activity_rows(page_rows, source_ids, with_surface=True),+ "count": count,+ "status_counts": status_counts,+ }@staticmethoddef _get_deployment_names(diff --git a/backend/dashboard_metrics/tests/test_recent_activity.py b/backend/dashboard_metrics/tests/test_recent_activity.pynew file mode 100644index 000000000..f2bf101d5--- /dev/null+++ b/backend/dashboard_metrics/tests/test_recent_activity.py@@ -0,0 +1,435 @@+"""``metrics/recent-activity/``: the paged form with counts (DG-02) and the+per-row ``surface`` (DG-03), and the default form left exactly as it was.++DB-backed Django ``TestCase`` → auto-marked ``integration`` by ``backend/conftest.py``.+"""++import json+import uuid+from datetime import timedelta++from account_v2.models import Organization+from api_v2.models import APIDeployment+from django.test import SimpleTestCase, TestCase+from django.utils import timezone+from drf_spectacular.generators import SchemaGenerator+from permissions.tests.base import CoOwnerOrgTestMixin+from pipeline_v2.models import Pipeline+from rest_framework.renderers import JSONRenderer+from rest_framework.test import APIRequestFactory, force_authenticate+from usage_v2.models import Usage, UsageType+from utils.user_context import UserContext+from workflow_manager.file_execution.models import WorkflowFileExecution+from workflow_manager.workflow_v2.enums import ExecutionStatus+from workflow_manager.workflow_v2.models.execution import WorkflowExecution+from workflow_manager.workflow_v2.models.workflow import Workflow++from dashboard_metrics import urls+from dashboard_metrics.views import DashboardMetricsViewSet++COMPLETED = ExecutionStatus.COMPLETED.value+ERROR = ExecutionStatus.ERROR.value+EXECUTING = ExecutionStatus.EXECUTING.value+ALL_STATUSES = [s.value for s in ExecutionStatus]+++class _Seed(CoOwnerOrgTestMixin):+ def setUp(self) -> None:+ self._seed_org()+ self.now = timezone.now().replace(microsecond=0)++ def _workflow(self, org: Organization | None = None) -> Workflow:+ return Workflow.objects.create(+ workflow_name=f"wf-{uuid.uuid4().hex[:6]}",+ organization=org or self.org,+ created_by=self.owner,+ )++ def _pipeline(self, pipeline_type: str) -> Pipeline:+ return Pipeline.objects.create(+ pipeline_name=f"{pipeline_type.lower()}-{uuid.uuid4().hex[:6]}",+ pipeline_type=pipeline_type,+ workflow=self._workflow(),+ organization=self.org,+ created_by=self.owner,+ )++ def _deployment(self) -> APIDeployment:+ return APIDeployment.objects.create(+ api_name=f"api-{uuid.uuid4().hex[:6]}",+ display_name="api",+ workflow=self._workflow(),+ organization=self.org,+ created_by=self.owner,+ )++ def _file(+ self,+ source,+ status: str,+ hours_ago: float,+ workflow: Workflow | None = None,+ tokens: int = 0,+ ) -> WorkflowFileExecution:+ """One file execution, from ``source`` (a pipeline or deployment, or+ None for a manual workflow run), created ``hours_ago``."""+ execution = WorkflowExecution.objects.create(+ workflow=workflow or source.workflow,+ pipeline_id=source.pk if source is not None else None,+ status=status,+ )+ file_execution = WorkflowFileExecution.objects.create(+ workflow_execution=execution,+ file_name=f"{uuid.uuid4().hex[:6]}.pdf",+ status=status,+ execution_time=1.5,+ )+ WorkflowFileExecution.objects.filter(pk=file_execution.pk).update(+ created_at=self.now - timedelta(hours=hours_ago)+ )+ file_execution.refresh_from_db()+ if tokens:+ Usage.objects.create(+ organization=self.org,+ run_id=file_execution.pk,+ adapter_instance_id=str(uuid.uuid4()),+ usage_type=UsageType.LLM,+ model_name="gpt-4o-mini",+ embedding_tokens=0,+ prompt_tokens=tokens,+ completion_tokens=tokens,+ total_tokens=tokens * 2,+ cost_in_dollars=0.25,+ )+ return file_execution++ def _get(self, **params):+ # refresh=true skips the response cache, which would otherwise answer a+ # repeated query from an earlier test step. It is not a paged-form param.+ params.setdefault("refresh", "true")+ request = APIRequestFactory().get("/metrics/recent-activity/", params)+ force_authenticate(request, user=self.owner)+ return DashboardMetricsViewSet.as_view({"get": "recent_activity"})(request)++ def _ids(self, response) -> list[str]:+ return [row["id"] for row in response.data["activity"]]+++class DefaultFormTests(_Seed, TestCase):+ """No new parameter: the response is the original one, byte for byte."""++ def test_default_response_is_unchanged(self) -> None:+ etl, task, api = (+ self._pipeline("ETL"),+ self._pipeline("TASK"),+ self._deployment(),+ )+ manual = self._workflow()+ e = self._file(etl, COMPLETED, 1, tokens=10)+ t = self._file(task, ERROR, 2)+ a = self._file(api, COMPLETED, 3)+ m = self._file(None, EXECUTING, 4, workflow=manual)++ def row(fe, type_, tokens=0, cost=0):+ # The original key order, which JSON clients see.+ return {+ "id": str(fe.pk),+ "execution_id": str(fe.workflow_execution_id),+ "type": type_,+ "file_name": fe.file_name,+ "status": fe.status,+ "workflow_name": fe.workflow_execution.workflow.workflow_name,+ "created_at": fe.created_at.isoformat(),+ "execution_time": 1.5,+ "total_tokens": tokens,+ "cost": cost,+ }++ expected = {+ "activity": [+ row(e, "etl", tokens=20, cost=0.25),+ # A Task pipeline run stays "workflow" here; only `surface` differs.+ row(t, "workflow"),+ row(a, "api"),+ row(m, "workflow"),+ ]+ }+ response = self._get()+ self.assertEqual(response.status_code, 200)+ self.assertEqual(+ JSONRenderer().render(response.data), JSONRenderer().render(expected)+ )++ def test_limit_still_applies_and_adds_nothing(self) -> None:+ etl = self._pipeline("ETL")+ for hours in range(1, 4):+ self._file(etl, COMPLETED, hours)++ response = self._get(limit="2")+ self.assertEqual(list(response.data), ["activity"])+ self.assertEqual(len(response.data["activity"]), 2)+ self.assertNotIn("surface", response.data["activity"][0])+ # The old cap and fallback are kept.+ self.assertEqual(len(self._get(limit="500").data["activity"]), 3)+ self.assertEqual(len(self._get(limit="x").data["activity"]), 3)+ # A blank paged-form parameter does not switch forms.+ response = self._get(limit="2", status="")+ self.assertEqual(list(response.data), ["activity"])+ self.assertEqual(len(response.data["activity"]), 2)+++class PagedFormTests(_Seed, TestCase):+ def setUp(self) -> None:+ super().setUp()+ self.etl = self._pipeline("ETL")+ self.task = self._pipeline("TASK")+ self.default = self._pipeline("DEFAULT")+ self.api = self._deployment()+ self.manual = self._workflow()+ # Newest first: hours ago 1..7.+ self.rows = {+ "etl_ok": self._file(self.etl, COMPLETED, 1),+ "task_err": self._file(self.task, ERROR, 2),+ "api_ok": self._file(self.api, COMPLETED, 3),+ "manual_err": self._file(None, ERROR, 4, workflow=self.manual),+ "default_ok": self._file(self.default, COMPLETED, 5),+ "etl_running": self._file(self.etl, EXECUTING, 6),+ # Outside a 2-day range.+ "etl_old": self._file(self.etl, ERROR, 24 * 3),+ }++ def _range(self, days: int = 2) -> dict:+ return {+ "start_date": (self.now - timedelta(days=days)).isoformat(),+ "end_date": self.now.isoformat(),+ }++ def _expect_ids(self, *names: str) -> list[str]:+ return [str(self.rows[n].pk) for n in names]++ def test_any_new_param_switches_to_the_paged_form(self) -> None:+ for param, value in (+ ("start_date", (self.now - timedelta(days=2)).isoformat()),+ ("end_date", self.now.isoformat()),+ ("status", COMPLETED),+ ("surface", "etl"),+ ("page", "1"),+ ("page_size", "5"),+ ):+ with self.subTest(param):+ response = self._get(**{param: value})+ self.assertEqual(response.status_code, 200, response.data)+ self.assertEqual(+ set(response.data),+ {+ "activity",+ "count",+ "status_counts",+ "page",+ "page_size",+ "start_date",+ "end_date",+ },+ )+ self.assertIn("surface", response.data["activity"][0])++ def test_range_counts_and_surface(self) -> None:+ response = self._get(**self._range())+ self.assertEqual(response.status_code, 200)+ self.assertEqual(+ self._ids(response),+ self._expect_ids(+ "etl_ok",+ "task_err",+ "api_ok",+ "manual_err",+ "default_ok",+ "etl_running",+ ),+ )+ self.assertEqual(response.data["count"], 6)+ self.assertEqual(+ response.data["status_counts"],+ {+ "PENDING": 0,+ "EXECUTING": 1,+ "COMPLETED": 3,+ "STOPPED": 0,+ "ERROR": 2,+ },+ )+ self.assertEqual((response.data["page"], response.data["page_size"]), (1, 20))+ self.assertEqual(+ [(row["type"], row["surface"]) for row in response.data["activity"]],+ [+ ("etl", "etl"),+ ("workflow", "task"),+ ("api", "api"),+ ("workflow", "workflow"),+ ("workflow", "workflow"),+ ("etl", "etl"),+ ],+ )++ def test_range_defaults_to_the_last_30_days(self) -> None:+ old = self._file(self.etl, COMPLETED, 24 * 31)+ response = self._get(page="1")+ self.assertNotIn(str(old.pk), self._ids(response))+ self.assertIn(str(self.rows["etl_old"].pk), self._ids(response))+ self.assertEqual(response.data["count"], 7)++ def test_status_filter_narrows_rows_and_count_not_status_counts(self) -> None:+ response = self._get(status="error,STOPPED", **self._range())+ self.assertEqual(self._ids(response), self._expect_ids("task_err", "manual_err"))+ self.assertEqual(response.data["count"], 2)+ # Chip counts stay those of the whole range.+ self.assertEqual(response.data["status_counts"]["COMPLETED"], 3)+ self.assertEqual(sum(response.data["status_counts"].values()), 6)++ def test_surface_filter(self) -> None:+ cases = {+ "etl": ["etl_ok", "etl_running"],+ "task": ["task_err"],+ "api": ["api_ok"],+ "workflow": ["manual_err", "default_ok"],+ "task,api": ["task_err", "api_ok"],+ "etl,task,api,workflow": [+ "etl_ok",+ "task_err",+ "api_ok",+ "manual_err",+ "default_ok",+ "etl_running",+ ],+ }+ for surface, names in cases.items():+ with self.subTest(surface):+ response = self._get(surface=surface, **self._range())+ self.assertEqual(self._ids(response), self._expect_ids(*names))+ self.assertEqual(response.data["count"], len(names))+ self.assertEqual(+ sum(response.data["status_counts"].values()), len(names)+ )++ def test_surface_and_status_together(self) -> None:+ response = self._get(surface="workflow", status=ERROR, **self._range())+ self.assertEqual(self._ids(response), self._expect_ids("manual_err"))+ self.assertEqual(response.data["count"], 1)+ self.assertEqual(+ response.data["status_counts"]["COMPLETED"], 1+ ) # default_ok++ def test_paging(self) -> None:+ all_ids = self._expect_ids(+ "etl_ok", "task_err", "api_ok", "manual_err", "default_ok", "etl_running"+ )+ pages = [+ self._ids(self._get(page=str(p), page_size="4", **self._range()))+ for p in (1, 2, 3)+ ]+ self.assertEqual(pages, [all_ids[:4], all_ids[4:], []])++ def test_paging_is_stable_when_created_at_ties(self) -> None:+ tied = [self._file(self.etl, COMPLETED, 0.5) for _ in range(4)]+ WorkflowFileExecution.objects.filter(pk__in=[t.pk for t in tied]).update(+ created_at=self.now - timedelta(minutes=30)+ )+ seen = []+ for page in (1, 2):+ seen += self._ids(self._get(page=str(page), page_size="2", surface="etl"))+ # The -id tie-break, exactly.+ self.assertEqual(seen, [str(pk) for pk in sorted((t.pk for t in tied), reverse=True)])++ def test_empty_range(self) -> None:+ response = self._get(+ start_date=(self.now + timedelta(days=1)).isoformat(),+ end_date=(self.now + timedelta(days=2)).isoformat(),+ )+ self.assertEqual(response.data["activity"], [])+ self.assertEqual(response.data["count"], 0)+ self.assertEqual(response.data["status_counts"], dict.fromkeys(ALL_STATUSES, 0))++ def test_other_organisations_are_not_counted(self) -> None:+ other = Organization.objects.create(+ name="org-b", display_name="Org B", organization_id="org-b"+ )+ execution = WorkflowExecution.objects.create(+ workflow=self._workflow(org=other), status=ERROR+ )+ file_execution = WorkflowFileExecution.objects.create(+ workflow_execution=execution, file_name="b.pdf", status=ERROR+ )+ WorkflowFileExecution.objects.filter(pk=file_execution.pk).update(+ created_at=self.now - timedelta(hours=1)+ )+ response = self._get(**self._range())+ self.assertEqual(response.data["count"], 6)+ self.assertEqual(response.data["status_counts"]["ERROR"], 2)++ def test_invalid_params_are_rejected(self) -> None:+ cases = {+ "status": {"status": "FAILED"},+ "empty status": {"status": ","},+ "surface": {"surface": "pipeline"},+ "page": {"page": "0"},+ "page too far": {"page": "10001"},+ "page_size": {"page_size": "101"},+ "date": {"start_date": "yesterday"},+ "order": {+ "start_date": self.now.isoformat(),+ "end_date": (self.now - timedelta(days=1)).isoformat(),+ },+ "too long": {+ "start_date": (self.now - timedelta(days=400)).isoformat(),+ "end_date": self.now.isoformat(),+ },+ }+ for name, params in cases.items():+ with self.subTest(name):+ self.assertEqual(self._get(**params).status_code, 400)++ def test_no_organization_is_forbidden(self) -> None:+ UserContext.set_organization_identifier(None)+ self.assertEqual(self._get(page="1").status_code, 403)+++class ContractTests(SimpleTestCase):+ """The drf-spectacular annotation is the contract, with the README.++ This checks the schema's names, not a real response's shape.+ """++ def test_schema_documents_both_forms(self) -> None:+ schema = SchemaGenerator(patterns=urls.urlpatterns).get_schema(+ request=None, public=True+ )+ (operation,) = (+ op+ for path in schema["paths"].values()+ for op in path.values()+ if op.get("operationId") == "metrics_recent_activity"+ )+ self.assertEqual(+ {p["name"] for p in operation["parameters"]},+ {+ "limit",+ "refresh",+ "start_date",+ "end_date",+ "status",+ "surface",+ "page",+ "page_size",+ },+ )+ self.assertLessEqual({"200", "400", "401", "403", "429"}, set(operation["responses"]))+ components = schema["components"]["schemas"]+ self.assertLessEqual(+ {"activity", "count", "status_counts", "page", "page_size"},+ set(components["RecentActivityResponse"]["properties"]),+ )+ row = components["RecentActivityRow"]+ self.assertIn("surface", row["properties"])+ self.assertNotIn("surface", row["required"])+ # Round-trips as JSON, as a generated schema must.+ json.dumps(schema, default=str)diff --git a/backend/dashboard_metrics/views.py b/backend/dashboard_metrics/views.pyindex 6a1147402..3c053a29e 100644--- a/backend/dashboard_metrics/views.py+++ b/backend/dashboard_metrics/views.py@@ -10,8 +10,16 @@ from django.db.models import Avg, Max, Min, Sumfrom django.db.models.functions import TruncDay, TruncHour, TruncWeekfrom django.utils import timezonefrom django_filters.rest_framework import DjangoFilterBackend+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, extend_schema, inline_serializer+from drf_standardized_errors.openapi_serializers import (+ ErrorResponse401Serializer,+ ErrorResponse403Serializer,+ ErrorResponse429Serializer,+ ValidationErrorResponseSerializer,+)from permissions.permission import IsOrganizationMember-from rest_framework import status, viewsets+from rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import PermissionDeniedfrom rest_framework.permissions import IsAuthenticated@@ -29,6 +37,7 @@ from .cache import (mset_metrics_buckets,)from .models import (+ ActivitySurface,EventMetricsDaily,EventMetricsHourly,EventMetricsMonthly,@@ -39,6 +48,7 @@ from .serializers import (DeploymentUsageQuerySerializer,EventMetricsHourlySerializer,MetricsQuerySerializer,+ RecentActivityQuerySerializer,)from .services import MetricsQueryService@@ -885,6 +895,86 @@ class DashboardMetricsViewSet(viewsets.ReadOnlyModelViewSet):return Response(response_data, status=status.HTTP_200_OK)+ @extend_schema(+ operation_id="metrics_recent_activity",+ tags=["dashboard-metrics"],+ parameters=[+ RecentActivityQuerySerializer,+ OpenApiParameter(+ "limit",+ OpenApiTypes.INT,+ description="Default form only: rows to return (default 10, max 50).",+ ),+ OpenApiParameter(+ "refresh", OpenApiTypes.BOOL, description="true bypasses the cache."+ ),+ ],+ request=None,+ responses={+ 200: inline_serializer(+ name="RecentActivityResponse",+ fields={+ "activity": inline_serializer(+ name="RecentActivityRow",+ many=True,+ fields={+ "id": serializers.UUIDField(),+ "execution_id": serializers.UUIDField(),+ "type": serializers.ChoiceField(+ choices=["etl", "api", "workflow"]+ ),+ "surface": serializers.ChoiceField(+ choices=ActivitySurface.choices,+ required=False,+ help_text="Paged form only.",+ ),+ "file_name": serializers.CharField(),+ "status": serializers.CharField(),+ "workflow_name": serializers.CharField(),+ "created_at": serializers.DateTimeField(),+ "execution_time": serializers.FloatField(allow_null=True),+ "total_tokens": serializers.IntegerField(),+ "cost": serializers.FloatField(),+ },+ ),+ "start_date": serializers.DateTimeField(+ required=False, help_text="Paged form only."+ ),+ "end_date": serializers.DateTimeField(+ required=False, help_text="Paged form only."+ ),+ "page": serializers.IntegerField(+ required=False, help_text="Paged form only."+ ),+ "page_size": serializers.IntegerField(+ required=False, help_text="Paged form only."+ ),+ "count": serializers.IntegerField(+ required=False,+ help_text="Paged form only: rows matching every filter.",+ ),+ "status_counts": serializers.DictField(+ child=serializers.IntegerField(),+ required=False,+ help_text=(+ "Paged form only: rows per status in the range and "+ "surfaces, ignoring the status filter."+ ),+ ),+ },+ ),+ 400: ValidationErrorResponseSerializer,+ 401: ErrorResponse401Serializer,+ 403: ErrorResponse403Serializer,+ 429: ErrorResponse429Serializer,+ },+ description=(+ "Recent file executions, newest first. Without any of start_date, "+ "end_date, status, surface, page or page_size (with a value) the response is the "+ "original one: limit rows and no counts. Passing any of them returns "+ "the paged form with counts. See dashboard_metrics/README.md."+ ),+ )@action(detail=False, methods=["get"], url_path="recent-activity")@cache_metrics_response(endpoint="recent_activity")def recent_activity(self, request: Request) -> Response:@@ -897,13 +987,21 @@ class DashboardMetricsViewSet(viewsets.ReadOnlyModelViewSet):Query Parameters:limit: Maximum records to return (default 10, max 50)+ The paged form (DG-02) is described in the README.Returns:200: List of recent activity items- 500: Error occurred+ 400: Invalid paged-form parameters"""organization = self._get_organization()org_id = str(organization.id)++ if any(+ request.query_params.get(param)+ for param in RecentActivityQuerySerializer.PAGED_PARAMS+ ):+ return self._recent_activity_page(request, org_id)+try:limit = min(int(request.query_params.get("limit", 10)), 50)except (ValueError, TypeError):@@ -912,6 +1010,30 @@ class DashboardMetricsViewSet(viewsets.ReadOnlyModelViewSet):data = MetricsQueryService.get_recent_activity(org_id, limit)return Response({"activity": data})+ def _recent_activity_page(self, request: Request, org_id: str) -> Response:+ serializer = RecentActivityQuerySerializer(data=request.query_params)+ serializer.is_valid(raise_exception=True)+ params = serializer.validated_data++ page = MetricsQueryService.get_activity_page(+ org_id,+ start_date=params["start_date"],+ end_date=params["end_date"],+ statuses=params.get("status"),+ surfaces=params.get("surface"),+ page=params["page"],+ page_size=params["page_size"],+ )+ return Response(+ {+ "start_date": params["start_date"].isoformat(),+ "end_date": params["end_date"].isoformat(),+ "page": params["page"],+ "page_size": params["page_size"],+ **page,+ }+ )+@action(detail=False, methods=["get"], url_path="workflow-token-usage")@cache_metrics_response(endpoint="workflow_token_usage")def workflow_token_usage(self, request: Request) -> Response: