Skip to content

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

UN-4387 [FEAT] Dashboard API for failing pipelines and deployments, and failed pages by source (#2352)

ali0d6c5b99ef6a
diff --git a/backend/dashboard_metrics/README.md b/backend/dashboard_metrics/README.md
index 61a61c40d..58c29b4f1 100644
--- a/backend/dashboard_metrics/README.md
+++ b/backend/dashboard_metrics/README.md
@@ -613,6 +613,8 @@ 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 |
+| `/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 |
### Auto Source Selection
@@ -684,6 +686,89 @@ Override with `?source=hourly|daily|monthly`
}
```
+### Attention and attribution (PB-T14)
+
+Both take only `start_date` and `end_date` (ISO 8601; default the last 30
+days, at most 365 days apart), are read live and are not cached. JSON Schemas for both responses are in
+[`contract/`](contract/); tests validate real responses against them.
+
+#### `/attention/`
+
+```json
+{
+ "start_date": "2026-09-16T00:00:00+00:00",
+ "end_date": "2026-10-16T00:00:00+00:00",
+ "items": [
+ {
+ "kind": "failing_pipeline",
+ "id": "6f1c2a4e-1d1b-4c8e-9a51-0c7b2f1e9d10",
+ "name": "Nightly invoices",
+ "count": 7,
+ "since": "2026-10-10T02:00:00+00:00",
+ "route": {"key": "etl_pipeline.detail", "params": {"id": "6f1c2a4e-…"}},
+ "details": {
+ "last_failure": "2026-10-15T02:00:00+00:00",
+ "last_success": "2026-10-09T02:00:00+00:00",
+ "pipeline_type": "ETL"
+ }
+ }
+ ],
+ "failed_kinds": []
+}
+```
+
+| kind | where | item | `count` | `since` |
+|---|---|---|---|---|
+| `failing_pipeline` | OSS | one per active ETL or Task pipeline | finished runs failed in a row | first failure of the streak |
+| `failing_deployment` | OSS | one per active API deployment | finished runs failed in a row | first failure of the streak |
+| others | cloud | defined by the cloud app that registers the kind | | |
+
+- A row is failing when each of its last five finished runs ended in ERROR and
+ the latest of them is in the range. Runs still pending or executing are
+ skipped; a STOPPED or COMPLETED run ends the streak. The rule and why it is
+ ERROR only are in `workflow_manager/workflow_v2/failing_streaks.py`.
+- `route` uses the route-registry keys proposed for global search (#2343), or
+ is `null`.
+ `details` is kind-specific.
+- Kinds are sorted by each provider's `order` (OSS: `failing_pipeline` = 10,
+ `failing_deployment` = 20; cloud kinds choose their own); within a kind,
+ newest failure first.
+- The range filters on when the newest failure happened; the failing test
+ always uses a row's latest runs.
+- `failed_kinds` names kinds whose provider raised or returned an item that
+ breaks the contract; never show those as "nothing needs attention".
+- A cloud app adds a kind by subclassing `attention.AttentionProvider` and
+ calling `register_attention_provider()` from its `AppConfig.ready()`.
+
+#### `/attribution/`
+
+```json
+{
+ "start_date": "2026-09-16T00:00:00+00:00",
+ "end_date": "2026-10-16T00:00:00+00:00",
+ "total_failed_pages": 708,
+ "sources": [
+ {"id": "6f1c…", "name": "Nightly invoices", "type": "etl_pipeline",
+ "failed_pages": 512, "share": 0.7232}
+ ],
+ "days": [
+ {"date": "2026-10-10", "failed_pages": 610,
+ "sources": [{"id": "6f1c…", "failed_pages": 512}]}
+ ]
+}
+```
+
+- Built from the same queryset as the `failed_pages` metric
+ (`MetricsQueryService.failed_file_executions_with_pages`), so
+ `total_failed_pages` and each day's `failed_pages` equal that series for the
+ same range.
+- A source is the pipeline or API deployment that ran the file; a run with no
+ pipeline is attributed to its workflow (`type: workflow`), and a source whose
+ pipeline, deployment or workflow no longer exists has `type: deleted` and
+ `name: null`.
+- Sources are ordered by failed pages, most first; `share` is the fraction of
+ `total_failed_pages`, rounded to 4 places.
+
---
## Caching Strategy
diff --git a/backend/dashboard_metrics/apps.py b/backend/dashboard_metrics/apps.py
index 00c41bd55..8b3ce5b94 100644
--- a/backend/dashboard_metrics/apps.py
+++ b/backend/dashboard_metrics/apps.py
@@ -9,3 +9,9 @@ class DashboardMetricsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "dashboard_metrics"
verbose_name = "Dashboard Metrics"
+
+ def ready(self) -> None:
+ from .attention import OSS_PROVIDERS, register_attention_provider
+
+ for provider in OSS_PROVIDERS:
+ register_attention_provider(provider)
diff --git a/backend/dashboard_metrics/attention.py b/backend/dashboard_metrics/attention.py
new file mode 100644
index 000000000..07b08baa8
--- /dev/null
+++ b/backend/dashboard_metrics/attention.py
@@ -0,0 +1,267 @@
+"""The dashboard's "needs attention" feed (PB-T14).
+
+Each kind of item comes from a provider. OSS registers the failing pipeline and
+failing deployment providers from ``DashboardMetricsConfig.ready()``; a cloud
+app registers its own kinds from its own ``ready()``, so a kind exists exactly
+where its app is installed and OSS never names a cloud kind. The response contract is ``contract/attention-response.schema.json``.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any
+
+from api_v2.models import APIDeployment
+from django.db import transaction
+from django.db.models import QuerySet
+from pipeline_v2.models import Pipeline
+from rest_framework.utils.encoders import JSONEncoder
+from workflow_manager.workflow_v2.failing_streaks import FailingStreak, failing_streaks
+
+logger = logging.getLogger(__name__)
+
+# Same pattern the published JSON Schema requires of ``kind``.
+_KIND = re.compile(r"^[a-z][a-z0-9_]*$")
+# Same pattern the published JSON Schema requires of ``route.key``.
+_ROUTE_KEY = re.compile(r"^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$")
+
+
+@dataclass(frozen=True)
+class AttentionItem:
+ """One open item.
+
+ ``since`` is when the item began (for failing rows, the first failure of
+ the streak). ``route`` names a frontend route-registry key (see #2343) and
+ its params.
+ """
+
+ kind: str
+ id: str
+ name: str | None
+ count: int
+ since: datetime | None
+ route_key: str | None = None
+ route_params: dict[str, str] = field(default_factory=dict)
+ details: dict[str, Any] = field(default_factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "kind": self.kind,
+ "id": self.id,
+ "name": self.name,
+ "count": self.count,
+ "since": self.since.isoformat() if self.since else None,
+ "route": (
+ {"key": self.route_key, "params": self.route_params}
+ if self.route_key
+ else None
+ ),
+ "details": self.details,
+ }
+
+
+class AttentionProvider(ABC):
+ """Source of one kind of attention item."""
+
+ kind: str
+ order: int
+
+ @abstractmethod
+ def items(
+ self, organization: Any, start_date: datetime, end_date: datetime
+ ) -> list[AttentionItem]:
+ """Open items of this kind for ``organization`` in the range."""
+
+
+_providers: dict[str, AttentionProvider] = {}
+
+
+def _is_int(value: Any) -> bool:
+ return isinstance(value, int) and not isinstance(value, bool)
+
+
+def register_attention_provider(provider: AttentionProvider) -> None:
+ """Register ``provider`` under its ``kind``.
+
+ Re-registering the same class is a no-op, so a repeated ``ready()`` is
+ harmless; a different class claiming a taken kind is a wiring bug.
+ """
+ if not _KIND.fullmatch(provider.kind):
+ raise ValueError(f"Invalid attention kind '{provider.kind}'")
+ if not _is_int(provider.order):
+ raise ValueError(f"Attention kind '{provider.kind}' needs an int order")
+ existing = _providers.get(provider.kind)
+ if existing is not None:
+ if type(existing) is type(provider):
+ return
+ raise ValueError(
+ f"Attention kind '{provider.kind}' is already registered by "
+ f"{type(existing).__name__}"
+ )
+ _providers[provider.kind] = provider
+
+
+def unregister_attention_provider(kind: str) -> None:
+ _providers.pop(kind, None)
+
+
+def get_attention_providers() -> list[AttentionProvider]:
+ """Registered providers in display order."""
+ return sorted(_providers.values(), key=lambda p: (p.order, p.kind))
+
+
+def collect_attention(
+ organization: Any, start_date: datetime, end_date: datetime
+) -> tuple[list[dict[str, Any]], list[str]]:
+ """Every provider's items, serialized, and the kinds whose provider failed.
+
+ A provider fails when it raises, or returns an item that is not of its own
+ kind or whose fields do not have the contract's types (``_serialize``). It
+ is logged and named, never shown as "nothing needs attention", and the
+ other providers' items still return.
+ """
+ items: list[dict[str, Any]] = []
+ failed: list[str] = []
+ for provider in get_attention_providers():
+ try:
+ # A savepoint per provider: with ATOMIC_REQUESTS on, a database
+ # error would otherwise abort the request's transaction and fail
+ # every provider after this one.
+ with transaction.atomic():
+ provided = [
+ _serialize(provider, item)
+ for item in provider.items(organization, start_date, end_date)
+ ]
+ except Exception:
+ logger.exception(
+ "Attention provider '%s' failed for organization %s (%s to %s)",
+ provider.kind,
+ getattr(organization, "organization_id", organization),
+ start_date.isoformat(),
+ end_date.isoformat(),
+ )
+ failed.append(provider.kind)
+ else:
+ items.extend(provided)
+ return items, failed
+
+
+def _serialize(provider: AttentionProvider, item: AttentionItem) -> dict[str, Any]:
+ if item.kind != provider.kind:
+ raise ValueError(f"Item of kind '{item.kind}' from provider '{provider.kind}'")
+ if not _is_int(item.count) or item.count < 0:
+ raise ValueError(f"Item count must be a non-negative int, got {item.count!r}")
+ if not isinstance(item.id, str) or not isinstance(item.name, str | None):
+ raise ValueError(
+ f"Item id must be a string and name a string or None, "
+ f"got {item.id!r} and {item.name!r}"
+ )
+ if not isinstance(item.since, datetime | None) or (
+ item.since is not None and item.since.tzinfo is None
+ ):
+ raise ValueError(f"Item since must be an aware datetime, got {item.since!r}")
+ if item.route_key is not None and not _ROUTE_KEY.fullmatch(str(item.route_key)):
+ raise ValueError(f"Invalid route key {item.route_key!r}")
+ if not isinstance(item.route_params, dict) or not all(
+ isinstance(k, str) and isinstance(v, str) for k, v in item.route_params.items()
+ ):
+ raise ValueError(
+ f"Route params must map strings to strings: {item.route_params!r}"
+ )
+ if item.route_params and item.route_key is None:
+ raise ValueError("Item has route params but no route key")
+ if not isinstance(item.details, dict):
+ raise ValueError(f"Item details must be a dict, got {item.details!r}")
+ serialized = item.to_dict()
+ # Render here, with the encoder the response uses, so a value it cannot
+ # encode fails this provider rather than the whole response.
+ json.dumps(serialized, cls=JSONEncoder)
+ return serialized
+
+
+class _FailingRowsProvider(AttentionProvider):
+ """Rows that ``failing_streaks`` finds failing, latest failure in range.
+
+ Inactive rows are left out: nothing runs them, so nothing needs doing.
+ """
+
+ @abstractmethod
+ def _rows(self, organization: Any) -> QuerySet[Any]:
+ """The org's active rows of this kind."""
+
+ @abstractmethod
+ def _item(self, streak: FailingStreak) -> AttentionItem:
+ """The item for one failing row."""
+
+ def items(
+ self, organization: Any, start_date: datetime, end_date: datetime
+ ) -> list[AttentionItem]:
+ streaks = failing_streaks(self._rows(organization), start_date, end_date)
+ return [self._item(streak) for streak in streaks]
+
+ def _base_item(
+ self, streak: FailingStreak, name: str, route_key: str, **details
+ ) -> AttentionItem:
+ return AttentionItem(
+ kind=self.kind,
+ id=str(streak.row.pk),
+ name=name,
+ count=streak.failures_in_a_row,
+ since=streak.failing_since,
+ route_key=route_key,
+ route_params={"id": str(streak.row.pk)},
+ details={
+ "last_failure": streak.last_failure.isoformat(),
+ "last_success": (
+ streak.last_success.isoformat() if streak.last_success else None
+ ),
+ **details,
+ },
+ )
+
+
+class FailingPipelineProvider(_FailingRowsProvider):
+ kind = "failing_pipeline"
+ order = 10
+
+ _ROUTE_KEYS = {
+ Pipeline.PipelineType.ETL: "etl_pipeline.detail",
+ Pipeline.PipelineType.TASK: "task_pipeline.detail",
+ }
+
+ def _rows(self, organization: Any) -> QuerySet[Any]:
+ return Pipeline._base_manager.filter(
+ organization=organization,
+ active=True,
+ pipeline_type__in=list(self._ROUTE_KEYS),
+ )
+
+ def _item(self, streak: FailingStreak) -> AttentionItem:
+ pipeline = streak.row
+ return self._base_item(
+ streak,
+ pipeline.pipeline_name,
+ self._ROUTE_KEYS[pipeline.pipeline_type],
+ pipeline_type=pipeline.pipeline_type,
+ )
+
+
+class FailingDeploymentProvider(_FailingRowsProvider):
+ kind = "failing_deployment"
+ order = 20
+
+ def _rows(self, organization: Any) -> QuerySet[Any]:
+ return APIDeployment._base_manager.filter(
+ organization=organization, is_active=True
+ )
+
+ def _item(self, streak: FailingStreak) -> AttentionItem:
+ return self._base_item(streak, streak.row.display_name, "api_deployment.detail")
+
+
+OSS_PROVIDERS = (FailingPipelineProvider(), FailingDeploymentProvider())
diff --git a/backend/dashboard_metrics/attribution.py b/backend/dashboard_metrics/attribution.py
new file mode 100644
index 000000000..4f279fbbf
--- /dev/null
+++ b/backend/dashboard_metrics/attribution.py
@@ -0,0 +1,161 @@
+"""Failed pages broken down by source and by day (PB-T14).
+
+Built from ``MetricsQueryService.failed_file_executions_with_pages``, the same
+queryset ``get_failed_pages`` sums for the ``failed_pages`` metric, so the
+totals here equal that series for the same range. The response contract is
+``contract/attribution-response.schema.json``.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections import defaultdict
+from datetime import datetime
+from enum import StrEnum
+from typing import Any
+
+from api_v2.models import APIDeployment
+from django.db.models import Sum
+from pipeline_v2.models import Pipeline
+from workflow_manager.workflow_v2.models.workflow import Workflow
+
+from dashboard_metrics.models import Granularity
+from dashboard_metrics.services import MetricsQueryService
+
+logger = logging.getLogger(__name__)
+
+
+class SourceType(StrEnum):
+ API_DEPLOYMENT = "api_deployment"
+ ETL_PIPELINE = "etl_pipeline"
+ TASK_PIPELINE = "task_pipeline"
+ # A pipeline of another type (e.g. APP, DEFAULT).
+ PIPELINE = "pipeline"
+ # Runs with no pipeline: a workflow run by hand.
+ WORKFLOW = "workflow"
+ # A source whose pipeline, deployment or workflow no longer exists.
+ DELETED = "deleted"
+
+
+_DELETED = (None, SourceType.DELETED)
+
+_PIPELINE_TYPES = {
+ Pipeline.PipelineType.ETL: SourceType.ETL_PIPELINE,
+ Pipeline.PipelineType.TASK: SourceType.TASK_PIPELINE,
+}
+
+
+def _describe_sources(
+ pipeline_ids: set, workflow_ids: set
+) -> dict[tuple[str, str], tuple[str | None, SourceType]]:
+ """Name and type of each source, keyed by ``(kind, id)``."""
+ described: dict[tuple[str, str], tuple[str | None, SourceType]] = {}
+ for d in APIDeployment._base_manager.filter(pk__in=pipeline_ids).values(
+ "pk", "display_name"
+ ):
+ described[("pipeline", str(d["pk"]))] = (
+ d["display_name"],
+ SourceType.API_DEPLOYMENT,
+ )
+ for p in Pipeline._base_manager.filter(pk__in=pipeline_ids).values(
+ "pk", "pipeline_name", "pipeline_type"
+ ):
+ described[("pipeline", str(p["pk"]))] = (
+ p["pipeline_name"],
+ _PIPELINE_TYPES.get(p["pipeline_type"], SourceType.PIPELINE),
+ )
+ for w in Workflow._base_manager.filter(pk__in=workflow_ids).values(
+ "pk", "workflow_name"
+ ):
+ described[("workflow", str(w["pk"]))] = (w["workflow_name"], SourceType.WORKFLOW)
+ return described
+
+
+def _source(
+ key: tuple[str, str],
+ pages: int,
+ total: int,
+ described: dict[tuple[str, str], tuple[str | None, SourceType]],
+) -> dict[str, Any]:
+ name, source_type = described.get(key, _DELETED)
+ return {
+ "id": key[1],
+ "name": name,
+ "type": source_type.value,
+ "failed_pages": pages,
+ "share": round(pages / total, 4) if total else 0.0,
+ }
+
+
+def failure_attribution(
+ organization_id: str, start_date: datetime, end_date: datetime
+) -> dict[str, Any]:
+ """Failed pages per day and per source for the range.
+
+ A source is the pipeline or API deployment that ran the file, or, for a run
+ with no pipeline, its workflow. Sources are ordered by failed pages, most
+ first; ``share`` is the source's fraction of the range's failed pages.
+ """
+ trunc_day = MetricsQueryService._get_trunc_func(Granularity.DAY)
+ rows = (
+ MetricsQueryService.failed_file_executions_with_pages(
+ organization_id, start_date, end_date
+ )
+ .annotate(period=trunc_day("created_at"))
+ .values(
+ "period",
+ "workflow_execution__pipeline_id",
+ "workflow_execution__workflow_id",
+ )
+ .annotate(value=Sum("pages"))
+ .order_by("period")
+ )
+
+ per_day: dict[datetime, dict[tuple[str, str], int]] = defaultdict(
+ lambda: defaultdict(int)
+ )
+ per_source: dict[tuple[str, str], int] = defaultdict(int)
+ pipeline_ids, workflow_ids = set(), set()
+ for row in rows:
+ pipeline_id = row["workflow_execution__pipeline_id"]
+ if pipeline_id is not None:
+ key = ("pipeline", str(pipeline_id))
+ pipeline_ids.add(pipeline_id)
+ else:
+ key = ("workflow", str(row["workflow_execution__workflow_id"]))
+ workflow_ids.add(row["workflow_execution__workflow_id"])
+ pages = row["value"] or 0
+ per_day[row["period"]][key] += pages
+ per_source[key] += pages
+
+ described = _describe_sources(pipeline_ids, workflow_ids)
+ total = sum(per_source.values())
+ unresolved = sorted(per_source.keys() - described.keys())
+ if unresolved:
+ logger.info(
+ "Attribution: %d sources reported as deleted for org %s: %s",
+ len(unresolved),
+ organization_id,
+ unresolved,
+ )
+
+ ordered = sorted(per_source.items(), key=lambda kv: (-kv[1], kv[0]))
+ return {
+ "start_date": start_date.isoformat(),
+ "end_date": end_date.isoformat(),
+ "total_failed_pages": total,
+ "sources": [_source(key, pages, total, described) for key, pages in ordered],
+ "days": [
+ {
+ "date": period.date().isoformat(),
+ "failed_pages": sum(sources.values()),
+ "sources": [
+ {"id": key[1], "failed_pages": pages}
+ for key, pages in sorted(
+ sources.items(), key=lambda kv: (-kv[1], kv[0])
+ )
+ ],
+ }
+ for period, sources in sorted(per_day.items())
+ ],
+ }
diff --git a/backend/dashboard_metrics/contract/attention-response.schema.json b/backend/dashboard_metrics/contract/attention-response.schema.json
new file mode 100644
index 000000000..05a47b52a
--- /dev/null
+++ b/backend/dashboard_metrics/contract/attention-response.schema.json
@@ -0,0 +1,52 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "unstract/dashboard-metrics/attention-response/v1",
+ "type": "object",
+ "required": ["start_date", "end_date", "items", "failed_kinds"],
+ "additionalProperties": false,
+ "properties": {
+ "start_date": {"type": "string", "format": "date-time"},
+ "end_date": {"type": "string", "format": "date-time"},
+ "items": {"type": "array", "items": {"$ref": "#/$defs/item"}},
+ "failed_kinds": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": {"type": "string", "pattern": "^[a-z][a-z0-9_]*$"}
+ }
+ },
+ "$defs": {
+ "item": {
+ "type": "object",
+ "required": ["kind", "id", "name", "count", "since", "route", "details"],
+ "additionalProperties": false,
+ "properties": {
+ "kind": {"type": "string", "pattern": "^[a-z][a-z0-9_]*$"},
+ "id": {"type": "string"},
+ "name": {"type": ["string", "null"]},
+ "count": {"type": "integer", "minimum": 0},
+ "since": {"type": ["string", "null"], "format": "date-time"},
+ "route": {
+ "oneOf": [
+ {"type": "null"},
+ {
+ "type": "object",
+ "required": ["key", "params"],
+ "additionalProperties": false,
+ "properties": {
+ "key": {
+ "type": "string",
+ "pattern": "^[a-z][a-z0-9_]*\\.[a-z][a-z0-9_]*$"
+ },
+ "params": {
+ "type": "object",
+ "additionalProperties": {"type": "string"}
+ }
+ }
+ }
+ ]
+ },
+ "details": {"type": "object"}
+ }
+ }
+ }
+}
diff --git a/backend/dashboard_metrics/contract/attribution-response.schema.json b/backend/dashboard_metrics/contract/attribution-response.schema.json
new file mode 100644
index 000000000..995167f3a
--- /dev/null
+++ b/backend/dashboard_metrics/contract/attribution-response.schema.json
@@ -0,0 +1,60 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "unstract/dashboard-metrics/attribution-response/v1",
+ "type": "object",
+ "required": ["start_date", "end_date", "total_failed_pages", "sources", "days"],
+ "additionalProperties": false,
+ "properties": {
+ "start_date": {"type": "string", "format": "date-time"},
+ "end_date": {"type": "string", "format": "date-time"},
+ "total_failed_pages": {"type": "integer", "minimum": 0},
+ "sources": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["id", "name", "type", "failed_pages", "share"],
+ "additionalProperties": false,
+ "properties": {
+ "id": {"type": "string"},
+ "name": {"type": ["string", "null"]},
+ "type": {
+ "enum": [
+ "api_deployment",
+ "etl_pipeline",
+ "task_pipeline",
+ "pipeline",
+ "workflow",
+ "deleted"
+ ]
+ },
+ "failed_pages": {"type": "integer", "minimum": 0},
+ "share": {"type": "number", "minimum": 0, "maximum": 1}
+ }
+ }
+ },
+ "days": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["date", "failed_pages", "sources"],
+ "additionalProperties": false,
+ "properties": {
+ "date": {"type": "string", "format": "date"},
+ "failed_pages": {"type": "integer", "minimum": 0},
+ "sources": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["id", "failed_pages"],
+ "additionalProperties": false,
+ "properties": {
+ "id": {"type": "string"},
+ "failed_pages": {"type": "integer", "minimum": 0}
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/backend/dashboard_metrics/services.py b/backend/dashboard_metrics/services.py
index f8591c4f0..0deaf76f4 100644
--- a/backend/dashboard_metrics/services.py
+++ b/backend/dashboard_metrics/services.py
@@ -410,6 +410,29 @@ class MetricsQueryService:
"""
trunc_func = MetricsQueryService._get_trunc_func(granularity)
+ # Main query: failed executions with their pages, grouped by period
+ return list(
+ MetricsQueryService.failed_file_executions_with_pages(
+ organization_id, start_date, end_date
+ )
+ .annotate(period=trunc_func("created_at"))
+ .values("period")
+ .annotate(value=Sum("pages"))
+ .order_by("period")
+ )
+
+ @staticmethod
+ def failed_file_executions_with_pages(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ ):
+ """Failed file executions in the range, each annotated with ``pages``.
+
+ The one definition of a failed page: ``get_failed_pages`` and the
+ dashboard's failure attribution both group this queryset, so their
+ totals agree by construction.
+ """
# Subquery: get pages for each file execution from page_usage
# Join on: page_usage.run_id = workflow_file_execution.id::text
pages_subquery = (
@@ -418,23 +441,12 @@ class MetricsQueryService:
.annotate(total=Sum("pages_processed"))
.values("total")[:1]
)
-
- # Main query: failed executions with their pages, grouped by period
- return list(
- WorkflowFileExecution.objects.filter(
- workflow_execution__workflow__organization_id=organization_id,
- status=ExecutionStatus.ERROR,
- created_at__gte=start_date,
- created_at__lte=end_date,
- )
- .annotate(
- pages=Coalesce(Subquery(pages_subquery), 0),
- period=trunc_func("created_at"),
- )
- .values("period")
- .annotate(value=Sum("pages"))
- .order_by("period")
- )
+ return WorkflowFileExecution.objects.filter(
+ workflow_execution__workflow__organization_id=organization_id,
+ status=ExecutionStatus.ERROR,
+ created_at__gte=start_date,
+ created_at__lte=end_date,
+ ).annotate(pages=Coalesce(Subquery(pages_subquery), 0))
@staticmethod
def get_hitl_reviews(
diff --git a/backend/dashboard_metrics/tests/test_attention_attribution.py b/backend/dashboard_metrics/tests/test_attention_attribution.py
new file mode 100644
index 000000000..5644adef2
--- /dev/null
+++ b/backend/dashboard_metrics/tests/test_attention_attribution.py
@@ -0,0 +1,597 @@
+"""Dashboard attention feed and failure attribution (PB-T14).
+
+* Each OSS attention kind appears with seeded data, and only when the row's
+ last five finished runs all ended in ERROR, the latest within the range.
+* Attribution per day and per source sums to the ``failed_pages`` metric for
+ the same range.
+* Both responses validate against the committed JSON Schemas.
+
+DB-backed Django ``TestCase`` → auto-marked ``integration`` by ``backend/conftest.py``.
+"""
+
+import json
+import uuid
+from datetime import timedelta
+from pathlib import Path
+from unittest import mock
+
+import jsonschema
+from account_usage.models import PageUsage
+from account_v2.models import Organization
+from api_v2.models import APIDeployment
+from django.db import connection
+from django.test import TestCase
+from django.utils import timezone
+from permissions.tests.base import CoOwnerOrgTestMixin
+from pipeline_v2.models import Pipeline
+from rest_framework.test import APIRequestFactory, force_authenticate
+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.failing_streaks import failing_streaks
+from workflow_manager.workflow_v2.models.execution import WorkflowExecution
+from workflow_manager.workflow_v2.models.workflow import Workflow
+
+from dashboard_metrics import attention
+from dashboard_metrics.attention import (
+ AttentionItem,
+ AttentionProvider,
+ FailingPipelineProvider,
+ get_attention_providers,
+ register_attention_provider,
+)
+from dashboard_metrics.attribution import SourceType
+from dashboard_metrics.models import Granularity
+from dashboard_metrics.services import MetricsQueryService
+from dashboard_metrics.views import DashboardMetricsViewSet
+
+CONTRACT = Path(__file__).parents[1] / "contract"
+ATTENTION_SCHEMA = json.loads((CONTRACT / "attention-response.schema.json").read_text())
+ATTRIBUTION_SCHEMA = json.loads(
+ (CONTRACT / "attribution-response.schema.json").read_text()
+)
+
+ERROR = ExecutionStatus.ERROR.value
+COMPLETED = ExecutionStatus.COMPLETED.value
+STOPPED = ExecutionStatus.STOPPED.value
+FORMATS = jsonschema.FormatChecker()
+
+
+class _Seed(CoOwnerOrgTestMixin):
+ def setUp(self) -> None:
+ self._seed_org()
+ self.now = timezone.now().replace(microsecond=0)
+
+ def _workflow(self, org: Organization | None = None, name: str = "wf") -> Workflow:
+ return Workflow.objects.create(
+ workflow_name=f"{name}-{uuid.uuid4().hex[:6]}",
+ organization=org or self.org,
+ created_by=self.owner,
+ )
+
+ def _pipeline(self, name: str, pipeline_type: str = "ETL", **fields) -> Pipeline:
+ return Pipeline.objects.create(
+ pipeline_name=name,
+ pipeline_type=pipeline_type,
+ workflow=self._workflow(),
+ organization=self.org,
+ created_by=self.owner,
+ active=fields.pop("active", True),
+ **fields,
+ )
+
+ def _deployment(self, name: str, **fields) -> APIDeployment:
+ return APIDeployment.objects.create(
+ api_name=f"api-{uuid.uuid4().hex[:6]}",
+ display_name=name,
+ workflow=self._workflow(),
+ organization=self.org,
+ created_by=self.owner,
+ **fields,
+ )
+
+ def _run(
+ self, row, status: str, hours_ago: float, workflow=None
+ ) -> WorkflowExecution:
+ execution = WorkflowExecution.objects.create(
+ workflow=workflow or row.workflow,
+ pipeline_id=row.pk if row is not None else None,
+ status=status,
+ )
+ WorkflowExecution.objects.filter(pk=execution.pk).update(
+ created_at=self.now - timedelta(hours=hours_ago)
+ )
+ return execution
+
+ def _runs(self, row, statuses_oldest_first: list[str], start_hours_ago: int = 10):
+ for i, status in enumerate(statuses_oldest_first):
+ self._run(row, status, start_hours_ago - i)
+
+ def _get(self, action: str, **params):
+ request = APIRequestFactory().get(f"/metrics/{action}/", params)
+ force_authenticate(request, user=self.owner)
+ return DashboardMetricsViewSet.as_view({"get": action})(request)
+
+
+class FailingStreakTests(_Seed, TestCase):
+ def test_five_failures_after_a_success_is_failing(self) -> None:
+ pipeline = self._pipeline("nightly")
+ self._runs(pipeline, [COMPLETED, ERROR, ERROR, ERROR, ERROR, ERROR, ERROR])
+
+ (streak,) = failing_streaks(Pipeline.objects.all())
+ self.assertEqual(streak.row, pipeline)
+ # The streak counts every failure since the success, not just five.
+ self.assertEqual(streak.failures_in_a_row, 6)
+ self.assertEqual(streak.last_success, self.now - timedelta(hours=10))
+ self.assertEqual(streak.failing_since, self.now - timedelta(hours=9))
+ self.assertEqual(streak.last_failure, self.now - timedelta(hours=4))
+
+ def test_never_succeeded_counts_every_failure(self) -> None:
+ pipeline = self._pipeline("new")
+ self._runs(pipeline, [ERROR] * 5)
+
+ (streak,) = failing_streaks(Pipeline.objects.all())
+ self.assertIsNone(streak.last_success)
+ self.assertEqual(streak.failures_in_a_row, 5)
+ self.assertEqual(streak.failing_since, self.now - timedelta(hours=10))
+
+ def test_streak_starts_after_the_last_run_that_did_not_fail(self) -> None:
+ cases = {
+ "errors before the last success": [ERROR, ERROR, COMPLETED],
+ "a stop": [COMPLETED, ERROR, STOPPED],
+ }
+ for name, before in cases.items():
+ with self.subTest(name):
+ pipeline = self._pipeline(name)
+ self._runs(pipeline, before + [ERROR] * 5)
+ (streak,) = (
+ s
+ for s in failing_streaks(Pipeline.objects.all())
+ if s.row == pipeline
+ )
+ self.assertEqual(streak.failures_in_a_row, 5)
+ self.assertEqual(streak.failing_since, self.now - timedelta(hours=7))
+
+ def test_unfinished_runs_are_skipped(self) -> None:
+ pipeline = self._pipeline("retrying")
+ self._runs(pipeline, [ERROR] * 5 + ["PENDING", "EXECUTING"])
+
+ (streak,) = failing_streaks(Pipeline.objects.all())
+ self.assertEqual(streak.failures_in_a_row, 5)
+ self.assertEqual(streak.last_failure, self.now - timedelta(hours=6))
+
+ def test_range_bounds_the_latest_failure(self) -> None:
+ pipeline = self._pipeline("nightly")
+ self._runs(pipeline, [ERROR] * 5) # latest failure 6 hours ago
+ hours = lambda h: self.now - timedelta(hours=h) # noqa: E731
+ cases = {
+ "inside": (hours(7), hours(5), [pipeline]),
+ "start after it": (hours(5), None, []),
+ "end before it": (None, hours(7), []),
+ }
+ for name, (start, end, expected) in cases.items():
+ with self.subTest(name):
+ rows = [
+ s.row for s in failing_streaks(Pipeline.objects.all(), start, end)
+ ]
+ self.assertEqual(rows, expected)
+
+ def test_not_failing(self) -> None:
+ cases = {
+ "four failures": [ERROR] * 4,
+ "a success among the last five": [ERROR, ERROR, COMPLETED, ERROR, ERROR],
+ "a stop among the last five": [ERROR, ERROR, STOPPED, ERROR, ERROR],
+ }
+ for name, statuses in cases.items():
+ with self.subTest(name):
+ self._runs(self._pipeline(name), statuses)
+ self.assertEqual(failing_streaks(Pipeline.objects.all()), [])
+
+ def test_one_query_whatever_the_number_of_rows(self) -> None:
+ for i in range(3):
+ self._runs(self._pipeline(f"p{i}"), [ERROR] * 5)
+ with self.assertNumQueries(1):
+ self.assertEqual(len(failing_streaks(Pipeline._base_manager.all())), 3)
+
+
+class AttentionTests(_Seed, TestCase):
+ def test_failing_pipeline_and_deployment_items(self) -> None:
+ etl = self._pipeline("nightly-etl")
+ self._runs(etl, [COMPLETED] + [ERROR] * 5)
+ task = self._pipeline("cleanup", pipeline_type="TASK")
+ self._runs(task, [ERROR] * 5, start_hours_ago=20)
+ deployment = self._deployment("Invoices API")
+ # The newest failure of all, yet listed after the pipelines.
+ self._runs(deployment, [ERROR] * 5, start_hours_ago=8)
+
+ response = self._get("attention")
+ self.assertEqual(response.status_code, 200)
+ jsonschema.validate(response.data, ATTENTION_SCHEMA, format_checker=FORMATS)
+ self.assertEqual(response.data["failed_kinds"], [])
+ by_id = {item["id"]: item for item in response.data["items"]}
+
+ self.assertEqual(
+ by_id[str(etl.pk)],
+ {
+ "kind": "failing_pipeline",
+ "id": str(etl.pk),
+ "name": "nightly-etl",
+ "count": 5,
+ "since": (self.now - timedelta(hours=9)).isoformat(),
+ "route": {"key": "etl_pipeline.detail", "params": {"id": str(etl.pk)}},
+ "details": {
+ "last_failure": (self.now - timedelta(hours=5)).isoformat(),
+ "last_success": (self.now - timedelta(hours=10)).isoformat(),
+ "pipeline_type": "ETL",
+ },
+ },
+ )
+ self.assertEqual(by_id[str(task.pk)]["route"]["key"], "task_pipeline.detail")
+ self.assertEqual(by_id[str(deployment.pk)]["kind"], "failing_deployment")
+ self.assertEqual(by_id[str(deployment.pk)]["name"], "Invoices API")
+ self.assertEqual(
+ by_id[str(deployment.pk)]["route"]["key"], "api_deployment.detail"
+ )
+ # Pipelines first, then deployments; newest failure first within a kind.
+ self.assertEqual(
+ [i["id"] for i in response.data["items"]],
+ [str(etl.pk), str(task.pk), str(deployment.pk)],
+ )
+
+ def test_excluded_rows(self) -> None:
+ self._runs(self._pipeline("paused", active=False), [ERROR] * 5)
+ self._runs(self._deployment("off", is_active=False), [ERROR] * 5)
+ # Failing, but its last failure is before the range.
+ self._runs(self._pipeline("old"), [ERROR] * 5, start_hours_ago=24 * 40)
+
+ other = Organization.objects.create(
+ name="org-b", display_name="Org B", organization_id="org-b"
+ )
+ # Of a type the feed lists, so only the organization filter drops them.
+ foreign = Pipeline.objects.create(
+ pipeline_name="foreign",
+ pipeline_type=Pipeline.PipelineType.ETL,
+ workflow=self._workflow(other),
+ organization=other,
+ created_by=self.owner,
+ active=True,
+ )
+ self._runs(foreign, [ERROR] * 5)
+ foreign_deployment = APIDeployment.objects.create(
+ api_name=f"api-{uuid.uuid4().hex[:6]}",
+ display_name="foreign",
+ workflow=self._workflow(other),
+ organization=other,
+ created_by=self.owner,
+ )
+ self._runs(foreign_deployment, [ERROR] * 5)
+
+ response = self._get("attention")
+ self.assertEqual(response.data["items"], [])
+
+ def test_only_etl_and_task_pipelines_are_listed(self) -> None:
+ etl = self._pipeline("nightly")
+ self._runs(etl, [ERROR] * 5)
+ self._runs(self._pipeline("app", pipeline_type="APP"), [ERROR] * 5)
+
+ response = self._get("attention")
+ self.assertEqual([i["id"] for i in response.data["items"]], [str(etl.pk)])
+ self.assertEqual(response.data["failed_kinds"], [])
+
+ def test_range_follows_the_query_parameters(self) -> None:
+ pipeline = self._pipeline("nightly")
+ self._runs(pipeline, [ERROR] * 5, start_hours_ago=24 * 40)
+ start = (self.now - timedelta(days=60)).isoformat()
+
+ response = self._get("attention", start_date=start)
+ self.assertEqual([i["id"] for i in response.data["items"]], [str(pipeline.pk)])
+
+
+class _Reviews(AttentionProvider):
+ kind = "test_reviews"
+ order = 30
+
+ def items(self, organization, start_date, end_date):
+ return [
+ AttentionItem(
+ kind=self.kind,
+ id="test_reviews",
+ name=None,
+ count=4,
+ since=start_date,
+ )
+ ]
+
+
+class _Broken(AttentionProvider):
+ kind = "test_broken"
+ order = 40
+
+ def items(self, organization, start_date, end_date):
+ raise RuntimeError("source unavailable")
+
+
+class _Malformed(AttentionProvider):
+ kind = "test_malformed"
+ order = 50
+
+ def items(self, organization, start_date, end_date):
+ return [AttentionItem(kind=self.kind, id="x", name=None, count=1, since="now")]
+
+
+class _DatabaseError(AttentionProvider):
+ kind = "test_database_error"
+ order = 1 # before the OSS providers, which query after it
+
+ def items(self, organization, start_date, end_date):
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT * FROM no_such_table")
+ return []
+
+
+class _First(AttentionProvider):
+ kind = "test_first"
+ order = 5
+
+ def items(self, organization, start_date, end_date):
+ return []
+
+
+class AttentionProviderRegistryTests(_Seed, TestCase):
+ """Test-only kinds on a copy of the registry, restored after each test."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ patcher = mock.patch.dict(attention._providers)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ # Registered out of order: _First sorts before the OSS providers.
+ for provider in (_Broken(), _Reviews(), _Malformed(), _First()):
+ register_attention_provider(provider)
+
+ def test_a_database_error_fails_only_its_own_provider(self) -> None:
+ register_attention_provider(_DatabaseError())
+ pipeline = self._pipeline("nightly")
+ self._runs(pipeline, [ERROR] * 5)
+
+ response = self._get("attention")
+ self.assertIn(str(pipeline.pk), [i["id"] for i in response.data["items"]])
+ self.assertEqual(
+ response.data["failed_kinds"],
+ ["test_database_error", "test_broken", "test_malformed"],
+ )
+
+ def test_contributed_kinds_and_failures(self) -> None:
+ response = self._get("attention")
+ jsonschema.validate(response.data, ATTENTION_SCHEMA, format_checker=FORMATS)
+ (item,) = response.data["items"]
+ self.assertEqual(
+ (item["kind"], item["count"], item["route"]), ("test_reviews", 4, None)
+ )
+ # A provider that raises, or returns an item that cannot be serialized,
+ # is named, never shown as "nothing needs attention".
+ self.assertEqual(response.data["failed_kinds"], ["test_broken", "test_malformed"])
+
+ def test_malformed_items_are_refused(self) -> None:
+ good = {"kind": "test_reviews", "id": "x", "name": None, "since": None}
+ cases = {
+ "another kind": {**good, "kind": "test_broken", "count": 1},
+ "negative count": {**good, "count": -1},
+ "bool count": {**good, "count": True},
+ "since not a datetime": {**good, "count": 1, "since": "now"},
+ "since a date": {**good, "count": 1, "since": self.now.date()},
+ "id not a string": {**good, "count": 1, "id": 7},
+ "name not a string": {**good, "count": 1, "name": 7},
+ "since without a timezone": {
+ **good,
+ "count": 1,
+ "since": self.now.replace(tzinfo=None),
+ },
+ "bad route key": {**good, "count": 1, "route_key": "Detail"},
+ "route param not a string": {
+ **good,
+ "count": 1,
+ "route_key": "x.detail",
+ "route_params": {"id": 7},
+ },
+ "details not a dict": {**good, "count": 1, "details": []},
+ "details not renderable": {**good, "count": 1, "details": {"x": object()}},
+ "route params without a key": {**good, "count": 1, "route_params": {"id": "x"}},
+ }
+ for name, fields in cases.items():
+ with self.subTest(name), self.assertRaises((ValueError, TypeError)):
+ attention._serialize(_Reviews(), AttentionItem(**fields))
+ self.assertEqual(
+ attention._serialize(_Reviews(), AttentionItem(**good, count=0))["count"], 0
+ )
+
+ def test_display_order(self) -> None:
+ kinds = [p.kind for p in get_attention_providers()]
+ self.assertEqual(kinds[0], "test_first")
+ self.assertLess(
+ kinds.index("failing_pipeline"), kinds.index("failing_deployment")
+ )
+ self.assertLess(kinds.index("failing_deployment"), kinds.index("test_reviews"))
+ self.assertLess(kinds.index("test_reviews"), kinds.index("test_broken"))
+
+ def test_registration_rules(self) -> None:
+ register_attention_provider(_Reviews()) # same class again: no-op
+
+ class _Other(_Reviews):
+ pass
+
+ with self.assertRaisesRegex(ValueError, "already registered"):
+ register_attention_provider(_Other())
+
+ class _BadKind(_Reviews):
+ kind = "Test-Reviews"
+
+ with self.assertRaisesRegex(ValueError, "Invalid attention kind"):
+ register_attention_provider(_BadKind())
+
+ class _BadOrder(_Reviews):
+ kind = "test_bad_order"
+ order = "30"
+
+ with self.assertRaisesRegex(ValueError, "needs an int order"):
+ register_attention_provider(_BadOrder())
+
+ def test_oss_providers_are_registered_by_the_app(self) -> None:
+ kinds = {p.kind for p in get_attention_providers()}
+ self.assertIn(FailingPipelineProvider.kind, kinds)
+
+
+class AttributionTests(_Seed, TestCase):
+ def _failed_file(self, execution, pages: int, days_ago: int, status=ERROR) -> None:
+ file_execution = WorkflowFileExecution.objects.create(
+ workflow_execution=execution,
+ file_name=f"{uuid.uuid4().hex[:6]}.pdf",
+ status=status,
+ )
+ WorkflowFileExecution.objects.filter(pk=file_execution.pk).update(
+ created_at=self.now - timedelta(days=days_ago)
+ )
+ PageUsage.objects.create(
+ organization_id=self.org.organization_id,
+ file_name=file_execution.file_name,
+ file_type="application/pdf",
+ run_id=str(file_execution.pk),
+ pages_processed=pages,
+ file_size=1024,
+ )
+
+ def _seed(self) -> dict:
+ etl = self._pipeline("nightly-etl")
+ deployment = self._deployment("Invoices API")
+ manual = self._workflow(name="manual")
+ gone = self._pipeline("removed")
+
+ etl_run = self._run(etl, ERROR, 1)
+ api_run = self._run(deployment, COMPLETED, 1)
+ manual_run = self._run(None, ERROR, 1, workflow=manual)
+ gone_run = self._run(gone, ERROR, 1)
+
+ self._failed_file(etl_run, 30, days_ago=2)
+ self._failed_file(etl_run, 20, days_ago=1)
+ self._failed_file(api_run, 10, days_ago=1)
+ self._failed_file(api_run, 99, days_ago=1, status=COMPLETED) # not a failure
+ self._failed_file(manual_run, 5, days_ago=2)
+ self._failed_file(gone_run, 1, days_ago=1)
+ gone_id = str(gone.pk)
+ Pipeline.objects.filter(pk=gone.pk).delete()
+
+ other = Organization.objects.create(
+ name="org-b", display_name="Org B", organization_id="org-b"
+ )
+ foreign_run = WorkflowExecution.objects.create(
+ workflow=self._workflow(other), status=ERROR
+ )
+ self._failed_file(foreign_run, 500, days_ago=1)
+ return {
+ "etl": str(etl.pk),
+ "api": str(deployment.pk),
+ "manual": str(manual.pk),
+ "gone": gone_id,
+ }
+
+ def test_breakdown_by_source_and_day(self) -> None:
+ ids = self._seed()
+ response = self._get("attribution")
+ self.assertEqual(response.status_code, 200)
+ jsonschema.validate(response.data, ATTRIBUTION_SCHEMA, format_checker=FORMATS)
+ data = response.data
+
+ self.assertEqual(data["total_failed_pages"], 66)
+ self.assertEqual(
+ [(s["id"], s["name"], s["type"], s["failed_pages"]) for s in data["sources"]],
+ [
+ (ids["etl"], "nightly-etl", "etl_pipeline", 50),
+ (ids["api"], "Invoices API", "api_deployment", 10),
+ (
+ ids["manual"],
+ Workflow.objects.get(pk=ids["manual"]).workflow_name,
+ "workflow",
+ 5,
+ ),
+ (ids["gone"], None, "deleted", 1),
+ ],
+ )
+ self.assertAlmostEqual(sum(s["share"] for s in data["sources"]), 1.0, places=3)
+ self.assertEqual(data["sources"][0]["share"], round(50 / 66, 4))
+
+ two_days_ago = (self.now - timedelta(days=2)).date().isoformat()
+ by_day = {d["date"]: d for d in data["days"]}
+ self.assertEqual(by_day[two_days_ago]["failed_pages"], 35)
+ self.assertEqual(
+ by_day[two_days_ago]["sources"],
+ [
+ {"id": ids["etl"], "failed_pages": 30},
+ {"id": ids["manual"], "failed_pages": 5},
+ ],
+ )
+
+ def test_totals_equal_the_failed_pages_series(self) -> None:
+ self._seed()
+ start = self.now - timedelta(days=30)
+ series = MetricsQueryService.get_failed_pages(
+ str(self.org.id), start, self.now, Granularity.DAY
+ )
+ response = self._get(
+ "attribution", start_date=start.isoformat(), end_date=self.now.isoformat()
+ )
+
+ self.assertEqual(
+ response.data["total_failed_pages"], sum(r["value"] for r in series)
+ )
+ self.assertEqual(
+ {d["date"]: d["failed_pages"] for d in response.data["days"]},
+ {r["period"].date().isoformat(): r["value"] for r in series},
+ )
+
+ def test_failed_files_without_pages(self) -> None:
+ pipeline = self._pipeline("no-pages")
+ WorkflowFileExecution.objects.create(
+ workflow_execution=self._run(pipeline, ERROR, 1),
+ file_name="x.pdf",
+ status=ERROR,
+ )
+
+ response = self._get("attribution")
+ self.assertEqual(response.status_code, 200)
+ jsonschema.validate(response.data, ATTRIBUTION_SCHEMA, format_checker=FORMATS)
+ self.assertEqual(response.data["total_failed_pages"], 0)
+ (source,) = response.data["sources"]
+ self.assertEqual((source["failed_pages"], source["share"]), (0, 0.0))
+
+ def test_other_pipeline_types(self) -> None:
+ app = self._pipeline("app", pipeline_type="APP")
+ self._failed_file(self._run(app, ERROR, 1), 3, days_ago=1)
+
+ response = self._get("attribution")
+ jsonschema.validate(response.data, ATTRIBUTION_SCHEMA, format_checker=FORMATS)
+ (source,) = response.data["sources"]
+ self.assertEqual((source["id"], source["type"]), (str(app.pk), "pipeline"))
+
+ def test_source_types_match_the_schema(self) -> None:
+ enum = ATTRIBUTION_SCHEMA["properties"]["sources"]["items"]["properties"]["type"]
+ self.assertEqual(set(enum["enum"]), {t.value for t in SourceType})
+
+ def test_empty_range(self) -> None:
+ response = self._get("attribution")
+ jsonschema.validate(response.data, ATTRIBUTION_SCHEMA, format_checker=FORMATS)
+ self.assertEqual(
+ (
+ response.data["total_failed_pages"],
+ response.data["sources"],
+ response.data["days"],
+ ),
+ (0, [], []),
+ )
+
+
+class OrganizationContextTests(_Seed, TestCase):
+ def test_no_organization_is_forbidden(self) -> None:
+ UserContext.set_organization_identifier(None)
+ for action in ("attention", "attribution"):
+ with self.subTest(action):
+ self.assertEqual(self._get(action).status_code, 403)
diff --git a/backend/dashboard_metrics/urls.py b/backend/dashboard_metrics/urls.py
index 36208a6b5..40a9cc26c 100644
--- a/backend/dashboard_metrics/urls.py
+++ b/backend/dashboard_metrics/urls.py
@@ -15,6 +15,8 @@ metrics_live_summary = DashboardMetricsViewSet.as_view({"get": "live_summary"})
metrics_live_series = DashboardMetricsViewSet.as_view({"get": "live_series"})
metrics_health = DashboardMetricsViewSet.as_view({"get": "health"})
metrics_recent_activity = DashboardMetricsViewSet.as_view({"get": "recent_activity"})
+metrics_attention = DashboardMetricsViewSet.as_view({"get": "attention"})
+metrics_attribution = DashboardMetricsViewSet.as_view({"get": "attribution"})
metrics_workflow_token_usage = DashboardMetricsViewSet.as_view(
{"get": "workflow_token_usage"}
)
@@ -40,6 +42,9 @@ urlpatterns = format_suffix_patterns(
metrics_workflow_token_usage,
name="metrics-workflow-token-usage",
),
+ # Dashboard attention feed and failure attribution (PB-T14)
+ path("attention/", metrics_attention, name="metrics-attention"),
+ path("attribution/", metrics_attribution, name="metrics-attribution"),
# Health check endpoint
path("health/", metrics_health, name="metrics-health"),
# Individual metric detail
diff --git a/backend/dashboard_metrics/views.py b/backend/dashboard_metrics/views.py
index 4c59d1536..6a1147402 100644
--- a/backend/dashboard_metrics/views.py
+++ b/backend/dashboard_metrics/views.py
@@ -21,6 +21,8 @@ from rest_framework.throttling import UserRateThrottle
from utils.filters.ordering_filter import DeterministicOrderingFilter
from utils.user_context import UserContext
+from .attention import collect_attention
+from .attribution import failure_attribution
from .cache import (
cache_metrics_response,
mget_metrics_buckets,
@@ -948,6 +950,60 @@ class DashboardMetricsViewSet(viewsets.ReadOnlyModelViewSet):
}
)
+ @action(detail=False, methods=["get"], url_path="attention")
+ def attention(self, request: Request) -> Response:
+ """Open items that need attention in the range (PB-T14).
+
+ Failing pipelines and API deployments in OSS; cloud apps add their own
+ kinds. Read live, not cached. Contract:
+ ``contract/attention-response.schema.json``.
+
+ Query Parameters:
+ start_date: Start of date range (ISO 8601). Default: 30 days ago
+ end_date: End of date range (ISO 8601). Default: now
+
+ Returns:
+ 200: Items, and ``failed_kinds`` naming any kind that could not load
+ """
+ query_serializer = MetricsQuerySerializer(data=request.query_params)
+ query_serializer.is_valid(raise_exception=True)
+ params = query_serializer.validated_data
+ organization = self._get_organization()
+
+ items, failed_kinds = collect_attention(
+ organization, params["start_date"], params["end_date"]
+ )
+ return Response(
+ {
+ "start_date": params["start_date"].isoformat(),
+ "end_date": params["end_date"].isoformat(),
+ "items": items,
+ "failed_kinds": failed_kinds,
+ }
+ )
+
+ @action(detail=False, methods=["get"], url_path="attribution")
+ def attribution(self, request: Request) -> Response:
+ """Failed pages by source and by day for the range (PB-T14).
+
+ Totals equal the ``failed_pages`` metric for the same range. Read
+ live, not cached. Contract: ``contract/attribution-response.schema.json``.
+
+ Query Parameters:
+ start_date: Start of date range (ISO 8601). Default: 30 days ago
+ end_date: End of date range (ISO 8601). Default: now
+ """
+ query_serializer = MetricsQuerySerializer(data=request.query_params)
+ query_serializer.is_valid(raise_exception=True)
+ params = query_serializer.validated_data
+ organization = self._get_organization()
+
+ return Response(
+ failure_attribution(
+ str(organization.id), params["start_date"], params["end_date"]
+ )
+ )
+
@action(detail=False, methods=["get"], url_path="health")
def health(self, request: Request) -> Response:
"""Health check endpoint for metrics system.
diff --git a/backend/workflow_manager/workflow_v2/failing_streaks.py b/backend/workflow_manager/workflow_v2/failing_streaks.py
new file mode 100644
index 000000000..a2c3c09da
--- /dev/null
+++ b/backend/workflow_manager/workflow_v2/failing_streaks.py
@@ -0,0 +1,115 @@
+"""Which pipelines and API deployments are failing right now.
+
+A row is failing when each of its last five finished runs ended in ERROR.
+Runs still PENDING or EXECUTING are skipped, so a queued retry does not hide a
+row that keeps failing. For each failing row this reports how many finished
+runs in a row have failed, when that streak began and when the row last
+succeeded.
+
+This is the list status dots' rule (ERROR is the red dot), not
+``unstract.core.data_models.is_failure_run``: that one also counts STOPPED and
+partly failed runs, which suits failure notifications but would list a pipeline
+someone stopped on purpose as broken.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import Any
+
+from django.contrib.postgres.expressions import ArraySubquery
+from django.db.models import Count, OuterRef, QuerySet, Subquery, Value
+from django.db.models.functions import Coalesce
+
+from unstract.core.data_models import ExecutionStatus
+from workflow_manager.workflow_v2.models.execution import WorkflowExecution
+
+FAILING_STREAK_RUNS = 5
+
+_FAILED = ExecutionStatus.ERROR.value
+_SUCCEEDED = ExecutionStatus.COMPLETED.value
+_FINISHED = sorted(ExecutionStatus.terminal_values())
+_EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
+
+
+@dataclass(frozen=True)
+class FailingStreak:
+ """One failing row."""
+
+ row: Any
+ failures_in_a_row: int
+ failing_since: datetime
+ last_failure: datetime
+ last_success: datetime | None
+
+
+def _finished_runs() -> QuerySet[WorkflowExecution]:
+ """The outer row's finished runs, newest first."""
+ return WorkflowExecution.objects.filter(
+ pipeline_id=OuterRef("pk"), status__in=_FINISHED
+ ).order_by("-created_at")
+
+
+def failing_streaks(
+ rows: QuerySet[Any],
+ start_date: datetime | None = None,
+ end_date: datetime | None = None,
+) -> list[FailingStreak]:
+ """Return the failing rows of ``rows``, newest failure first.
+
+ ``rows`` is a queryset of ``Pipeline`` or ``APIDeployment``; executions are
+ matched on ``WorkflowExecution.pipeline_id``. Rows with fewer than five
+ finished runs are never failing. ``start_date`` and ``end_date``, when
+ given, bound the latest failure: the failing test always uses the row's
+ latest runs, so a past ``end_date`` does not mean "failing as of then".
+
+ One query, whatever the number of rows. The failing test and the range run
+ in SQL first, so the streak lookups, which can read a row's whole history,
+ are computed only for rows that are failing.
+ """
+ finished = _finished_runs()
+ rows = rows.annotate(
+ _recent_statuses=ArraySubquery(finished.values("status")[:FAILING_STREAK_RUNS]),
+ _last_failure=Subquery(finished.values("created_at")[:1]),
+ ).filter(_recent_statuses=[_FAILED] * FAILING_STREAK_RUNS)
+ if start_date is not None:
+ rows = rows.filter(_last_failure__gte=start_date)
+ if end_date is not None:
+ rows = rows.filter(_last_failure__lte=end_date)
+
+ # The streak is the ERRORs since the newest finished run that was not one.
+ streak = finished.filter(
+ status=_FAILED,
+ created_at__gt=Coalesce(OuterRef("_streak_break"), Value(_EPOCH)),
+ )
+ annotated = rows.annotate(
+ _last_success=Subquery(
+ finished.filter(status=_SUCCEEDED).values("created_at")[:1]
+ ),
+ _streak_break=Subquery(finished.exclude(status=_FAILED).values("created_at")[:1]),
+ ).annotate(
+ _failing_since=Subquery(streak.order_by("created_at").values("created_at")[:1]),
+ _failures_in_a_row=Coalesce(
+ Subquery(
+ streak.order_by()
+ .values("pipeline_id")
+ .annotate(n=Count("id"))
+ .values("n")[:1]
+ ),
+ 0,
+ ),
+ )
+
+ streaks = [
+ FailingStreak(
+ row=row,
+ failures_in_a_row=row._failures_in_a_row,
+ failing_since=row._failing_since,
+ last_failure=row._last_failure,
+ last_success=row._last_success,
+ )
+ for row in annotated
+ ]
+ streaks.sort(key=lambda s: (s.last_failure, str(s.row.pk)), reverse=True)
+ return streaks