Skip to content

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

[FEAT] Dashboard metrics system (#1724)

Athul03aa50072a7f
diff --git a/backend/backend/settings/base.py b/backend/backend/settings/base.py
index 28f9a1c6e..97e5be789 100644
--- a/backend/backend/settings/base.py
+++ b/backend/backend/settings/base.py
@@ -130,6 +130,7 @@ API_DEPLOYMENT_RATE_LIMIT_LOCK_BLOCKING_TIMEOUT = int(
os.environ.get("API_DEPLOYMENT_RATE_LIMIT_LOCK_BLOCKING_TIMEOUT", 5)
)
+
DB_NAME = os.environ.get("DB_NAME", "unstract_db")
DB_USER = os.environ.get("DB_USER", "unstract_dev")
DB_HOST = os.environ.get("DB_HOST", "backend-db-1")
@@ -342,6 +343,7 @@ SHARED_APPS = (
"prompt_studio.prompt_studio_index_manager_v2",
"tags",
"configuration",
+ "dashboard_metrics",
)
TENANT_APPS = []
@@ -607,6 +609,23 @@ SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SCOPE = [
]
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_AUTH_EXTRA_ARGUMENTS: dict[str, str] = {}
+# Dashboard Metrics Cache TTLs (in seconds)
+DASHBOARD_CACHE_TTL_CURRENT_BUCKET = int(
+ os.environ.get("DASHBOARD_CACHE_TTL_CURRENT_BUCKET", 60)
+)
+DASHBOARD_CACHE_TTL_HISTORICAL = int(
+ os.environ.get("DASHBOARD_CACHE_TTL_HISTORICAL", 28800)
+)
+DASHBOARD_CACHE_TTL_OVERVIEW = int(os.environ.get("DASHBOARD_CACHE_TTL_OVERVIEW", 300))
+DASHBOARD_CACHE_TTL_SUMMARY = int(os.environ.get("DASHBOARD_CACHE_TTL_SUMMARY", 900))
+DASHBOARD_CACHE_TTL_SERIES = int(os.environ.get("DASHBOARD_CACHE_TTL_SERIES", 1800))
+DASHBOARD_CACHE_TTL_WORKFLOW_USAGE = int(
+ os.environ.get("DASHBOARD_CACHE_TTL_WORKFLOW_USAGE", 3600)
+)
+DASHBOARD_BUCKET_CACHE_ENABLED = (
+ os.environ.get("DASHBOARD_BUCKET_CACHE_ENABLED", "true").lower() == "true"
+)
+
# Always keep this line at the bottom of the file.
if missing_settings:
ERROR_MESSAGE = "Below required settings are missing.\n" + ",\n".join(
diff --git a/backend/backend/urls_v2.py b/backend/backend/urls_v2.py
index 988183abf..05df8c58e 100644
--- a/backend/backend/urls_v2.py
+++ b/backend/backend/urls_v2.py
@@ -63,4 +63,5 @@ urlpatterns = [
path("tags/", include("tags.urls")),
path("execution/", include("workflow_manager.execution.urls")),
path("execution/", include("workflow_manager.file_execution.urls")),
+ path("metrics/", include("dashboard_metrics.urls")),
]
diff --git a/backend/dashboard_metrics/README.md b/backend/dashboard_metrics/README.md
new file mode 100644
index 000000000..5e16b398a
--- /dev/null
+++ b/backend/dashboard_metrics/README.md
@@ -0,0 +1,827 @@
+# Dashboard Metrics Module
+
+This module provides a metrics dashboard for monitoring document processing, API usage, and LLM costs. It aggregates data from various source tables into pre-computed hourly, daily, and monthly tables for fast querying.
+
+---
+
+## Quick Reference (TL;DR)
+
+### What It Does
+- Tracks **12 metrics**: documents processed, pages processed, LLM calls, challenges, summarization calls, API requests, ETL executions, LLM costs, prompt executions, failed pages, HITL reviews, and HITL completions
+- Aggregates data from 4 source tables into 3 pre-computed tables (hourly/daily/monthly)
+- Provides REST API endpoints with Redis caching for fast dashboard rendering
+
+### Data Flow
+```
+Source Tables (usage_v2, page_usage, workflow_execution, workflow_file_execution)
+ ↓ [Celery task every 15 min]
+Aggregated Tables (EventMetricsHourly → Daily → Monthly)
+ ↓
+API Endpoints (/overview/, /summary/, /series/)
+ ↓ [Redis cache]
+Frontend Dashboard (MetricsSummary, MetricsChart, MetricsTable)
+```
+
+### Key Files
+| File | Purpose |
+|------|---------|
+| `services.py` | Queries source tables (9 methods, one per metric) |
+| `tasks.py` | Celery tasks for aggregation and cleanup |
+| `views.py` | REST API endpoints |
+| `cache.py` | Redis caching layer (bucket-based MGET) |
+| `models.py` | Aggregated tables (Hourly/Daily/Monthly) |
+
+### Quick Commands
+```bash
+# Backfill historical data (run first!)
+python manage.py backfill_metrics --days=30
+
+# Start metrics worker
+celery -A backend worker -Q dashboard_metric_events -l info
+
+# Start scheduler (for periodic aggregation)
+celery -A backend beat -l info
+```
+
+### Celery Tasks & Schedule
+| Task | Schedule | What It Does |
+|------|----------|--------------|
+| `aggregate_from_sources` | Every 15 min | Aggregates source → hourly/daily/monthly |
+| `cleanup_hourly_data` | Daily 2 AM | Deletes hourly data > 30 days |
+| `cleanup_daily_data` | Weekly Sun 3 AM | Deletes daily data > 365 days |
+
+### API Endpoints
+| Endpoint | Source | Use Case |
+|----------|--------|----------|
+| `/overview/` | Hourly table | Dashboard home (last 7 days) |
+| `/summary/` | Auto-selected | Detailed stats with date range |
+| `/series/` | Auto-selected | Time series charts |
+| `/live-summary/` | Source tables | Real-time (no aggregation delay) |
+
+### Caching TTLs
+- **Current hour**: 30 seconds (data still changing)
+- **Historical**: 8 hours (stable data)
+- **Overview API**: 5 minutes
+- **Summary/Series API**: 15-30 minutes
+
+---
+
+## Table of Contents
+
+- [Architecture Overview](#architecture-overview)
+- [Metrics Definitions](#metrics-definitions)
+- [Source Tables](#source-tables)
+- [Aggregated Tables](#aggregated-tables)
+- [Celery Tasks](#celery-tasks)
+- [API Endpoints](#api-endpoints)
+- [Caching Strategy](#caching-strategy)
+- [Frontend Components](#frontend-components)
+- [Setup & Configuration](#setup--configuration)
+- [Management Commands](#management-commands)
+
+---
+
+## Architecture Overview
+
+```
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ SOURCE TABLES │
+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
+│ │ usage_v2 │ │ page_usage │ │ workflow_ │ │ workflow_ │ │
+│ │ │ │ │ │ execution │ │ file_exec │ │
+│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
+└─────────┼─────────────────┼─────────────────┼─────────────────┼────────────┘
+ │ │ │ │
+ └─────────────────┴────────┬────────┴─────────────────┘
+ │
+ ┌────────────────▼────────────────┐
+ │ MetricsQueryService │
+ │ (services.py) │
+ │ │
+ │ Queries source tables and │
+ │ aggregates by time period │
+ └────────────────┬────────────────┘
+ │
+ ┌──────────────────────────┼──────────────────────────┐
+ │ │ │
+ ▼ ▼ ▼
+┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
+│ EventMetrics │ │ EventMetrics │ │ EventMetrics │
+│ Hourly │ │ Daily │ │ Monthly │
+│ │ │ │ │ │
+│ • 24h query │ │ • 7 day query │ │ • 2 month query │
+│ • 30 day retain │ │ • 365 day retain│ │ • No cleanup │
+└────────┬────────┘ └────────┬────────┘ └────────┬────────┘
+ │ │ │
+ └────────────────────────┼────────────────────────┘
+ │
+ ┌─────────────▼─────────────┐
+ │ API Endpoints │
+ │ (views.py) │
+ │ │
+ │ /overview/ │
+ │ /summary/ │
+ │ /series/ │
+ │ /live-summary/ │
+ │ /live-series/ │
+ └─────────────┬─────────────┘
+ │
+ ┌─────────────▼─────────────┐
+ │ Redis Cache (Bucket) │
+ │ │
+ │ Per-hour bucket caching │
+ │ MGET for batch retrieval │
+ └─────────────┬─────────────┘
+ │
+ ┌─────────────▼─────────────┐
+ │ Frontend Dashboard │
+ │ │
+ │ MetricsSummary │
+ │ MetricsChart │
+ │ MetricsBreakdown │
+ │ MetricsTable │
+ └───────────────────────────┘
+```
+
+### Why Pre-Aggregated Tables Are Safe
+
+The dashboard reads from **pre-aggregated tables** (`event_metrics_hourly`, `event_metrics_daily`, `event_metrics_monthly`) rather than querying source tables directly. This design is intentionally safe for both reads and writes:
+
+**Write Safety:**
+- Aggregation tables are **write-isolated** — only the Celery aggregation task (`aggregate_from_sources`) and the `backfill_metrics` management command write to them. No user-facing request path writes to these tables.
+- Writes use `update_or_create` with a unique constraint on `(organization, timestamp, metric_name, project, tag)`, making upserts idempotent. Running the aggregation task twice for the same period simply overwrites with the same values.
+- Aggregation tasks use `_base_manager` to bypass Django's `DefaultOrganizationManagerMixin`, which relies on `UserContext` (unavailable in Celery). This is safe because the task already scopes all queries by `organization_id`.
+
+**Read Safety:**
+- Dashboard API endpoints read **only** from pre-aggregated tables, never from source tables (except `/live-summary/` and `/live-series/` which are for real-time fallback).
+- B-tree indexes on `(organization, metric_name, timestamp/date/month)` ensure efficient lookups. Even with millions of rows, queries are index-only scans.
+- No expensive joins — each aggregated row is self-contained with `metric_name`, `metric_value`, and `metric_count`.
+
+**No Impact on Source Tables:**
+- The aggregation task only runs `SELECT` queries against source tables (`usage_v2`, `page_usage`, `workflow_execution`, `workflow_file_execution`). It never modifies them.
+- Source table performance is unaffected by the dashboard feature. If the aggregation task is slow or fails, source tables continue working normally.
+
+**Failure Resilience:**
+- If the aggregation task fails, the dashboard shows stale data (up to 15 minutes old) rather than crashing.
+- Celery tasks have `max_retries=3` with exponential backoff.
+- Cleanup tasks (hourly: 30-day retention, daily: 365-day retention) prevent unbounded table growth.
+
+---
+
+## Metrics Definitions
+
+### All 12 Metrics
+
+| Metric Name | Type | Description | Unit |
+|-------------|------|-------------|------|
+| `documents_processed` | Counter | Number of documents successfully processed | count |
+| `pages_processed` | Histogram | Total pages extracted from documents | count |
+| `llm_calls` | Counter | Number of LLM API calls made | count |
+| `challenges` | Counter | LLM calls for challenge/verification | count |
+| `summarization_calls` | Counter | LLM calls for summarization | count |
+| `deployed_api_requests` | Counter | Requests to deployed API endpoints | count |
+| `etl_pipeline_executions` | Counter | ETL pipeline workflow executions | count |
+| `llm_usage` | Histogram | LLM usage cost | USD ($) |
+| `prompt_executions` | Counter | Total workflow/prompt executions | count |
+| `failed_pages` | Histogram | Pages that failed during processing | count |
+| `hitl_reviews` | Counter | HITL (Human-in-the-Loop) reviews initiated | count |
+| `hitl_completions` | Counter | HITL reviews completed | count |
+
+### Metric Types: Counter vs Histogram
+
+The `metric_type` field distinguishes how metrics are aggregated:
+
+| Type | Aggregation | Use Case | Example |
+|------|-------------|----------|---------|
+| **Counter** | `COUNT(id)` | Counting discrete events | "How many LLM calls happened?" |
+| **Histogram** | `SUM(value)` | Summing continuous values | "How many pages were processed?" |
+
+**Counter Metrics** (9 metrics):
+- `documents_processed`, `llm_calls`, `challenges`, `summarization_calls`
+- `deployed_api_requests`, `etl_pipeline_executions`, `prompt_executions`
+- `hitl_reviews`, `hitl_completions`
+
+**Histogram Metrics** (3 metrics):
+- `pages_processed` - Sums `pages_processed` field from PageUsage
+- `llm_usage` - Sums `cost_in_dollars` field from Usage
+- `failed_pages` - Sums failed pages from PageUsage
+
+The `metric_count` field tracks how many source records were aggregated, useful for calculating averages (`total_value / metric_count`).
+
+### Cost Calculation (`llm_usage` metric)
+
+The `cost_in_dollars` value in the Usage table is calculated by the **platform-service** when recording LLM usage:
+
+```
+cost = (input_cost_per_token × input_tokens) + (output_cost_per_token × output_tokens)
+```
+
+**Pricing Source**: LiteLLM's model pricing database
+- URL: `https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json`
+- Cached locally with configurable TTL (default: 7 days)
+- Contains `input_cost_per_token` and `output_cost_per_token` per model/provider
+
+**Calculation Flow** (in `platform-service/helper/cost_calculation.py`):
+1. Lookup model by name + provider in pricing database
+2. Get `input_cost_per_token` and `output_cost_per_token`
+3. Calculate: `cost = (input_cost × prompt_tokens) + (output_cost × completion_tokens)`
+4. Store in `usage_v2.cost_in_dollars` field
+
+**Example**: GPT-4 with 1000 input tokens and 500 output tokens:
+- Input: $0.00003/token × 1000 = $0.03
+- Output: $0.00006/token × 500 = $0.03
+- Total: $0.06
+
+---
+
+## Source Tables
+
+### Metric to Source Table Mapping
+
+| Metric | Source Table | Model | Filter Conditions | Aggregation |
+|--------|-------------|-------|-------------------|-------------|
+| `documents_processed` | `workflow_file_execution` | `WorkflowFileExecution` | `status="COMPLETED"` | `COUNT(id)` |
+| `pages_processed` | `page_usage` | `PageUsage` | None | `SUM(pages_processed)` |
+| `llm_calls` | `usage_v2` | `Usage` | `usage_type="llm"` | `COUNT(id)` |
+| `challenges` | `usage_v2` | `Usage` | `usage_type="llm"`, `llm_usage_reason="challenge"` | `COUNT(id)` |
+| `summarization_calls` | `usage_v2` | `Usage` | `usage_type="llm"`, `llm_usage_reason="summarize"` | `COUNT(id)` |
+| `deployed_api_requests` | `workflow_execution` | `WorkflowExecution` | `pipeline_id IN APIDeployment.ids` | `COUNT(id)` |
+| `etl_pipeline_executions` | `workflow_execution` | `WorkflowExecution` | `pipeline_id IN Pipeline(type=ETL).ids` | `COUNT(id)` |
+| `llm_usage` | `usage_v2` | `Usage` | `usage_type="llm"` | `SUM(cost_in_dollars)` |
+| `prompt_executions` | `workflow_execution` | `WorkflowExecution` | Via `workflow.organization_id` | `COUNT(id)` |
+
+### Source Table Details
+
+#### 1. `usage_v2` (Usage Model)
+- **Location**: `usage_v2/models.py`
+- **Key Fields**:
+ - `organization_id`: UUID - Organization reference
+ - `usage_type`: String - Type of usage ("llm", "embedding", etc.)
+ - `llm_usage_reason`: String - Reason for LLM call ("extraction", "challenge", "summarize")
+ - `cost_in_dollars`: Decimal - Cost of the LLM call
+ - `created_at`: DateTime - Timestamp
+- **Metrics Derived**: `llm_calls`, `challenges`, `summarization_calls`, `llm_usage`
+
+#### 2. `page_usage` (PageUsage Model)
+- **Location**: `account_usage/models.py`
+- **Key Fields**:
+ - `organization_id`: String - Organization ID (note: CharField, not FK)
+ - `pages_processed`: Integer - Number of pages processed
+ - `file_name`: String - Source file name
+ - `created_at`: DateTime - Timestamp
+- **Metrics Derived**: `pages_processed`
+
+#### 3. `workflow_execution` (WorkflowExecution Model)
+- **Location**: `workflow_manager/workflow_v2/models/execution.py`
+- **Key Fields**:
+ - `workflow_id`: FK - Reference to Workflow
+ - `pipeline_id`: FK - Reference to Pipeline/APIDeployment
+ - `status`: String - Execution status
+ - `created_at`: DateTime - Timestamp
+- **Metrics Derived**: `deployed_api_requests`, `etl_pipeline_executions`, `prompt_executions`
+
+#### 4. `workflow_file_execution` (WorkflowFileExecution Model)
+- **Location**: `workflow_manager/file_execution/models.py`
+- **Key Fields**:
+ - `workflow_execution_id`: FK - Reference to WorkflowExecution
+ - `file_name`: String - Processed file name
+ - `status`: String - "COMPLETED", "ERROR", etc.
+ - `created_at`: DateTime - Timestamp
+- **Metrics Derived**: `documents_processed`
+
+---
+
+## Aggregated Tables
+
+### Three-Tier Aggregation
+
+| Table | Model | Time Column | Granularity | Query Window | Retention |
+|-------|-------|-------------|-------------|--------------|-----------|
+| `event_metrics_hourly` | `EventMetricsHourly` | `timestamp` | Hour | Last 24 hours | 30 days |
+| `event_metrics_daily` | `EventMetricsDaily` | `date` | Day | Last 7 days | 365 days |
+| `event_metrics_monthly` | `EventMetricsMonthly` | `month` | Month | Last 2 months | Forever |
+
+### Table Schema
+
+All three tables share a similar schema:
+
+```python
+class EventMetricsHourly(Model):
+ id = UUIDField(primary_key=True)
+ organization = ForeignKey(Organization)
+ timestamp = DateTimeField() # Hour bucket (truncated)
+ metric_name = CharField(max_length=64) # e.g., "documents_processed"
+ metric_type = CharField(choices=["counter", "histogram"])
+ metric_value = FloatField() # Aggregated value
+ metric_count = IntegerField() # Number of events aggregated
+ project = CharField(default="default")
+ tag = CharField(blank=True)
+ created_at = DateTimeField(auto_now_add=True)
+ modified_at = DateTimeField(auto_now=True)
+```
+
+### Unique Constraints
+
+Each table has a unique constraint on:
+```
+(organization, timestamp/date/month, metric_name, project, tag)
+```
+
+This enables upsert operations during aggregation.
+
+---
+
+## Celery Tasks
+
+### Task Configuration
+
+Located in `tasks.py`:
+
+| Task Name | Celery Name | Schedule | Queue | Purpose |
+|-----------|-------------|----------|-------|---------|
+| `aggregate_metrics_from_sources` | `dashboard_metrics.aggregate_from_sources` | Every 15 min | `dashboard_metric_events` | Aggregate from source tables |
+| `cleanup_hourly_metrics` | `dashboard_metrics.cleanup_hourly_data` | Daily 2:00 AM UTC | `dashboard_metric_events` | Delete hourly data >30 days |
+| `cleanup_daily_metrics` | `dashboard_metrics.cleanup_daily_data` | Weekly Sun 3:00 AM UTC | `dashboard_metric_events` | Delete daily data >365 days |
+
+### Queue Configuration
+
+In `backend/celery_config.py`:
+
+```python
+task_queues = [
+ Queue("dashboard_metric_events", routing_key="dashboard_metric_events"),
+ # ... other queues
+]
+
+task_routes = {
+ "dashboard_metrics.aggregate_from_sources": {"queue": "dashboard_metric_events"},
+ "dashboard_metrics.cleanup_hourly_data": {"queue": "dashboard_metric_events"},
+ "dashboard_metrics.cleanup_daily_data": {"queue": "dashboard_metric_events"},
+}
+```
+
+### Running the Worker
+
+```bash
+# Start the dashboard metrics worker
+celery -A backend worker --loglevel=info -Q dashboard_metric_events
+
+# Start Celery Beat for periodic tasks
+celery -A backend beat --loglevel=info
+```
+
+### Aggregation Task Details
+
+The `aggregate_metrics_from_sources` task:
+
+1. **Iterates over all organizations**
+2. **For each metric**:
+ - Queries source table with `MetricsQueryService`
+ - Groups by time period (hour/day/month)
+3. **Upserts results** into aggregated tables using `update_or_create`
+4. **Uses `_base_manager`** to bypass Django's organization filter in Celery context
+
+```python
+# Query windows
+hourly_start = end_date - timedelta(hours=24) # Last 24 hours
+daily_start = end_date - timedelta(days=7) # Last 7 days
+monthly_start = first_of_previous_month # Last 2 months
+```
+
+---
+
+## API Endpoints
+
+### Endpoint Overview
+
+Base URL: `/api/v1/unstract/<org_id>/metrics/`
+
+| Endpoint | Method | Description | Data Source |
+|----------|--------|-------------|-------------|
+| `/overview/` | GET | Last 7 days summary + daily trend | `EventMetricsHourly` |
+| `/summary/` | GET | Summary stats for date range | Auto-selected table |
+| `/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 |
+| `/health/` | GET | Health check | DB + Cache |
+
+### Auto Source Selection
+
+The `/summary/` and `/series/` endpoints automatically select the data source:
+
+| Date Range | Source Table |
+|------------|--------------|
+| ≤ 7 days | `event_metrics_hourly` |
+| ≤ 90 days | `event_metrics_daily` |
+| > 90 days | `event_metrics_monthly` |
+
+Override with `?source=hourly|daily|monthly`
+
+### Query Parameters
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `start_date` | ISO 8601 | 30 days ago | Start of date range |
+| `end_date` | ISO 8601 | Now | End of date range |
+| `granularity` | String | `day` | Time grouping: `hour`, `day`, `week` |
+| `metric_name` | String | None | Filter by specific metric |
+| `project` | String | None | Filter by project |
+| `source` | String | `auto` | Data source: `auto`, `hourly`, `daily`, `monthly` |
+
+### Response Format
+
+#### `/overview/` Response
+```json
+{
+ "period": {
+ "start_date": "2024-01-01T00:00:00Z",
+ "end_date": "2024-01-07T23:59:59Z",
+ "days": 7
+ },
+ "totals": [
+ {"metric_name": "documents_processed", "total_value": 1500, "total_count": 150},
+ {"metric_name": "pages_processed", "total_value": 45000, "total_count": 150}
+ ],
+ "daily_trend": [
+ {
+ "date": "2024-01-01T00:00:00Z",
+ "metrics": {
+ "documents_processed": 200,
+ "pages_processed": 6000
+ }
+ }
+ ]
+}
+```
+
+#### `/summary/` Response
+```json
+{
+ "start_date": "2024-01-01T00:00:00Z",
+ "end_date": "2024-01-31T23:59:59Z",
+ "source": "daily",
+ "summary": [
+ {
+ "metric_name": "documents_processed",
+ "metric_type": "counter",
+ "total_value": 5000,
+ "total_count": 500,
+ "average_value": 10,
+ "min_value": 1,
+ "max_value": 50
+ }
+ ]
+}
+```
+
+---
+
+## Caching Strategy
+
+### Two-Layer Caching
+
+#### 1. Whole-Response Caching (Simple)
+Used for `/overview/`, `/live-summary/`, `/live-series/`
+
+```python
+@cache_metrics_response(endpoint="overview")
+def overview(self, request):
+ ...
+```
+
+TTLs:
+- Overview: 5 minutes
+- Summary: 15 minutes
+- Series: 30 minutes
+
+#### 2. Bucket-Based Caching (Advanced)
+Used for `/summary/` and `/series/` with hourly source
+
+**How it works:**
+1. Split time range into hourly buckets
+2. Use Redis MGET to fetch all buckets in one round-trip
+3. Query DB only for missing buckets
+4. Save new buckets with appropriate TTL
+
+**Cache Key Format:**
+```
+metrics:bucket:hourly:<org_id>:<timestamp>[:metric_name]
+```
+
+**TTL Strategy:**
+- Current hour: 30 seconds (data still changing)
+- Historical hours: 8 hours (data stable)
+
+**Benefits:**
+- Overlapping queries reuse cached buckets
+- Query for Jan 1-7 caches 168 hourly buckets
+- Query for Jan 5-10 reuses 72 cached buckets, only queries 72 new
+
+### Cache Configuration
+
+In `settings.py`:
+```python
+DASHBOARD_CACHE_TTL_CURRENT_HOUR = 30 # 30 seconds
+DASHBOARD_CACHE_TTL_HISTORICAL = 28800 # 8 hours
+DASHBOARD_CACHE_TTL_OVERVIEW = 300 # 5 minutes
+DASHBOARD_CACHE_TTL_SUMMARY = 900 # 15 minutes
+DASHBOARD_CACHE_TTL_SERIES = 1800 # 30 minutes
+```
+
+---
+
+## UI Data Flow — What Shows Where
+
+### Overview Tab
+
+#### Summary Cards (top row)
+
+- **Component**: `MetricsSummary` → `frontend/src/components/metrics-dashboard/MetricsSummary.jsx`
+- **Hook**: `useMetricsOverview(startDate, endDate)`
+- **API**: `GET /metrics/overview/?start_date=...&end_date=...`
+- **DB**: `event_metrics_daily` (8-90d range) or `event_metrics_hourly` (≤7d) or `event_metrics_monthly` (>90d)
+- **Response field**: `totals[]` — one entry per metric, `SUM(metric_value)` over the date range
+
+| Card | `metric_name` in DB | Display |
+|---|---|---|
+| Total Pages Processed | `pages_processed` | Sum of `metric_value` |
+| Documents Processed | `documents_processed` | Sum of `metric_value` |
+| LLM Calls | `llm_calls` | Sum of `metric_value` |
+| Prompt Executions | `prompt_executions` | Sum of `metric_value` |
+| LLM Usage Cost | `llm_usage` | Sum of `metric_value` ($ prefix) |
+
+Cards appear in priority order. Only metrics with data show up.
+
+#### Pages Processed Chart (left, below cards)
+
+- **Component**: `PagesChart` → `frontend/src/components/metrics-dashboard/MetricsChart.jsx`
+- **Hook**: `useMetricsOverview(chartStart, chartEnd)` (fixed 30-day range)
+- **API**: Same `/metrics/overview/`
+- **Response field**: `daily_trend[]`
+
+| Line | Color | Source |
+|---|---|---|
+| Pages Processed | Blue `#1890ff` | `daily_trend[].metrics.pages_processed` |
+| Failed Pages | Red `#ff4d4f` | `daily_trend[].metrics.failed_pages` |
+
+#### Trend Analysis Chart (bottom left)
+
+- **Component**: `TrendAnalysisChart` → `frontend/src/components/metrics-dashboard/MetricsChart.jsx`
+- **Hook**: Same `useMetricsOverview` as Pages chart (fixed 30-day range)
+- **Response field**: `daily_trend[]` (excludes `pages_processed` and `failed_pages`)
+
+Default lines: `documents_processed` (yellow), `llm_calls` (purple).
+Users toggle metrics via Filter dropdown.
+
+#### Recent Activity (right sidebar)
+
+- **Component**: `RecentActivity` → `frontend/src/components/metrics-dashboard/RecentActivity.jsx`
+- **Hook**: `useRecentActivity(5)`
+- **API**: `GET /metrics/recent-activity/?limit=5`
+- **DB**: `workflow_execution` + `workflow_file_execution` + `usage` (live queries, no pre-aggregation)
+
+| Field | Source |
+|---|---|
+| Type (ETL / API / Workflow) | Determined by pipeline/api_deployment FK presence |
+| Status tag | `workflow_execution.status` |
+| File name | `workflow_file_execution.file_name` |
+| Token count | `SUM(usage.total_tokens)` per execution |
+| Time ago | Relative time from `workflow_file_execution.created_at` |
+
+### LLM Usage Tab
+
+#### LLM Usage by Workflow (table)
+
+- **Component**: `LLMUsageTable` → `frontend/src/components/metrics-dashboard/LLMUsageTable.jsx`
+- **Hook**: `useWorkflowTokenUsage(startDate, endDate)`
+- **API**: `GET /metrics/workflow-token-usage/?start_date=...&end_date=...`
+- **DB**: `usage` table (live query, `usage_type='llm'`, grouped by `workflow_id`)
+
+| Column | Source |
+|---|---|
+| Workflow | `workflow.workflow_name` (resolved via `usage.workflow_id` FK) |
+| Tokens | `SUM(usage.total_tokens)` |
+| LLM Calls | `COUNT(usage.id)` |
+| Cost | `SUM(usage.cost_in_dollars)` |
+
+Sorted by tokens descending. Only rows with non-empty `workflow_id` appear.
+
+### Data Hooks
+
+Located in `frontend/src/hooks/useMetricsData.js`:
+
+| Hook | Endpoint | Purpose |
+|------|----------|---------|
+| `useMetricsOverview` | `/overview/` | Summary cards + chart data |
+| `useRecentActivity` | `/recent-activity/` | Live recent processing events |
+| `useWorkflowTokenUsage` | `/workflow-token-usage/` | Per-workflow LLM token breakdown |
+
+### Frontend Caching
+
+Uses localStorage with TTL matching backend (`frontend/src/helpers/metricsCache.js`):
+```javascript
+const CACHE_TTL = {
+ overview: 5 * 60 * 1000, // 5 minutes
+ summary: 15 * 60 * 1000, // 15 minutes
+ series: 30 * 60 * 1000, // 30 minutes
+};
+```
+
+---
+
+## Setup & Configuration
+
+### 1. Install Dependencies
+
+```bash
+cd backend/
+uv sync
+```
+
+Required packages in `pyproject.toml`:
+- `django-celery-beat` - For periodic task scheduling
+- `django-redis` - For MGET/pipeline operations
+
+### 2. Run Migrations
+
+```bash
+python manage.py migrate dashboard_metrics
+```
+
+This creates:
+- Three aggregated tables
+- Periodic task schedules in `django_celery_beat`
+
+### 3. Backfill Historical Data
+
+```bash
+# Backfill last 30 days for all organizations
+python manage.py backfill_metrics --days=30
+
+# Backfill for specific org
+python manage.py backfill_metrics --days=90 --org-id=<uuid>
+
+# Dry run to see what would be done
+python manage.py backfill_metrics --days=7 --dry-run
+```
+
+### 4. Start Workers
+
+```bash
+# Terminal 1: Dashboard metrics worker
+celery -A backend worker --loglevel=info -Q dashboard_metric_events
+
+# Terminal 2: Celery Beat scheduler
+celery -A backend beat --loglevel=info
+```
+
+### 5. Verify Setup
+
+```bash
+# Check periodic tasks are registered
+python manage.py shell -c "
+from django_celery_beat.models import PeriodicTask
+for t in PeriodicTask.objects.filter(name__startswith='dashboard'):
+ print(f'{t.name}: enabled={t.enabled}')
+"
+
+# Check aggregated data exists
+python manage.py shell -c "
+from dashboard_metrics.models import EventMetricsHourly
+print(f'Hourly records: {EventMetricsHourly._base_manager.count()}')
+"
+```
+
+---
+
+## Management Commands
+
+### `backfill_metrics`
+
+Populates aggregated tables from historical source data.
+
+```bash
+python manage.py backfill_metrics [options]
+
+Options:
+ --days=N Number of days to backfill (default: 30)
+ --org-id=UUID Specific organization (default: all)
+ --dry-run Show what would be done
+ --skip-hourly Skip hourly aggregation
+ --skip-daily Skip daily aggregation
+ --skip-monthly Skip monthly aggregation
+```
+
+---
+
+## Troubleshooting
+
+### Common Issues
+
+#### 1. Chart shows only one metric
+**Cause**: Only one metric has data in `EventMetricsHourly`
+**Fix**: Run `python manage.py backfill_metrics --days=30`
+
+#### 2. Empty dashboard
+**Cause**: Aggregated tables are empty
+**Fix**:
+1. Check source tables have data
+2. Run backfill command
+3. Verify Celery worker is running
+
+#### 3. Celery task not running
+**Cause**: Task not routed to correct queue
+**Fix**: Ensure `celery_config.py` has the task route:
+```python
+"dashboard_metrics.aggregate_from_sources": {"queue": "dashboard_metric_events"},
+```
+
+#### 4. Slow queries
+**Cause**: Large date range hitting hourly table
+**Fix**: Use `?source=daily` or `?source=monthly` for large ranges
+
+### Debugging Commands
+
+```bash
+# Check what's in aggregated tables
+python manage.py shell -c "
+from dashboard_metrics.models import *
+from django.db.models import Count
+
+print('=== Hourly ===')
+for m in EventMetricsHourly._base_manager.values('metric_name').annotate(c=Count('id')):
+ print(f\" {m['metric_name']}: {m['c']}\")
+
+print('=== Daily ===')
+for m in EventMetricsDaily._base_manager.values('metric_name').annotate(c=Count('id')):
+ print(f\" {m['metric_name']}: {m['c']}\")
+"
+
+# Manually trigger aggregation
+python manage.py shell -c "
+from dashboard_metrics.tasks import aggregate_metrics_from_sources
+result = aggregate_metrics_from_sources()
+print(result)
+"
+
+# Check Redis cache keys
+python manage.py shell -c "
+from django.core.cache import cache
+keys = cache.keys('metrics:*')
+print(f'Cached metric keys: {len(keys)}')
+"
+```
+
+---
+
+## File Structure
+
+```
+backend/dashboard_metrics/
+├── __init__.py
+├── admin.py # Django admin registration
+├── apps.py # App configuration
+├── cache.py # Caching layer (bucket-based + decorators)
+├── models.py # EventMetricsHourly/Daily/Monthly models
+├── serializers.py # DRF serializers
+├── services.py # MetricsQueryService (source table queries)
+├── tasks.py # Celery tasks (aggregation, cleanup)
+├── urls.py # URL routing
+├── views.py # API ViewSet
+├── README.md # This file
+├── management/
+│ └── commands/
+│ └── backfill_metrics.py # Backfill historical data
+├── migrations/
+│ ├── 0001_initial.py # Create 3 aggregation tables
+│ └── 0002_setup_periodic_tasks.py # Register Celery Beat schedules
+└── tests/
+ └── test_tasks.py
+```
+
+---
+
+## Contributing
+
+When adding new metrics:
+
+1. **Add query method** in `services.py`:
+ ```python
+ @staticmethod
+ def get_new_metric(org_id, start, end, granularity):
+ ...
+ ```
+
+2. **Add to metric configs** in `tasks.py`:
+ ```python
+ metric_configs = [
+ ...
+ ("new_metric", MetricsQueryService.get_new_metric, False),
+ ]
+ ```
+
+3. **Add to backfill command** in `management/commands/backfill_metrics.py`
+
+4. **Update frontend** default selected metrics if needed
+
+5. **Run backfill** to populate historical data
diff --git a/backend/dashboard_metrics/__init__.py b/backend/dashboard_metrics/__init__.py
new file mode 100644
index 000000000..a06a663ce
--- /dev/null
+++ b/backend/dashboard_metrics/__init__.py
@@ -0,0 +1,4 @@
+"""Dashboard Metrics app for Unstract.
+
+Provides storage and API for customer-facing metrics dashboards.
+"""
diff --git a/backend/dashboard_metrics/apps.py b/backend/dashboard_metrics/apps.py
new file mode 100644
index 000000000..00c41bd55
--- /dev/null
+++ b/backend/dashboard_metrics/apps.py
@@ -0,0 +1,11 @@
+"""Django app configuration for dashboard_metrics."""
+
+from django.apps import AppConfig
+
+
+class DashboardMetricsConfig(AppConfig):
+ """Configuration for the Dashboard Metrics app."""
+
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "dashboard_metrics"
+ verbose_name = "Dashboard Metrics"
diff --git a/backend/dashboard_metrics/cache.py b/backend/dashboard_metrics/cache.py
new file mode 100644
index 000000000..881594848
--- /dev/null
+++ b/backend/dashboard_metrics/cache.py
@@ -0,0 +1,405 @@
+"""Cache layer for Dashboard Metrics.
+
+Provides caching for computed metric aggregations to reduce database load.
+Uses Redis through Django's cache framework.
+
+Cache TTL Strategy:
+- Current hour/day/month data: Configurable via DASHBOARD_CACHE_TTL_CURRENT_BUCKET (default 60s)
+- Historical data: Configurable via DASHBOARD_CACHE_TTL_HISTORICAL (default 8 hours)
+
+Bucket-based Caching:
+- Time ranges are split into buckets (hourly/daily/monthly)
+- Each bucket is cached independently with appropriate TTL
+- MGET used to fetch multiple buckets in single Redis round-trip
+- Partial cache hits allow reuse across overlapping queries
+"""
+
+import hashlib
+import json
+import logging
+from collections.abc import Callable
+from datetime import datetime, timedelta
+from functools import wraps
+from typing import Any
+
+from django.conf import settings
+from django.core.cache import cache
+from django.utils import timezone
+from rest_framework.response import Response
+from utils.user_context import UserContext
+
+logger = logging.getLogger(__name__)
+
+# Try to get raw Redis client for MGET/pipeline operations
+try:
+ from django_redis import get_redis_connection
+
+ REDIS_AVAILABLE = True
+except ImportError:
+ REDIS_AVAILABLE = False
+ logger.warning("django_redis not available, bucket caching will use fallback")
+
+# Cache TTL values from Django settings (configured in settings/base.py)
+CACHE_TTL_CURRENT_BUCKET = settings.DASHBOARD_CACHE_TTL_CURRENT_BUCKET
+CACHE_TTL_HISTORICAL = settings.DASHBOARD_CACHE_TTL_HISTORICAL
+CACHE_TTL_OVERVIEW = settings.DASHBOARD_CACHE_TTL_OVERVIEW
+CACHE_TTL_SUMMARY = settings.DASHBOARD_CACHE_TTL_SUMMARY
+CACHE_TTL_SERIES = settings.DASHBOARD_CACHE_TTL_SERIES
+CACHE_TTL_WORKFLOW_USAGE = settings.DASHBOARD_CACHE_TTL_WORKFLOW_USAGE
+
+# Cache key prefix
+CACHE_PREFIX = "dashboard_metrics"
+
+
+def _build_cache_key(org_id: str, endpoint: str, params: dict[str, Any]) -> str:
+ """Build a unique cache key from organization, endpoint, and parameters.
+
+ Args:
+ org_id: Organization identifier
+ endpoint: API endpoint name (e.g., 'summary', 'series')
+ params: Query parameters
+
+ Returns:
+ Unique cache key string
+ """
+ # Sort params for consistent hashing
+ sorted_params = json.dumps(params, sort_keys=True, default=str)
+ params_hash = hashlib.sha256(sorted_params.encode()).hexdigest()[:12]
+ return f"{CACHE_PREFIX}:{org_id}:{endpoint}:{params_hash}"
+
+
+def cache_metrics_response(
+ endpoint: str,
+ ttl: int | None = None,
+) -> Callable:
+ """Decorator to cache metrics API responses.
+
+ Args:
+ endpoint: Endpoint name for cache key
+ ttl: Cache TTL in seconds (defaults based on endpoint)
+
+ Returns:
+ Decorated function with caching
+ """
+ # Default TTLs per endpoint
+ default_ttls = {
+ "overview": CACHE_TTL_OVERVIEW,
+ "summary": CACHE_TTL_SUMMARY,
+ "series": CACHE_TTL_SERIES,
+ "workflow_token_usage": CACHE_TTL_WORKFLOW_USAGE,
+ "recent_activity": CACHE_TTL_OVERVIEW,
+ }
+
+ def decorator(func: Callable) -> Callable:
+ @wraps(func)
+ def wrapper(self, request, *args, **kwargs):
+ # Get organization from context
+ org = UserContext.get_organization()
+ if not org:
+ # No caching without organization context
+ return func(self, request, *args, **kwargs)
+
+ org_id = str(org.id)
+
+ # Build cache key from query params (exclude refresh param)
+ params = {k: v for k, v in request.query_params.items() if k != "refresh"}
+ cache_key = _build_cache_key(org_id, endpoint, params)
+
+ # Skip cache if refresh=true requested
+ force_refresh = request.query_params.get("refresh", "").lower() == "true"
+
+ # Check cache (unless force refresh)
+ if not force_refresh:
+ cached = cache.get(cache_key)
+ if cached is not None:
+ logger.debug(f"Cache hit for {endpoint}: {cache_key}")
+ return Response(cached)
+
+ # Execute function and cache result
+ response = func(self, request, *args, **kwargs)
+
+ if response.status_code == 200:
+ cache_ttl = ttl or default_ttls.get(endpoint, CACHE_TTL_SUMMARY)
+ cache.set(cache_key, response.data, cache_ttl)
+ logger.debug(f"Cached {endpoint} for {cache_ttl}s: {cache_key}")
+
+ return response
+
+ return wrapper
+
+ return decorator
+
+
+# =============================================================================
+# Bucket-based Caching for Time-Range Queries
+# =============================================================================
+
+
+def _get_redis_client():
+ """Get raw Redis client for MGET/pipeline operations.
+
+ Returns:
+ Redis client or None if not available
+ """
+ if not REDIS_AVAILABLE:
+ return None
+ try:
+ return get_redis_connection("default")
+ except Exception:
+ logger.warning("Failed to get Redis connection")
+ return None
+
+
+def generate_time_buckets(
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = "hourly",
+) -> list[datetime]:
+ """Generate time bucket timestamps for a date range.
+
+ Args:
+ start_date: Start of the range
+ end_date: End of the range
+ granularity: 'hourly', 'daily', or 'monthly'
+
+ Returns:
+ List of bucket start timestamps
+ """
+ buckets = []
+
+ # Ensure timezone awareness
+ if start_date.tzinfo is None:
+ start_date = timezone.make_aware(start_date, timezone.utc)
+ if end_date.tzinfo is None:
+ end_date = timezone.make_aware(end_date, timezone.utc)
+
+ if granularity == "hourly":
+ # Truncate to hour
+ current = start_date.replace(minute=0, second=0, microsecond=0)
+ while current <= end_date:
+ buckets.append(current)
+ current = current + timedelta(hours=1)
+
+ elif granularity == "daily":
+ # Truncate to day
+ current = start_date.replace(hour=0, minute=0, second=0, microsecond=0)
+ while current <= end_date:
+ buckets.append(current)
+ current = current + timedelta(days=1)
+
+ elif granularity == "monthly":
+ # Truncate to first of month
+ current = start_date.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+ while current <= end_date:
+ buckets.append(current)
+ # Move to next month
+ if current.month == 12:
+ current = current.replace(year=current.year + 1, month=1)
+ else:
+ current = current.replace(month=current.month + 1)
+
+ return buckets
+
+
+def _build_bucket_key(
+ org_id: str,
+ granularity: str,
+ bucket_ts: datetime,
+ metric_name: str | None = None,
+) -> str:
+ """Build cache key for a specific time bucket.
+
+ Key format: metrics:bucket:<granularity>:<org_id>:<bucket_iso>[:metric_name]
+
+ Args:
+ org_id: Organization identifier
+ granularity: 'hourly', 'daily', or 'monthly'
+ bucket_ts: Bucket timestamp
+ metric_name: Optional metric name filter
+
+ Returns:
+ Cache key string
+ """
+ bucket_str = (
+ bucket_ts.strftime("%Y-%m-%dT%H:00:00")
+ if granularity == "hourly"
+ else bucket_ts.strftime("%Y-%m-%d")
+ if granularity == "daily"
+ else bucket_ts.strftime("%Y-%m")
+ )
+
+ key = f"{CACHE_PREFIX}:bucket:{granularity}:{org_id}:{bucket_str}"
+ if metric_name:
+ key = f"{key}:{metric_name}"
+ return key
+
+
+def _get_ttl_for_bucket(bucket_ts: datetime, granularity: str = "hourly") -> int:
+ """Get appropriate TTL for a time bucket.
+
+ Current period uses short TTL (30s), historical uses long TTL (8h).
+
+ Args:
+ bucket_ts: Bucket timestamp
+ granularity: 'hourly', 'daily', or 'monthly'
+
+ Returns:
+ TTL in seconds
+ """
+ now = timezone.now()
+
+ if granularity == "hourly":
+ current_bucket = now.replace(minute=0, second=0, microsecond=0)
+ elif granularity == "daily":
+ current_bucket = now.replace(hour=0, minute=0, second=0, microsecond=0)
+ else: # monthly
+ current_bucket = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+
+ # Ensure bucket_ts is timezone aware for comparison
+ if bucket_ts.tzinfo is None:
+ bucket_ts = timezone.make_aware(bucket_ts, timezone.utc)
+
+ # Current bucket gets short TTL, historical gets long TTL
+ if bucket_ts >= current_bucket:
+ return CACHE_TTL_CURRENT_BUCKET
+ return CACHE_TTL_HISTORICAL
+
+
+def mget_metrics_buckets(
+ org_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = "hourly",
+ metric_name: str | None = None,
+) -> tuple[dict[datetime, list[dict]], list[datetime]]:
+ """Batch fetch cached metrics using Redis MGET.
+
+ Args:
+ org_id: Organization identifier
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: 'hourly', 'daily', or 'monthly'
+ metric_name: Optional metric name filter
+
+ Returns:
+ Tuple of (cached_data dict, missing_buckets list)
+ - cached_data: {bucket_timestamp: [records]}
+ - missing_buckets: list of bucket timestamps not in cache
+ """
+ buckets = generate_time_buckets(start_date, end_date, granularity)
+
+ if not buckets:
+ return {}, []
+
+ redis_client = _get_redis_client()
+
+ # Fallback to individual cache.get if Redis MGET not available
+ if not redis_client:
+ cached_data = {}
+ missing_buckets = []
+
+ for bucket_ts in buckets:
+ key = _build_bucket_key(org_id, granularity, bucket_ts, metric_name)
+ data = cache.get(key)
+ if data is not None:
+ cached_data[bucket_ts] = data
+ else:
+ missing_buckets.append(bucket_ts)
+
+ logger.debug(
+ f"Bucket cache (fallback): {len(cached_data)} hits, "
+ f"{len(missing_buckets)} misses for org {org_id}"
+ )
+ return cached_data, missing_buckets
+
+ # Use Redis MGET for batch retrieval
+ keys = [
+ _build_bucket_key(org_id, granularity, bucket_ts, metric_name)
+ for bucket_ts in buckets
+ ]
+
+ try:
+ # MGET returns list of values (or None for missing keys)
+ values = redis_client.mget(keys)
+
+ cached_data = {}
+ missing_buckets = []
+
+ for bucket_ts, value in zip(buckets, values, strict=False):
+ if value is not None:
+ try:
+ cached_data[bucket_ts] = json.loads(value)
+ except (json.JSONDecodeError, TypeError):
+ missing_buckets.append(bucket_ts)
+ else:
+ missing_buckets.append(bucket_ts)
+
+ logger.debug(
+ f"Bucket cache (MGET): {len(cached_data)} hits, "
+ f"{len(missing_buckets)} misses for org {org_id}"
+ )
+ return cached_data, missing_buckets
+
+ except Exception:
+ logger.exception("MGET failed, falling back to no cache")
+ return {}, buckets
+
+
+def mset_metrics_buckets(
+ org_id: str,
+ bucket_data: dict[datetime, list[dict]],
+ granularity: str = "hourly",
+ metric_name: str | None = None,
+) -> int:
+ """Batch save metrics buckets to cache using Redis pipeline.
+
+ Each bucket gets TTL based on whether it's current or historical.
+
+ Args:
+ org_id: Organization identifier
+ bucket_data: Dict of {bucket_timestamp: [records]}
+ granularity: 'hourly', 'daily', or 'monthly'
+ metric_name: Optional metric name filter
+
+ Returns:
+ Number of buckets saved
+ """
+ if not bucket_data:
+ return 0
+
+ redis_client = _get_redis_client()
+
+ # Fallback to individual cache.set if Redis pipeline not available
+ if not redis_client:
+ saved = 0
+ for bucket_ts, data in bucket_data.items():
+ key = _build_bucket_key(org_id, granularity, bucket_ts, metric_name)
+ ttl = _get_ttl_for_bucket(bucket_ts, granularity)
+ try:
+ cache.set(key, data, ttl)
+ saved += 1
+ except Exception:
+ logger.warning(f"Failed to cache bucket {key}")
+ return saved
+
+ # Use Redis pipeline for batch save with different TTLs
+ try:
+ pipe = redis_client.pipeline()
+
+ for bucket_ts, data in bucket_data.items():
+ key = _build_bucket_key(org_id, granularity, bucket_ts, metric_name)
+ ttl = _get_ttl_for_bucket(bucket_ts, granularity)
+ serialized = json.dumps(data, default=str)
+ pipe.setex(key, ttl, serialized)
+
+ pipe.execute()
+
+ logger.debug(
+ f"Cached {len(bucket_data)} buckets for org {org_id} "
+ f"(granularity={granularity})"
+ )
+ return len(bucket_data)
+
+ except Exception:
+ logger.exception("Pipeline MSET failed")
+ return 0
diff --git a/backend/dashboard_metrics/management/__init__.py b/backend/dashboard_metrics/management/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/backend/dashboard_metrics/management/commands/__init__.py b/backend/dashboard_metrics/management/commands/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/backend/dashboard_metrics/management/commands/backfill_metrics.py b/backend/dashboard_metrics/management/commands/backfill_metrics.py
new file mode 100644
index 000000000..2c8287ab6
--- /dev/null
+++ b/backend/dashboard_metrics/management/commands/backfill_metrics.py
@@ -0,0 +1,348 @@
+"""Management command to backfill metrics from source tables.
+
+This command populates EventMetricsHourly, EventMetricsDaily, and EventMetricsMonthly
+tables from historical data in source tables (Usage, PageUsage, WorkflowExecution, etc.)
+
+Usage:
+ python manage.py backfill_metrics --days=30
+ python manage.py backfill_metrics --days=90 --org-id=12
+ python manage.py backfill_metrics --days=7 --dry-run
+"""
+
+import logging
+from datetime import datetime, timedelta
+
+from account_v2.models import Organization
+from django.core.management.base import BaseCommand
+from django.utils import timezone
+
+from dashboard_metrics.models import (
+ EventMetricsDaily,
+ EventMetricsHourly,
+ EventMetricsMonthly,
+ Granularity,
+ MetricType,
+)
+from dashboard_metrics.services import MetricsQueryService
+
+logger = logging.getLogger(__name__)
+
+
+class Command(BaseCommand):
+ help = "Backfill metrics from source tables into aggregated tables"
+
+ # Metric configurations: (name, query_method, is_histogram)
+ METRIC_CONFIGS = [
+ ("documents_processed", MetricsQueryService.get_documents_processed, False),
+ ("pages_processed", MetricsQueryService.get_pages_processed, True),
+ ("llm_calls", MetricsQueryService.get_llm_calls, False),
+ ("challenges", MetricsQueryService.get_challenges, False),
+ ("summarization_calls", MetricsQueryService.get_summarization_calls, False),
+ ("deployed_api_requests", MetricsQueryService.get_deployed_api_requests, False),
+ (
+ "etl_pipeline_executions",
+ MetricsQueryService.get_etl_pipeline_executions,
+ False,
+ ),
+ ("llm_usage", MetricsQueryService.get_llm_usage_cost, True),
+ ("prompt_executions", MetricsQueryService.get_prompt_executions, False),
+ ("failed_pages", MetricsQueryService.get_failed_pages, True),
+ ("hitl_reviews", MetricsQueryService.get_hitl_reviews, False),
+ ("hitl_completions", MetricsQueryService.get_hitl_completions, False),
+ ]
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ "--days",
+ type=int,
+ default=30,
+ help="Number of days to backfill (default: 30)",
+ )
+ parser.add_argument(
+ "--org-id",
+ type=str,
+ default=None,
+ help="Specific organization ID to backfill (default: all orgs)",
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Show what would be done without making changes",
+ )
+ parser.add_argument(
+ "--skip-hourly",
+ action="store_true",
+ help="Skip hourly aggregation (only do daily/monthly)",
+ )
+ parser.add_argument(
+ "--skip-daily",
+ action="store_true",
+ help="Skip daily aggregation",
+ )
+ parser.add_argument(
+ "--skip-monthly",
+ action="store_true",
+ help="Skip monthly aggregation",
+ )
+
+ def handle(self, *args, **options):
+ days = options["days"]
+ org_id = options.get("org_id")
+ dry_run = options["dry_run"]
+ skip_hourly = options["skip_hourly"]
+ skip_daily = options["skip_daily"]
+ skip_monthly = options["skip_monthly"]
+
+ end_date = timezone.now()
+ start_date = end_date - timedelta(days=days)
+
+ self.stdout.write(f"Backfill period: {start_date.date()} to {end_date.date()}")
+ self.stdout.write(f"Days: {days}")
+
+ if dry_run:
+ self.stdout.write(self.style.WARNING("DRY RUN - no changes will be made"))
+
+ # Get organizations to process
+ if org_id:
+ try:
+ orgs = [Organization.objects.get(id=org_id)]
+ self.stdout.write(f"Processing single org: {org_id}")
+ except Organization.DoesNotExist:
+ self.stderr.write(self.style.ERROR(f"Organization {org_id} not found"))
+ return
+ else:
+ orgs = list(Organization.objects.all())
+ self.stdout.write(f"Processing {len(orgs)} organizations")
+
+ total_stats = {
+ "hourly": {"upserted": 0},
+ "daily": {"upserted": 0},
+ "monthly": {"upserted": 0},
+ "errors": 0,
+ }
+
+ for org in orgs:
+ org_id_str = str(org.id)
+ self.stdout.write(f"\nProcessing org: {org.display_name} ({org_id_str})")
+
+ try:
+ # Collect all metric data for this org
+ hourly_data, daily_data, monthly_data = self._collect_metrics(
+ org_id_str, start_date, end_date
+ )
+
+ self.stdout.write(
+ f" Collected: {len(hourly_data)} hourly, "
+ f"{len(daily_data)} daily, {len(monthly_data)} monthly records"
+ )
+
+ if not dry_run:
+ # Write to tables (bulk INSERT...ON CONFLICT)
+ if not skip_hourly:
+ h_count = self._bulk_upsert_hourly(hourly_data)
+ total_stats["hourly"]["upserted"] += h_count
+ self.stdout.write(f" Hourly: {h_count} upserted")
+
+ if not skip_daily:
+ d_count = self._bulk_upsert_daily(daily_data)
+ total_stats["daily"]["upserted"] += d_count
+ self.stdout.write(f" Daily: {d_count} upserted")
+
+ if not skip_monthly:
+ m_count = self._bulk_upsert_monthly(monthly_data)
+ total_stats["monthly"]["upserted"] += m_count
+ self.stdout.write(f" Monthly: {m_count} upserted")
+
+ except Exception as e:
+ self.stderr.write(
+ self.style.ERROR(f" Error processing org {org_id_str}: {e}")
+ )
+ total_stats["errors"] += 1
+ logger.exception(f"Error backfilling org {org_id_str}")
+
+ # Print summary
+ self.stdout.write("\n" + "=" * 50)
+ self.stdout.write(self.style.SUCCESS("BACKFILL COMPLETE"))
+ self.stdout.write(f"Hourly: {total_stats['hourly']['upserted']} upserted")
+ self.stdout.write(f"Daily: {total_stats['daily']['upserted']} upserted")
+ self.stdout.write(f"Monthly: {total_stats['monthly']['upserted']} upserted")
+ self.stdout.write(f"Errors: {total_stats['errors']}")
+
+ def _collect_metrics(
+ self, org_id: str, start_date: datetime, end_date: datetime
+ ) -> tuple[dict, dict, dict]:
+ """Collect metrics from source tables for all granularities."""
+ hourly_agg = {}
+ daily_agg = {}
+ monthly_agg = {}
+
+ for metric_name, query_method, is_histogram in self.METRIC_CONFIGS:
+ metric_type = MetricType.HISTOGRAM if is_histogram else MetricType.COUNTER
+
+ try:
+ # Query hourly data
+ hourly_results = query_method(
+ org_id, start_date, end_date, granularity=Granularity.HOUR
+ )
+ for row in hourly_results:
+ period = row["period"]
+ value = row["value"] or 0
+ hour_ts = self._truncate_to_hour(period)
+ key = (org_id, hour_ts.isoformat(), metric_name, "default", "")
+
+ if key not in hourly_agg:
+ hourly_agg[key] = {
+ "metric_type": metric_type,
+ "value": 0,
+ "count": 0,
+ }
+ hourly_agg[key]["value"] += value
+ hourly_agg[key]["count"] += 1
+
+ # Query daily data
+ daily_results = query_method(
+ org_id, start_date, end_date, granularity=Granularity.DAY
+ )
+ for row in daily_results:
+ period = row["period"]
+ value = row["value"] or 0
+ day_date = period.date() if hasattr(period, "date") else period
+ key = (org_id, day_date.isoformat(), metric_name, "default", "")
+
+ if key not in daily_agg:
+ daily_agg[key] = {
+ "metric_type": metric_type,
+ "value": 0,
+ "count": 0,
+ }
+ daily_agg[key]["value"] += value
+ daily_agg[key]["count"] += 1
+
+ # Query for monthly (aggregate daily results by month)
+ for row in daily_results:
+ period = row["period"]
+ value = row["value"] or 0
+ if hasattr(period, "date"):
+ month_date = period.replace(day=1).date()
+ else:
+ month_date = period.replace(day=1)
+ key = (org_id, month_date.isoformat(), metric_name, "default", "")
+
+ if key not in monthly_agg:
+ monthly_agg[key] = {
+ "metric_type": metric_type,
+ "value": 0,
+ "count": 0,
+ }
+ monthly_agg[key]["value"] += value
+ monthly_agg[key]["count"] += 1
+
+ except Exception as e:
+ logger.warning(f"Error querying {metric_name} for org {org_id}: {e}")
+
+ return hourly_agg, daily_agg, monthly_agg
+
+ def _truncate_to_hour(self, ts: datetime) -> datetime:
+ """Truncate datetime to hour."""
+ if ts.tzinfo is None:
+ ts = timezone.make_aware(ts, timezone.utc)
+ return ts.replace(minute=0, second=0, microsecond=0)
+
+ def _bulk_upsert_hourly(self, aggregations: dict) -> int:
+ """Bulk upsert hourly aggregations using INSERT ... ON CONFLICT."""
+ objects = []
+ for key, agg in aggregations.items():
+ org_id, ts_str, metric_name, project, tag = key
+ objects.append(
+ EventMetricsHourly(
+ organization_id=org_id,
+ timestamp=datetime.fromisoformat(ts_str),
+ metric_name=metric_name,
+ project=project,
+ tag=tag,
+ metric_type=agg["metric_type"],
+ metric_value=agg["value"],
+ metric_count=agg["count"],
+ )
+ )
+ if not objects:
+ return 0
+ EventMetricsHourly._base_manager.bulk_create(
+ objects,
+ update_conflicts=True,
+ unique_fields=[
+ "organization",
+ "timestamp",
+ "metric_name",
+ "project",
+ "tag",
+ ],
+ update_fields=["metric_type", "metric_value", "metric_count", "modified_at"],
+ )
+ return len(objects)
+
+ def _bulk_upsert_daily(self, aggregations: dict) -> int:
+ """Bulk upsert daily aggregations using INSERT ... ON CONFLICT."""
+ objects = []
+ for key, agg in aggregations.items():
+ org_id, date_str, metric_name, project, tag = key
+ objects.append(
+ EventMetricsDaily(
+ organization_id=org_id,
+ date=datetime.fromisoformat(date_str).date(),
+ metric_name=metric_name,
+ project=project,
+ tag=tag,
+ metric_type=agg["metric_type"],
+ metric_value=agg["value"],
+ metric_count=agg["count"],
+ )
+ )
+ if not objects:
+ return 0
+ EventMetricsDaily._base_manager.bulk_create(
+ objects,
+ update_conflicts=True,
+ unique_fields=[
+ "organization",
+ "date",
+ "metric_name",
+ "project",
+ "tag",
+ ],
+ update_fields=["metric_type", "metric_value", "metric_count", "modified_at"],
+ )
+ return len(objects)
+
+ def _bulk_upsert_monthly(self, aggregations: dict) -> int:
+ """Bulk upsert monthly aggregations using INSERT ... ON CONFLICT."""
+ objects = []
+ for key, agg in aggregations.items():
+ org_id, month_str, metric_name, project, tag = key
+ objects.append(
+ EventMetricsMonthly(
+ organization_id=org_id,
+ month=datetime.fromisoformat(month_str).date(),
+ metric_name=metric_name,
+ project=project,
+ tag=tag,
+ metric_type=agg["metric_type"],
+ metric_value=agg["value"],
+ metric_count=agg["count"],
+ )
+ )
+ if not objects:
+ return 0
+ EventMetricsMonthly._base_manager.bulk_create(
+ objects,
+ update_conflicts=True,
+ unique_fields=[
+ "organization",
+ "month",
+ "metric_name",
+ "project",
+ "tag",
+ ],
+ update_fields=["metric_type", "metric_value", "metric_count", "modified_at"],
+ )
+ return len(objects)
diff --git a/backend/dashboard_metrics/migrations/0001_initial.py b/backend/dashboard_metrics/migrations/0001_initial.py
new file mode 100644
index 000000000..eb9f7aa38
--- /dev/null
+++ b/backend/dashboard_metrics/migrations/0001_initial.py
@@ -0,0 +1,348 @@
+# Generated by Django 4.2.1 on 2025-01-08
+
+import uuid
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = [
+ ("account_v2", "0002_user_auth_provider"),
+ ]
+
+ operations = [
+ # Create EventMetricsHourly table
+ migrations.CreateModel(
+ name="EventMetricsHourly",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("modified_at", models.DateTimeField(auto_now=True)),
+ (
+ "id",
+ models.UUIDField(
+ db_comment="Primary key UUID, auto-generated",
+ default=uuid.uuid4,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "timestamp",
+ models.DateTimeField(
+ db_comment="Hour bucket timestamp (truncated to hour)",
+ db_index=True,
+ ),
+ ),
+ (
+ "metric_name",
+ models.CharField(
+ db_comment="Metric identifier from MetricName enum",
+ db_index=True,
+ max_length=64,
+ ),
+ ),
+ (
+ "metric_type",
+ models.CharField(
+ choices=[("counter", "Counter"), ("histogram", "Histogram")],
+ db_comment="Type of metric (counter or histogram)",
+ default="counter",
+ max_length=16,
+ ),
+ ),
+ (
+ "metric_value",
+ models.FloatField(
+ db_comment="Aggregated value (sum for counters, sum for histograms)",
+ default=0,
+ ),
+ ),
+ (
+ "metric_count",
+ models.IntegerField(
+ db_comment="Number of events aggregated into this record",
+ default=1,
+ ),
+ ),
+ (
+ "project",
+ models.CharField(
+ db_comment="Project identifier for filtering",
+ db_index=True,
+ default="default",
+ max_length=64,
+ ),
+ ),
+ (
+ "tag",
+ models.CharField(
+ blank=True,
+ db_comment="Optional tag for categorization",
+ default="",
+ max_length=64,
+ ),
+ ),
+ (
+ "organization",
+ models.ForeignKey(
+ blank=True,
+ db_comment="Foreign key reference to the Organization model.",
+ default=None,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="account_v2.organization",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "Event Metric (Hourly)",
+ "verbose_name_plural": "Event Metrics (Hourly)",
+ "db_table": "event_metrics_hourly",
+ "indexes": [
+ models.Index(
+ fields=["organization", "timestamp"], name="idx_metrics_org_ts"
+ ),
+ models.Index(
+ fields=["organization", "metric_name", "timestamp"],
+ name="idx_metrics_org_name_ts",
+ ),
+ models.Index(
+ fields=["project", "timestamp"], name="idx_metrics_project_ts"
+ ),
+ ],
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="eventmetricshourly",
+ constraint=models.UniqueConstraint(
+ fields=("organization", "timestamp", "metric_name", "project", "tag"),
+ name="unique_hourly_metric",
+ ),
+ ),
+ # Create EventMetricsDaily table
+ migrations.CreateModel(
+ name="EventMetricsDaily",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("modified_at", models.DateTimeField(auto_now=True)),
+ (
+ "id",
+ models.UUIDField(
+ db_comment="Primary key UUID, auto-generated",
+ default=uuid.uuid4,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "date",
+ models.DateField(
+ db_comment="Day bucket (date only)",
+ db_index=True,
+ ),
+ ),
+ (
+ "metric_name",
+ models.CharField(
+ db_comment="Metric identifier from MetricName enum",
+ db_index=True,
+ max_length=64,
+ ),
+ ),
+ (
+ "metric_type",
+ models.CharField(
+ choices=[("counter", "Counter"), ("histogram", "Histogram")],
+ db_comment="Type of metric (counter or histogram)",
+ default="counter",
+ max_length=16,
+ ),
+ ),
+ (
+ "metric_value",
+ models.FloatField(
+ db_comment="Aggregated value (sum for counters)",
+ default=0,
+ ),
+ ),
+ (
+ "metric_count",
+ models.IntegerField(
+ db_comment="Number of events aggregated into this record",
+ default=1,
+ ),
+ ),
+ (
+ "project",
+ models.CharField(
+ db_comment="Project identifier for filtering",
+ db_index=True,
+ default="default",
+ max_length=64,
+ ),
+ ),
+ (
+ "tag",
+ models.CharField(
+ blank=True,
+ db_comment="Optional tag for categorization",
+ default="",
+ max_length=64,
+ ),
+ ),
+ (
+ "organization",
+ models.ForeignKey(
+ blank=True,
+ db_comment="Foreign key reference to the Organization model.",
+ default=None,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="account_v2.organization",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "Event Metric (Daily)",
+ "verbose_name_plural": "Event Metrics (Daily)",
+ "db_table": "event_metrics_daily",
+ "indexes": [
+ models.Index(
+ fields=["organization", "date"],
+ name="idx_daily_org_date",
+ ),
+ models.Index(
+ fields=["organization", "metric_name", "date"],
+ name="idx_daily_org_name_date",
+ ),
+ models.Index(
+ fields=["project", "date"],
+ name="idx_daily_project_date",
+ ),
+ ],
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="eventmetricsdaily",
+ constraint=models.UniqueConstraint(
+ fields=("organization", "date", "metric_name", "project", "tag"),
+ name="unique_daily_metric",
+ ),
+ ),
+ # Create EventMetricsMonthly table
+ migrations.CreateModel(
+ name="EventMetricsMonthly",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("modified_at", models.DateTimeField(auto_now=True)),
+ (
+ "id",
+ models.UUIDField(
+ db_comment="Primary key UUID, auto-generated",
+ default=uuid.uuid4,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "month",
+ models.DateField(
+ db_comment="First day of month bucket",
+ db_index=True,
+ ),
+ ),
+ (
+ "metric_name",
+ models.CharField(
+ db_comment="Metric identifier from MetricName enum",
+ db_index=True,
+ max_length=64,
+ ),
+ ),
+ (
+ "metric_type",
+ models.CharField(
+ choices=[("counter", "Counter"), ("histogram", "Histogram")],
+ db_comment="Type of metric (counter or histogram)",
+ default="counter",
+ max_length=16,
+ ),
+ ),
+ (
+ "metric_value",
+ models.FloatField(
+ db_comment="Aggregated value (sum for counters)",
+ default=0,
+ ),
+ ),
+ (
+ "metric_count",
+ models.IntegerField(
+ db_comment="Number of events aggregated into this record",
+ default=1,
+ ),
+ ),
+ (
+ "project",
+ models.CharField(
+ db_comment="Project identifier for filtering",
+ db_index=True,
+ default="default",
+ max_length=64,
+ ),
+ ),
+ (
+ "tag",
+ models.CharField(
+ blank=True,
+ db_comment="Optional tag for categorization",
+ default="",
+ max_length=64,
+ ),
+ ),
+ (
+ "organization",
+ models.ForeignKey(
+ blank=True,
+ db_comment="Foreign key reference to the Organization model.",
+ default=None,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="account_v2.organization",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "Event Metric (Monthly)",
+ "verbose_name_plural": "Event Metrics (Monthly)",
+ "db_table": "event_metrics_monthly",
+ "indexes": [
+ models.Index(
+ fields=["organization", "month"],
+ name="idx_monthly_org_month",
+ ),
+ models.Index(
+ fields=["organization", "metric_name", "month"],
+ name="idx_monthly_org_name_month",
+ ),
+ models.Index(
+ fields=["project", "month"],
+ name="idx_monthly_project_month",
+ ),
+ ],
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="eventmetricsmonthly",
+ constraint=models.UniqueConstraint(
+ fields=("organization", "month", "metric_name", "project", "tag"),
+ name="unique_monthly_metric",
+ ),
+ ),
+ ]
diff --git a/backend/dashboard_metrics/migrations/0002_setup_periodic_tasks.py b/backend/dashboard_metrics/migrations/0002_setup_periodic_tasks.py
new file mode 100644
index 000000000..a59d3fab0
--- /dev/null
+++ b/backend/dashboard_metrics/migrations/0002_setup_periodic_tasks.py
@@ -0,0 +1,108 @@
+"""Data migration to create periodic tasks for dashboard metrics.
+
+Creates three periodic tasks:
+- Aggregation: Every 15 minutes, queries source tables and populates
+ EventMetricsHourly, EventMetricsDaily, and EventMetricsMonthly
+- Hourly data cleanup: Daily at 2:00 AM UTC, removes hourly data older than 30 days
+- Daily data cleanup: Weekly on Sundays at 3:00 AM UTC, removes daily data older than 365 days
+"""
+
+from django.db import migrations
+
+
+def create_periodic_tasks(apps, schema_editor):
+ """Create all periodic tasks for metrics processing."""
+ CrontabSchedule = apps.get_model("django_celery_beat", "CrontabSchedule")
+ IntervalSchedule = apps.get_model("django_celery_beat", "IntervalSchedule")
+ PeriodicTask = apps.get_model("django_celery_beat", "PeriodicTask")
+
+ # --- Aggregation task: every 15 minutes ---
+ schedule_15min, _ = IntervalSchedule.objects.get_or_create(
+ every=15,
+ period="minutes",
+ )
+
+ PeriodicTask.objects.update_or_create(
+ name="dashboard_metrics_aggregate_from_sources",
+ defaults={
+ "task": "dashboard_metrics.aggregate_from_sources",
+ "interval": schedule_15min,
+ "queue": "dashboard_metric_events",
+ "enabled": True,
+ "description": (
+ "Aggregate metrics from source tables (Usage, PageUsage, etc.) "
+ "into hourly, daily, and monthly metrics tables"
+ ),
+ },
+ )
+
+ # --- Hourly cleanup task: daily at 2:00 AM UTC ---
+ schedule_2am, _ = CrontabSchedule.objects.get_or_create(
+ minute="0",
+ hour="2",
+ day_of_week="*",
+ day_of_month="*",
+ month_of_year="*",
+ defaults={"timezone": "UTC"},
+ )
+
+ PeriodicTask.objects.update_or_create(
+ name="dashboard_metrics_cleanup_hourly",
+ defaults={
+ "task": "dashboard_metrics.cleanup_hourly_data",
+ "crontab": schedule_2am,
+ "queue": "dashboard_metric_events",
+ "kwargs": '{"retention_days": 30}',
+ "enabled": True,
+ "description": "Clean up hourly dashboard metrics older than 30 days",
+ },
+ )
+
+ # --- Daily cleanup task: weekly on Sundays at 3:00 AM UTC ---
+ schedule_3am_sun, _ = CrontabSchedule.objects.get_or_create(
+ minute="0",
+ hour="3",
+ day_of_week="0", # Sunday
+ day_of_month="*",
+ month_of_year="*",
+ defaults={"timezone": "UTC"},
+ )
+
+ PeriodicTask.objects.update_or_create(
+ name="dashboard_metrics_cleanup_daily",
+ defaults={
+ "task": "dashboard_metrics.cleanup_daily_data",
+ "crontab": schedule_3am_sun,
+ "queue": "dashboard_metric_events",
+ "kwargs": '{"retention_days": 365}',
+ "enabled": True,
+ "description": "Clean up daily dashboard metrics older than 365 days",
+ },
+ )
+
+
+def remove_periodic_tasks(apps, schema_editor):
+ """Remove all periodic tasks on rollback."""
+ PeriodicTask = apps.get_model("django_celery_beat", "PeriodicTask")
+
+ PeriodicTask.objects.filter(
+ name__in=[
+ "dashboard_metrics_aggregate_from_sources",
+ "dashboard_metrics_cleanup_hourly",
+ "dashboard_metrics_cleanup_daily",
+ ]
+ ).delete()
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("dashboard_metrics", "0001_initial"),
+ ("django_celery_beat", "0018_improve_crontab_helptext"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ create_periodic_tasks,
+ remove_periodic_tasks,
+ ),
+ ]
diff --git a/backend/dashboard_metrics/migrations/__init__.py b/backend/dashboard_metrics/migrations/__init__.py
new file mode 100644
index 000000000..26ad5a757
--- /dev/null
+++ b/backend/dashboard_metrics/migrations/__init__.py
@@ -0,0 +1 @@
+"""Dashboard metrics migrations."""
diff --git a/backend/dashboard_metrics/models.py b/backend/dashboard_metrics/models.py
new file mode 100644
index 000000000..44fec5439
--- /dev/null
+++ b/backend/dashboard_metrics/models.py
@@ -0,0 +1,334 @@
+"""Django models for Dashboard Metrics."""
+
+import uuid
+
+from django.db import models
+from utils.models.base_model import BaseModel
+from utils.models.organization_mixin import (
+ DefaultOrganizationManagerMixin,
+ DefaultOrganizationMixin,
+)
+
+
+class Granularity(models.TextChoices):
+ """Time granularity for metric aggregation."""
+
+ HOUR = "hour", "Hour"
+ DAY = "day", "Day"
+ WEEK = "week", "Week"
+
+
+class MetricType(models.TextChoices):
+ """Type of metric - determines aggregation behavior."""
+
+ COUNTER = "counter", "Counter"
+ HISTOGRAM = "histogram", "Histogram"
+
+
+class EventMetricsHourlyManager(DefaultOrganizationManagerMixin):
+ """Manager for EventMetricsHourly with organization filtering."""
+
+ pass
+
+
+class EventMetricsDailyManager(DefaultOrganizationManagerMixin):
+ """Manager for EventMetricsDaily with organization filtering."""
+
+ pass
+
+
+class EventMetricsMonthlyManager(DefaultOrganizationManagerMixin):
+ """Manager for EventMetricsMonthly with organization filtering."""
+
+ pass
+
+
+class EventMetricsHourly(DefaultOrganizationMixin, BaseModel):
+ """Hourly aggregated metrics for dashboard display.
+
+ Stores metric events aggregated by hour for efficient querying.
+ Pre-computed by the scheduled aggregation task every 15 minutes.
+
+ Attributes:
+ id: UUID primary key
+ timestamp: Hour bucket timestamp (truncated to hour)
+ metric_name: Name of the metric from MetricName enum
+ metric_type: Type of metric (counter or histogram)
+ metric_value: Aggregated value (sum for counters, sum for histograms)
+ metric_count: Number of events aggregated into this record
+ project: Project identifier for filtering
+ tag: Optional tag for categorization
+ """
+
+ id = models.UUIDField(
+ primary_key=True,
+ default=uuid.uuid4,
+ editable=False,
+ db_comment="Primary key UUID, auto-generated",
+ )
+ timestamp = models.DateTimeField(
+ db_index=True,
+ db_comment="Hour bucket timestamp (truncated to hour)",
+ )
+ metric_name = models.CharField(
+ max_length=64,
+ db_index=True,
+ db_comment="Metric identifier from MetricName enum",
+ )
+ metric_type = models.CharField(
+ max_length=16,
+ choices=MetricType.choices,
+ default=MetricType.COUNTER,
+ db_comment="Type of metric (counter or histogram)",
+ )
+ metric_value = models.FloatField(
+ default=0,
+ db_comment="Aggregated value (sum for counters, sum for histograms)",
+ )
+ metric_count = models.IntegerField(
+ default=1,
+ db_comment="Number of events aggregated into this record",
+ )
+ project = models.CharField(
+ max_length=64,
+ default="default",
+ db_index=True,
+ db_comment="Project identifier for filtering",
+ )
+ tag = models.CharField(
+ max_length=64,
+ default="",
+ blank=True,
+ db_comment="Optional tag for categorization",
+ )
+
+ # Manager
+ objects = EventMetricsHourlyManager()
+
+ def __str__(self) -> str:
+ return f"{self.metric_name}@{self.timestamp}: {self.metric_value}"
+
+ class Meta:
+ db_table = "event_metrics_hourly"
+ verbose_name = "Event Metric (Hourly)"
+ verbose_name_plural = "Event Metrics (Hourly)"
+ indexes = [
+ models.Index(
+ fields=["organization", "timestamp"],
+ name="idx_metrics_org_ts",
+ ),
+ models.Index(
+ fields=["organization", "metric_name", "timestamp"],
+ name="idx_metrics_org_name_ts",
+ ),
+ models.Index(
+ fields=["project", "timestamp"],
+ name="idx_metrics_project_ts",
+ ),
+ ]
+ constraints = [
+ models.UniqueConstraint(
+ fields=[
+ "organization",
+ "timestamp",
+ "metric_name",
+ "project",
+ "tag",
+ ],
+ name="unique_hourly_metric",
+ )
+ ]
+
+
+class EventMetricsDaily(DefaultOrganizationMixin, BaseModel):
+ """Daily aggregated metrics for dashboard display.
+
+ Stores metric events aggregated by day for efficient querying.
+ Pre-computed by the scheduled aggregation task every 15 minutes.
+
+ Attributes:
+ id: UUID primary key
+ date: Day bucket (date only)
+ metric_name: Name of the metric from MetricName enum
+ metric_type: Type of metric (counter or histogram)
+ metric_value: Aggregated value (sum for counters)
+ metric_count: Number of events aggregated into this record
+ project: Project identifier for filtering
+ tag: Optional tag for categorization
+ """
+
+ id = models.UUIDField(
+ primary_key=True,
+ default=uuid.uuid4,
+ editable=False,
+ db_comment="Primary key UUID, auto-generated",
+ )
+ date = models.DateField(
+ db_index=True,
+ db_comment="Day bucket (date only)",
+ )
+ metric_name = models.CharField(
+ max_length=64,
+ db_index=True,
+ db_comment="Metric identifier from MetricName enum",
+ )
+ metric_type = models.CharField(
+ max_length=16,
+ choices=MetricType.choices,
+ default=MetricType.COUNTER,
+ db_comment="Type of metric (counter or histogram)",
+ )
+ metric_value = models.FloatField(
+ default=0,
+ db_comment="Aggregated value (sum for counters)",
+ )
+ metric_count = models.IntegerField(
+ default=1,
+ db_comment="Number of events aggregated into this record",
+ )
+ project = models.CharField(
+ max_length=64,
+ default="default",
+ db_index=True,
+ db_comment="Project identifier for filtering",
+ )
+ tag = models.CharField(
+ max_length=64,
+ default="",
+ blank=True,
+ db_comment="Optional tag for categorization",
+ )
+
+ # Manager
+ objects = EventMetricsDailyManager()
+
+ def __str__(self) -> str:
+ return f"{self.metric_name}@{self.date}: {self.metric_value}"
+
+ class Meta:
+ db_table = "event_metrics_daily"
+ verbose_name = "Event Metric (Daily)"
+ verbose_name_plural = "Event Metrics (Daily)"
+ indexes = [
+ models.Index(
+ fields=["organization", "date"],
+ name="idx_daily_org_date",
+ ),
+ models.Index(
+ fields=["organization", "metric_name", "date"],
+ name="idx_daily_org_name_date",
+ ),
+ models.Index(
+ fields=["project", "date"],
+ name="idx_daily_project_date",
+ ),
+ ]
+ constraints = [
+ models.UniqueConstraint(
+ fields=[
+ "organization",
+ "date",
+ "metric_name",
+ "project",
+ "tag",
+ ],
+ name="unique_daily_metric",
+ )
+ ]
+
+
+class EventMetricsMonthly(DefaultOrganizationMixin, BaseModel):
+ """Monthly aggregated metrics for dashboard display.
+
+ Stores metric events aggregated by month for efficient querying.
+ Pre-computed by the scheduled aggregation task every 15 minutes.
+
+ Attributes:
+ id: UUID primary key
+ month: First day of month bucket
+ metric_name: Name of the metric from MetricName enum
+ metric_type: Type of metric (counter or histogram)
+ metric_value: Aggregated value (sum for counters)
+ metric_count: Number of events aggregated into this record
+ project: Project identifier for filtering
+ tag: Optional tag for categorization
+ """
+
+ id = models.UUIDField(
+ primary_key=True,
+ default=uuid.uuid4,
+ editable=False,
+ db_comment="Primary key UUID, auto-generated",
+ )
+ month = models.DateField(
+ db_index=True,
+ db_comment="First day of month bucket",
+ )
+ metric_name = models.CharField(
+ max_length=64,
+ db_index=True,
+ db_comment="Metric identifier from MetricName enum",
+ )
+ metric_type = models.CharField(
+ max_length=16,
+ choices=MetricType.choices,
+ default=MetricType.COUNTER,
+ db_comment="Type of metric (counter or histogram)",
+ )
+ metric_value = models.FloatField(
+ default=0,
+ db_comment="Aggregated value (sum for counters)",
+ )
+ metric_count = models.IntegerField(
+ default=1,
+ db_comment="Number of events aggregated into this record",
+ )
+ project = models.CharField(
+ max_length=64,
+ default="default",
+ db_index=True,
+ db_comment="Project identifier for filtering",
+ )
+ tag = models.CharField(
+ max_length=64,
+ default="",
+ blank=True,
+ db_comment="Optional tag for categorization",
+ )
+
+ # Manager
+ objects = EventMetricsMonthlyManager()
+
+ def __str__(self) -> str:
+ return f"{self.metric_name}@{self.month}: {self.metric_value}"
+
+ class Meta:
+ db_table = "event_metrics_monthly"
+ verbose_name = "Event Metric (Monthly)"
+ verbose_name_plural = "Event Metrics (Monthly)"
+ indexes = [
+ models.Index(
+ fields=["organization", "month"],
+ name="idx_monthly_org_month",
+ ),
+ models.Index(
+ fields=["organization", "metric_name", "month"],
+ name="idx_monthly_org_name_month",
+ ),
+ models.Index(
+ fields=["project", "month"],
+ name="idx_monthly_project_month",
+ ),
+ ]
+ constraints = [
+ models.UniqueConstraint(
+ fields=[
+ "organization",
+ "month",
+ "metric_name",
+ "project",
+ "tag",
+ ],
+ name="unique_monthly_metric",
+ )
+ ]
diff --git a/backend/dashboard_metrics/serializers.py b/backend/dashboard_metrics/serializers.py
new file mode 100644
index 000000000..844a8c173
--- /dev/null
+++ b/backend/dashboard_metrics/serializers.py
@@ -0,0 +1,91 @@
+"""Serializers for Dashboard Metrics API."""
+
+from datetime import timedelta
+
+from django.utils import timezone
+from rest_framework import serializers
+
+from .models import EventMetricsHourly
+
+
+class MetricsQuerySerializer(serializers.Serializer):
+ """Serializer for metrics query parameters."""
+
+ start_date = serializers.DateTimeField(
+ required=False,
+ help_text="Start of date range (ISO 8601). Defaults to 30 days ago.",
+ )
+ end_date = serializers.DateTimeField(
+ required=False,
+ help_text="End of date range (ISO 8601). Defaults to now.",
+ )
+ metric_name = serializers.CharField(
+ required=False,
+ help_text="Filter by specific metric name.",
+ )
+ project = serializers.CharField(
+ required=False,
+ help_text="Filter by project identifier.",
+ )
+ tag = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Filter by tag.",
+ )
+ granularity = serializers.ChoiceField(
+ choices=["hour", "day", "week"],
+ default="day",
+ help_text="Time granularity for aggregation.",
+ )
+ source = serializers.ChoiceField(
+ choices=["auto", "hourly", "daily", "monthly"],
+ default="auto",
+ required=False,
+ help_text=(
+ "Data source table. 'auto' selects based on date range: "
+ "≤7 days=hourly, ≤90 days=daily, >90 days=monthly."
+ ),
+ )
+
+ 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
+
+
+class EventMetricsHourlySerializer(serializers.ModelSerializer):
+ """Model serializer for EventMetricsHourly records."""
+
+ class Meta:
+ model = EventMetricsHourly
+ fields = [
+ "id",
+ "timestamp",
+ "metric_name",
+ "metric_type",
+ "metric_value",
+ "metric_count",
+ "project",
+ "tag",
+ "created_at",
+ ]
+ read_only_fields = fields
diff --git a/backend/dashboard_metrics/services.py b/backend/dashboard_metrics/services.py
new file mode 100644
index 000000000..1942bd7aa
--- /dev/null
+++ b/backend/dashboard_metrics/services.py
@@ -0,0 +1,766 @@
+"""Services for querying metrics from existing tables.
+
+This module provides the MetricsQueryService class which queries metrics
+directly from source tables (usage, page_usage, workflow_execution, etc.)
+and aggregates them into event_metrics_hourly/daily/monthly tables.
+
+Note: Uses _base_manager for models with DefaultOrganizationManagerMixin
+to bypass the UserContext filter when running from Celery tasks.
+"""
+
+from datetime import datetime
+from typing import Any
+
+from account_usage.models import PageUsage
+from api_v2.models import APIDeployment
+from django.db.models import CharField, Count, OuterRef, Q, Subquery, Sum
+from django.db.models.functions import Cast, Coalesce, TruncDay, TruncHour, TruncWeek
+from pipeline_v2.models import Pipeline
+from usage_v2.models import Usage
+from workflow_manager.file_execution.models import WorkflowFileExecution
+from workflow_manager.workflow_v2.models.execution import WorkflowExecution
+
+from dashboard_metrics.models import Granularity
+from unstract.core.data_models import ExecutionStatus
+
+
+def _get_usage_queryset():
+ """Get Usage queryset bypassing the organization context filter.
+
+ Usage model uses DefaultOrganizationManagerMixin which filters by
+ UserContext.get_organization(). This returns None in Celery tasks,
+ causing queries to return empty results. Use _base_manager instead.
+ """
+ return Usage._base_manager.all()
+
+
+class MetricsQueryService:
+ """Service for querying metrics from source tables.
+
+ This service provides methods to query each metric type from its
+ respective source table, with support for date filtering and
+ time-based aggregation (hourly, daily, weekly).
+
+ Metrics available:
+ - documents_processed: from workflow_file_execution
+ - pages_processed: from page_usage
+ - llm_calls: from usage (type=llm)
+ - challenges: from usage (reason=challenge)
+ - summarization_calls: from usage (reason=summarize)
+ - deployed_api_requests: from workflow_execution + api_deployment
+ - etl_pipeline_executions: from workflow_execution + pipeline
+ - llm_usage: from usage (cost_in_dollars)
+ - prompt_executions: from workflow_execution
+ """
+
+ @staticmethod
+ def _get_trunc_func(granularity: str):
+ """Get the appropriate truncation function for the granularity."""
+ trunc_map = {
+ Granularity.HOUR: TruncHour,
+ Granularity.DAY: TruncDay,
+ Granularity.WEEK: TruncWeek,
+ }
+ return trunc_map.get(granularity, TruncDay)
+
+ @staticmethod
+ def get_documents_processed(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = Granularity.DAY,
+ ) -> list[dict[str, Any]]:
+ """Query documents processed from workflow_file_execution.
+
+ Counts completed file executions grouped by time period.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: Time granularity (hour, day, week)
+
+ Returns:
+ List of dicts with 'period' and 'value' keys
+ """
+ trunc_func = MetricsQueryService._get_trunc_func(granularity)
+
+ return list(
+ WorkflowFileExecution.objects.filter(
+ workflow_execution__workflow__organization_id=organization_id,
+ status=ExecutionStatus.COMPLETED,
+ created_at__gte=start_date,
+ created_at__lte=end_date,
+ )
+ .annotate(period=trunc_func("created_at"))
+ .values("period")
+ .annotate(value=Count("id"))
+ .order_by("period")
+ )
+
+ @staticmethod
+ def get_pages_processed(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = Granularity.DAY,
+ ) -> list[dict[str, Any]]:
+ """Query pages processed from page_usage.
+
+ Sums pages_processed field grouped by time period.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: Time granularity (hour, day, week)
+
+ Returns:
+ List of dicts with 'period' and 'value' keys
+ """
+ trunc_func = MetricsQueryService._get_trunc_func(granularity)
+
+ return list(
+ PageUsage.objects.filter(
+ organization_id=organization_id,
+ created_at__gte=start_date,
+ created_at__lte=end_date,
+ )
+ .annotate(period=trunc_func("created_at"))
+ .values("period")
+ .annotate(value=Sum("pages_processed"))
+ .order_by("period")
+ )
+
+ @staticmethod
+ def get_llm_calls(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = Granularity.DAY,
+ ) -> list[dict[str, Any]]:
+ """Query LLM calls from usage table.
+
+ Counts usage records where usage_type='llm' grouped by time period.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: Time granularity (hour, day, week)
+
+ Returns:
+ List of dicts with 'period' and 'value' keys
+ """
+ trunc_func = MetricsQueryService._get_trunc_func(granularity)
+
+ return list(
+ _get_usage_queryset()
+ .filter(
+ organization_id=organization_id,
+ usage_type="llm",
+ created_at__gte=start_date,
+ created_at__lte=end_date,
+ )
+ .annotate(period=trunc_func("created_at"))
+ .values("period")
+ .annotate(value=Count("id"))
+ .order_by("period")
+ )
+
+ @staticmethod
+ def get_challenges(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = Granularity.DAY,
+ ) -> list[dict[str, Any]]:
+ """Query challenge calls from usage table.
+
+ Counts usage records where llm_usage_reason='challenge' grouped by time period.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: Time granularity (hour, day, week)
+
+ Returns:
+ List of dicts with 'period' and 'value' keys
+ """
+ trunc_func = MetricsQueryService._get_trunc_func(granularity)
+
+ return list(
+ _get_usage_queryset()
+ .filter(
+ organization_id=organization_id,
+ usage_type="llm",
+ llm_usage_reason="challenge",
+ created_at__gte=start_date,
+ created_at__lte=end_date,
+ )
+ .annotate(period=trunc_func("created_at"))
+ .values("period")
+ .annotate(value=Count("id"))
+ .order_by("period")
+ )
+
+ @staticmethod
+ def get_summarization_calls(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = Granularity.DAY,
+ ) -> list[dict[str, Any]]:
+ """Query summarization calls from usage table.
+
+ Counts usage records where llm_usage_reason='summarize' grouped by time period.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: Time granularity (hour, day, week)
+
+ Returns:
+ List of dicts with 'period' and 'value' keys
+ """
+ trunc_func = MetricsQueryService._get_trunc_func(granularity)
+
+ return list(
+ _get_usage_queryset()
+ .filter(
+ organization_id=organization_id,
+ usage_type="llm",
+ llm_usage_reason="summarize",
+ created_at__gte=start_date,
+ created_at__lte=end_date,
+ )
+ .annotate(period=trunc_func("created_at"))
+ .values("period")
+ .annotate(value=Count("id"))
+ .order_by("period")
+ )
+
+ @staticmethod
+ def get_deployed_api_requests(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = Granularity.DAY,
+ ) -> list[dict[str, Any]]:
+ """Query API deployment requests from workflow_execution.
+
+ Counts workflow executions where pipeline_id matches an API deployment
+ for the organization, grouped by time period.
+
+ Uses subquery to avoid N+1 query pattern.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: Time granularity (hour, day, week)
+
+ Returns:
+ List of dicts with 'period' and 'value' keys
+ """
+ trunc_func = MetricsQueryService._get_trunc_func(granularity)
+
+ # Use _base_manager to bypass DefaultOrganizationManagerMixin
+ # (UserContext is None in Celery tasks)
+ api_subquery = APIDeployment._base_manager.filter(
+ organization_id=organization_id
+ ).values("id")
+
+ return list(
+ WorkflowExecution.objects.filter(
+ pipeline_id__in=Subquery(api_subquery),
+ created_at__gte=start_date,
+ created_at__lte=end_date,
+ )
+ .annotate(period=trunc_func("created_at"))
+ .values("period")
+ .annotate(value=Count("id"))
+ .order_by("period")
+ )
+
+ @staticmethod
+ def get_etl_pipeline_executions(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = Granularity.DAY,
+ ) -> list[dict[str, Any]]:
+ """Query ETL pipeline executions from workflow_execution.
+
+ Counts workflow executions where pipeline_id matches an ETL pipeline
+ for the organization, grouped by time period.
+
+ Uses subquery to avoid N+1 query pattern.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: Time granularity (hour, day, week)
+
+ Returns:
+ List of dicts with 'period' and 'value' keys
+ """
+ trunc_func = MetricsQueryService._get_trunc_func(granularity)
+
+ # Use _base_manager to bypass DefaultOrganizationManagerMixin
+ # (UserContext is None in Celery tasks)
+ pipeline_subquery = Pipeline._base_manager.filter(
+ organization_id=organization_id,
+ pipeline_type="ETL",
+ ).values("id")
+
+ return list(
+ WorkflowExecution.objects.filter(
+ pipeline_id__in=Subquery(pipeline_subquery),
+ created_at__gte=start_date,
+ created_at__lte=end_date,
+ )
+ .annotate(period=trunc_func("created_at"))
+ .values("period")
+ .annotate(value=Count("id"))
+ .order_by("period")
+ )
+
+ @staticmethod
+ def get_llm_usage_cost(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = Granularity.DAY,
+ ) -> list[dict[str, Any]]:
+ """Query LLM usage cost from usage table.
+
+ Sums cost_in_dollars for LLM usage records grouped by time period.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: Time granularity (hour, day, week)
+
+ Returns:
+ List of dicts with 'period' and 'value' keys
+ """
+ trunc_func = MetricsQueryService._get_trunc_func(granularity)
+
+ return list(
+ _get_usage_queryset()
+ .filter(
+ organization_id=organization_id,
+ usage_type="llm",
+ created_at__gte=start_date,
+ created_at__lte=end_date,
+ )
+ .annotate(period=trunc_func("created_at"))
+ .values("period")
+ .annotate(value=Sum("cost_in_dollars"))
+ .order_by("period")
+ )
+
+ @staticmethod
+ def get_prompt_executions(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = Granularity.DAY,
+ ) -> list[dict[str, Any]]:
+ """Query prompt executions from workflow_execution.
+
+ Counts all workflow executions for the organization grouped by time period.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: Time granularity (hour, day, week)
+
+ Returns:
+ List of dicts with 'period' and 'value' keys
+ """
+ trunc_func = MetricsQueryService._get_trunc_func(granularity)
+
+ return list(
+ WorkflowExecution.objects.filter(
+ workflow__organization_id=organization_id,
+ created_at__gte=start_date,
+ created_at__lte=end_date,
+ )
+ .annotate(period=trunc_func("created_at"))
+ .values("period")
+ .annotate(value=Count("id"))
+ .order_by("period")
+ )
+
+ @staticmethod
+ def get_failed_pages(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = Granularity.DAY,
+ ) -> list[dict[str, Any]]:
+ """Query failed pages from workflow_file_execution + page_usage.
+
+ Sums pages_processed for file executions with status='ERROR',
+ grouped by time period based on when the failure occurred.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: Time granularity (hour, day, week)
+
+ Returns:
+ List of dicts with 'period' and 'value' keys
+ """
+ trunc_func = MetricsQueryService._get_trunc_func(granularity)
+
+ # Subquery: get pages for each file execution from page_usage
+ # Join on: page_usage.run_id = workflow_file_execution.id::text
+ pages_subquery = (
+ PageUsage.objects.filter(run_id=Cast(OuterRef("id"), CharField()))
+ .values("run_id")
+ .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")
+ )
+
+ @staticmethod
+ def get_hitl_reviews(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = Granularity.DAY,
+ ) -> list[dict[str, Any]]:
+ """Query HITL review counts from manual_review_v2.
+
+ Returns empty list on OSS where manual_review_v2 is not installed.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: Time granularity (hour, day, week)
+
+ Returns:
+ List of dicts with 'period' and 'value' keys
+ """
+ try:
+ from manual_review_v2.models import ManualReviewEntity
+ except ImportError:
+ return []
+
+ trunc_func = MetricsQueryService._get_trunc_func(granularity)
+
+ return list(
+ ManualReviewEntity.objects.filter(
+ organization_id=organization_id,
+ created_at__gte=start_date,
+ created_at__lte=end_date,
+ )
+ .annotate(period=trunc_func("created_at"))
+ .values("period")
+ .annotate(value=Count("id"))
+ .order_by("period")
+ )
+
+ @staticmethod
+ def get_hitl_completions(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ granularity: str = Granularity.DAY,
+ ) -> list[dict[str, Any]]:
+ """Query completed HITL reviews from manual_review_v2.
+
+ Returns empty list on OSS where manual_review_v2 is not installed.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+ granularity: Time granularity (hour, day, week)
+
+ Returns:
+ List of dicts with 'period' and 'value' keys
+ """
+ try:
+ from manual_review_v2.models import ManualReviewEntity
+ except ImportError:
+ return []
+
+ trunc_func = MetricsQueryService._get_trunc_func(granularity)
+
+ return list(
+ ManualReviewEntity.objects.filter(
+ organization_id=organization_id,
+ status="APPROVED",
+ modified_at__gte=start_date,
+ modified_at__lte=end_date,
+ )
+ .annotate(period=trunc_func("modified_at"))
+ .values("period")
+ .annotate(value=Count("id"))
+ .order_by("period")
+ )
+
+ @classmethod
+ def get_all_metrics_summary(
+ cls,
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ ) -> dict[str, float]:
+ """Get summary totals for all metrics.
+
+ Aggregates all metric types for the given date range.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+
+ Returns:
+ Dict mapping metric name to total value
+ """
+ return {
+ "documents_processed": sum(
+ r["value"]
+ for r in cls.get_documents_processed(
+ organization_id, start_date, end_date
+ )
+ ),
+ "pages_processed": sum(
+ r["value"] or 0
+ for r in cls.get_pages_processed(organization_id, start_date, end_date)
+ ),
+ "llm_calls": sum(
+ r["value"]
+ for r in cls.get_llm_calls(organization_id, start_date, end_date)
+ ),
+ "challenges": sum(
+ r["value"]
+ for r in cls.get_challenges(organization_id, start_date, end_date)
+ ),
+ "summarization_calls": sum(
+ r["value"]
+ for r in cls.get_summarization_calls(
+ organization_id, start_date, end_date
+ )
+ ),
+ "deployed_api_requests": sum(
+ r["value"]
+ for r in cls.get_deployed_api_requests(
+ organization_id, start_date, end_date
+ )
+ ),
+ "etl_pipeline_executions": sum(
+ r["value"]
+ for r in cls.get_etl_pipeline_executions(
+ organization_id, start_date, end_date
+ )
+ ),
+ "llm_usage": sum(
+ r["value"] or 0
+ for r in cls.get_llm_usage_cost(organization_id, start_date, end_date)
+ ),
+ "prompt_executions": sum(
+ r["value"]
+ for r in cls.get_prompt_executions(organization_id, start_date, end_date)
+ ),
+ "failed_pages": sum(
+ r["value"] or 0
+ for r in cls.get_failed_pages(organization_id, start_date, end_date)
+ ),
+ }
+
+ @staticmethod
+ def get_recent_activity(
+ organization_id: str,
+ limit: int = 10,
+ ) -> list[dict[str, Any]]:
+ """Get recent processing activity across all execution types.
+
+ Returns recent file executions with type differentiation:
+ - etl: pipeline_id matches ETL Pipeline
+ - api: pipeline_id matches APIDeployment
+ - workflow: pipeline_id is null (manual workflow/prompt studio)
+
+ Args:
+ organization_id: Organization UUID string
+ limit: Maximum number of records to return
+
+ 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)
+ )
+
+ # 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
+
+ # 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"
+
+ results.append(
+ {
+ "id": str(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,
+ }
+ )
+
+ # 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
+
+ @staticmethod
+ def get_workflow_token_usage(
+ organization_id: str,
+ start_date: datetime,
+ end_date: datetime,
+ ) -> list[dict[str, Any]]:
+ """Get per-workflow LLM token usage breakdown.
+
+ Aggregates total_tokens and cost_in_dollars grouped by workflow,
+ with workflow name resolved from the Workflow model.
+
+ Args:
+ organization_id: Organization UUID string
+ start_date: Start of date range
+ end_date: End of date range
+
+ Returns:
+ List of dicts with workflow_id, workflow_name, total_tokens,
+ total_cost, and call_count, ordered by total_tokens descending.
+ """
+ from workflow_manager.workflow_v2.models.workflow import Workflow
+
+ # Query Usage grouped by workflow_id
+ usage_qs = (
+ _get_usage_queryset()
+ .filter(
+ organization_id=organization_id,
+ usage_type="llm",
+ created_at__gte=start_date,
+ created_at__lte=end_date,
+ )
+ .exclude(Q(workflow_id__isnull=True) | Q(workflow_id=""))
+ .values("workflow_id")
+ .annotate(
+ total_tokens=Sum("total_tokens"),
+ total_cost=Sum("cost_in_dollars"),
+ call_count=Count("id"),
+ )
+ .order_by("-total_tokens")
+ )
+
+ # Evaluate queryset once to avoid double DB hit
+ usage_rows = list(usage_qs)
+
+ # Resolve workflow names using _base_manager to bypass
+ # DefaultOrganizationManagerMixin (UserContext is None in Celery tasks)
+ workflow_ids = [row["workflow_id"] for row in usage_rows]
+ workflow_names = {}
+ if workflow_ids:
+ workflows = Workflow._base_manager.filter(id__in=workflow_ids).values(
+ "id", "workflow_name"
+ )
+ workflow_names = {str(w["id"]): w["workflow_name"] for w in workflows}
+
+ results = []
+ for row in usage_rows:
+ wf_id = row["workflow_id"]
+ results.append(
+ {
+ "workflow_id": str(wf_id),
+ "workflow_name": workflow_names.get(str(wf_id), "Unknown"),
+ "total_tokens": row["total_tokens"] or 0,
+ "total_cost": round(row["total_cost"] or 0, 4),
+ "call_count": row["call_count"] or 0,
+ }
+ )
+
+ return results
diff --git a/backend/dashboard_metrics/tasks.py b/backend/dashboard_metrics/tasks.py
new file mode 100644
index 000000000..414d86ad1
--- /dev/null
+++ b/backend/dashboard_metrics/tasks.py
@@ -0,0 +1,551 @@
+"""Celery tasks for Dashboard Metrics aggregation and cleanup.
+
+Tasks:
+- aggregate_metrics_from_sources: Periodic aggregation from source tables
+- cleanup_hourly_metrics: Remove hourly metrics older than retention period
+- cleanup_daily_metrics: Remove daily metrics older than retention period
+"""
+
+import logging
+from datetime import datetime, timedelta
+from typing import Any
+
+from celery import shared_task
+from django.core.cache import cache
+from django.db.utils import DatabaseError, OperationalError
+from django.utils import timezone
+
+from .models import (
+ EventMetricsDaily,
+ EventMetricsHourly,
+ EventMetricsMonthly,
+ Granularity,
+ MetricType,
+)
+from .services import MetricsQueryService
+
+logger = logging.getLogger(__name__)
+
+# Retention periods for metrics cleanup
+DASHBOARD_HOURLY_METRICS_RETENTION_DAYS = 30
+DASHBOARD_DAILY_METRICS_RETENTION_DAYS = 365
+
+
+def _truncate_to_hour(ts: float | datetime) -> datetime:
+ """Truncate a timestamp to the hour.
+
+ Args:
+ ts: Unix timestamp (float) or datetime object
+
+ Returns:
+ datetime truncated to the hour in UTC
+ """
+ if isinstance(ts, (int, float)):
+ dt = datetime.fromtimestamp(ts, tz=timezone.utc)
+ else:
+ dt = ts if ts.tzinfo else timezone.make_aware(ts, timezone.utc)
+ return dt.replace(minute=0, second=0, microsecond=0)
+
+
+def _truncate_to_day(ts: datetime) -> datetime:
+ """Truncate a datetime to midnight (start of day).
+
+ Args:
+ ts: datetime object
+
+ Returns:
+ datetime truncated to midnight
+ """
+ return ts.replace(hour=0, minute=0, second=0, microsecond=0)
+
+
+def _truncate_to_month(ts: datetime) -> datetime:
+ """Truncate a datetime to first day of month.
+
+ Args:
+ ts: datetime object
+
+ Returns:
+ datetime set to first day of month at midnight
+ """
+ return ts.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+
+
+def _bulk_upsert_hourly(aggregations: dict) -> int:
+ """Bulk upsert hourly aggregations using INSERT ... ON CONFLICT.
+
+ Uses bulk_create with update_conflicts to perform a single SQL statement
+ instead of N×2 roundtrips (SELECT + INSERT/UPDATE per row).
+
+ Uses _base_manager to bypass DefaultOrganizationManagerMixin which
+ filters by UserContext.get_organization() — returns None in Celery context.
+
+ Args:
+ aggregations: Dict of aggregated metric data keyed by
+ (org_id, hour_ts_str, metric_name, project, tag)
+
+ Returns:
+ Number of rows upserted
+ """
+ objects = []
+ for key, agg in aggregations.items():
+ org_id, hour_ts_str, metric_name, project, tag = key
+ objects.append(
+ EventMetricsHourly(
+ organization_id=org_id,
+ timestamp=datetime.fromisoformat(hour_ts_str),
+ metric_name=metric_name,
+ project=project,
+ tag=tag,
+ metric_type=agg["metric_type"],
+ metric_value=agg["value"],
+ metric_count=agg["count"],
+ )
+ )
+
+ if not objects:
+ return 0
+
+ EventMetricsHourly._base_manager.bulk_create(
+ objects,
+ update_conflicts=True,
+ unique_fields=["organization", "timestamp", "metric_name", "project", "tag"],
+ update_fields=["metric_type", "metric_value", "metric_count", "modified_at"],
+ )
+ return len(objects)
+
+
+def _bulk_upsert_daily(aggregations: dict) -> int:
+ """Bulk upsert daily aggregations using INSERT ... ON CONFLICT.
+
+ Uses _base_manager to bypass DefaultOrganizationManagerMixin.
+
+ Args:
+ aggregations: Dict keyed by (org_id, date_str, metric_name, project, tag)
+
+ Returns:
+ Number of rows upserted
+ """
+ objects = []
+ for key, agg in aggregations.items():
+ org_id, date_str, metric_name, project, tag = key
+ objects.append(
+ EventMetricsDaily(
+ organization_id=org_id,
+ date=datetime.fromisoformat(date_str).date(),
+ metric_name=metric_name,
+ project=project,
+ tag=tag,
+ metric_type=agg["metric_type"],
+ metric_value=agg["value"],
+ metric_count=agg["count"],
+ )
+ )
+
+ if not objects:
+ return 0
+
+ EventMetricsDaily._base_manager.bulk_create(
+ objects,
+ update_conflicts=True,
+ unique_fields=["organization", "date", "metric_name", "project", "tag"],
+ update_fields=["metric_type", "metric_value", "metric_count", "modified_at"],
+ )
+ return len(objects)
+
+
+def _bulk_upsert_monthly(aggregations: dict) -> int:
+ """Bulk upsert monthly aggregations using INSERT ... ON CONFLICT.
+
+ Uses _base_manager to bypass DefaultOrganizationManagerMixin.
+
+ Args:
+ aggregations: Dict keyed by (org_id, month_str, metric_name, project, tag)
+
+ Returns:
+ Number of rows upserted
+ """
+ objects = []
+ for key, agg in aggregations.items():
+ org_id, month_str, metric_name, project, tag = key
+ objects.append(
+ EventMetricsMonthly(
+ organization_id=org_id,
+ month=datetime.fromisoformat(month_str).date(),
+ metric_name=metric_name,
+ project=project,
+ tag=tag,
+ metric_type=agg["metric_type"],
+ metric_value=agg["value"],
+ metric_count=agg["count"],
+ )
+ )
+
+ if not objects:
+ return 0
+
+ EventMetricsMonthly._base_manager.bulk_create(
+ objects,
+ update_conflicts=True,
+ unique_fields=["organization", "month", "metric_name", "project", "tag"],
+ update_fields=["metric_type", "metric_value", "metric_count", "modified_at"],
+ )
+ return len(objects)
+
+
+AGGREGATION_LOCK_KEY = "dashboard_metrics:aggregation_lock"
+AGGREGATION_LOCK_TIMEOUT = 900 # 15 minutes (matches task schedule)
+
+
+@shared_task(
+ name="dashboard_metrics.aggregate_from_sources",
+ soft_time_limit=600,
+ time_limit=660,
+ max_retries=3,
+ autoretry_for=(DatabaseError, OperationalError),
+ retry_backoff=True,
+ retry_backoff_max=300,
+)
+def aggregate_metrics_from_sources() -> dict[str, Any]:
+ """Aggregate metrics from source tables into hourly, daily, and monthly tables.
+
+ This task runs periodically (every 15 minutes) to query metrics from
+ source tables (Usage, PageUsage, WorkflowExecution, etc.) and aggregate
+ them into EventMetricsHourly, EventMetricsDaily, and EventMetricsMonthly
+ tables for fast dashboard queries at different granularities.
+
+ Uses a Redis distributed lock to prevent overlapping runs when a task
+ takes longer than the 15-minute schedule interval.
+
+ Aggregation windows:
+ - Hourly: Last 24 hours (rolling window)
+ - Daily: Last 2 days (to catch day boundaries)
+ - Monthly: Current month (updates running total)
+
+ Returns:
+ Dict with aggregation summary for all three tiers
+ """
+ # Acquire distributed lock to prevent overlapping runs
+ if not cache.add(AGGREGATION_LOCK_KEY, "running", AGGREGATION_LOCK_TIMEOUT):
+ logger.info("Skipping aggregation — another run is in progress")
+ return {"success": True, "skipped": True, "reason": "lock_held"}
+
+ try:
+ return _run_aggregation()
+ finally:
+ cache.delete(AGGREGATION_LOCK_KEY)
+
+
+def _run_aggregation() -> dict[str, Any]:
+ """Execute the actual aggregation logic.
+
+ Separated from the task function to keep the lock management clean.
+ """
+ from account_v2.models import Organization
+ from workflow_manager.workflow_v2.models.execution import WorkflowExecution
+
+ end_date = timezone.now()
+
+ # Query windows for each granularity
+ # - Hourly: Last 24 hours (rolling window, matches retention of 30 days)
+ # - Daily: Last 7 days (ensures we capture late-arriving data)
+ # - Monthly: Last 2 months (current + previous, ensures month transitions are captured)
+ hourly_start = end_date - timedelta(hours=24)
+ daily_start = end_date - timedelta(days=7)
+ # Include previous month to handle month boundaries
+ if end_date.month == 1:
+ monthly_start = end_date.replace(
+ year=end_date.year - 1,
+ month=12,
+ day=1,
+ hour=0,
+ minute=0,
+ second=0,
+ microsecond=0,
+ )
+ else:
+ monthly_start = end_date.replace(
+ month=end_date.month - 1, day=1, hour=0, minute=0, second=0, microsecond=0
+ )
+
+ # Metric definitions: (name, query_method, is_histogram)
+ metric_configs = [
+ ("documents_processed", MetricsQueryService.get_documents_processed, False),
+ ("pages_processed", MetricsQueryService.get_pages_processed, True),
+ ("llm_calls", MetricsQueryService.get_llm_calls, False),
+ ("challenges", MetricsQueryService.get_challenges, False),
+ ("summarization_calls", MetricsQueryService.get_summarization_calls, False),
+ ("deployed_api_requests", MetricsQueryService.get_deployed_api_requests, False),
+ (
+ "etl_pipeline_executions",
+ MetricsQueryService.get_etl_pipeline_executions,
+ False,
+ ),
+ ("llm_usage", MetricsQueryService.get_llm_usage_cost, True),
+ ("prompt_executions", MetricsQueryService.get_prompt_executions, False),
+ ("failed_pages", MetricsQueryService.get_failed_pages, True),
+ ("hitl_reviews", MetricsQueryService.get_hitl_reviews, False),
+ ("hitl_completions", MetricsQueryService.get_hitl_completions, False),
+ ]
+
+ stats = {
+ "hourly": {"upserted": 0},
+ "daily": {"upserted": 0},
+ "monthly": {"upserted": 0},
+ "errors": 0,
+ "orgs_processed": 0,
+ }
+
+ # Pre-filter to orgs with recent activity to reduce DB load.
+ # One lightweight query avoids running 36 queries per dormant org.
+ active_org_ids = set(
+ WorkflowExecution.objects.filter(
+ created_at__gte=monthly_start,
+ )
+ .values_list("workflow__organization_id", flat=True)
+ .distinct()
+ )
+ total_orgs = Organization.objects.count()
+ logger.info(
+ "Aggregation: %d active orgs out of %d total",
+ len(active_org_ids),
+ total_orgs,
+ )
+
+ if not active_org_ids:
+ return {
+ "success": True,
+ "organizations_processed": 0,
+ "hourly": stats["hourly"],
+ "daily": stats["daily"],
+ "monthly": stats["monthly"],
+ "errors": 0,
+ "skipped_reason": "no_active_orgs",
+ }
+
+ organizations = Organization.objects.filter(id__in=active_org_ids).only("id")
+
+ for org in organizations:
+ org_id = str(org.id)
+ hourly_agg: dict[tuple, dict] = {}
+ daily_agg: dict[tuple, dict] = {}
+ monthly_agg: dict[tuple, dict] = {}
+
+ try:
+ for metric_name, query_method, is_histogram in metric_configs:
+ metric_type = MetricType.HISTOGRAM if is_histogram else MetricType.COUNTER
+
+ try:
+ # === HOURLY AGGREGATION (last 24 hours) ===
+ hourly_results = query_method(
+ org_id, hourly_start, end_date, granularity=Granularity.HOUR
+ )
+ for row in hourly_results:
+ period = row["period"]
+ value = row["value"] or 0
+ hour_ts = _truncate_to_hour(period)
+ key = (org_id, hour_ts.isoformat(), metric_name, "default", "")
+
+ if key not in hourly_agg:
+ hourly_agg[key] = {
+ "metric_type": metric_type,
+ "value": 0,
+ "count": 0,
+ }
+ hourly_agg[key]["value"] += value
+ hourly_agg[key]["count"] += 1
+
+ # === DAILY AGGREGATION (last 7 days) ===
+ daily_results = query_method(
+ org_id, daily_start, end_date, granularity=Granularity.DAY
+ )
+ for row in daily_results:
+ period = row["period"]
+ value = row["value"] or 0
+ day_ts = _truncate_to_day(period)
+ key = (
+ org_id,
+ day_ts.date().isoformat(),
+ metric_name,
+ "default",
+ "",
+ )
+
+ if key not in daily_agg:
+ daily_agg[key] = {
+ "metric_type": metric_type,
+ "value": 0,
+ "count": 0,
+ }
+ daily_agg[key]["value"] += value
+ daily_agg[key]["count"] += 1
+
+ # === MONTHLY AGGREGATION (last 2 months) ===
+ monthly_results = query_method(
+ org_id, monthly_start, end_date, granularity=Granularity.DAY
+ )
+ # Group results by month and create separate records
+ monthly_buckets: dict[str, dict] = {}
+ for row in monthly_results:
+ period = row["period"]
+ value = row["value"] or 0
+ month_ts = _truncate_to_month(period)
+ month_key_str = month_ts.date().isoformat()
+
+ if month_key_str not in monthly_buckets:
+ monthly_buckets[month_key_str] = {"value": 0, "count": 0}
+ monthly_buckets[month_key_str]["value"] += value
+ monthly_buckets[month_key_str]["count"] += 1
+
+ # Create aggregation entries for each month
+ for month_key_str, bucket in monthly_buckets.items():
+ month_key = (
+ org_id,
+ month_key_str,
+ metric_name,
+ "default",
+ "",
+ )
+ monthly_agg[month_key] = {
+ "metric_type": metric_type,
+ "value": bucket["value"],
+ "count": bucket["count"] or 1,
+ }
+
+ except Exception:
+ logger.exception("Error querying %s for org %s", metric_name, org_id)
+ stats["errors"] += 1
+
+ # Bulk upsert all three tiers (single INSERT...ON CONFLICT each)
+ if hourly_agg:
+ stats["hourly"]["upserted"] += _bulk_upsert_hourly(hourly_agg)
+
+ if daily_agg:
+ stats["daily"]["upserted"] += _bulk_upsert_daily(daily_agg)
+
+ if monthly_agg:
+ stats["monthly"]["upserted"] += _bulk_upsert_monthly(monthly_agg)
+
+ stats["orgs_processed"] += 1
+
+ except Exception as e:
+ logger.exception(f"Error processing org {org_id}: {e}")
+ stats["errors"] += 1
+
+ logger.info(
+ f"Aggregation completed: {stats['orgs_processed']} orgs, "
+ f"hourly={stats['hourly']['upserted']}, "
+ f"daily={stats['daily']['upserted']}, "
+ f"monthly={stats['monthly']['upserted']}, "
+ f"errors={stats['errors']}"
+ )
+
+ return {
+ "success": True,
+ "organizations_processed": stats["orgs_processed"],
+ "hourly": stats["hourly"],
+ "daily": stats["daily"],
+ "monthly": stats["monthly"],
+ "errors": stats["errors"],
+ "period": {
+ "hourly": {"start": hourly_start.isoformat(), "end": end_date.isoformat()},
+ "daily": {"start": daily_start.isoformat(), "end": end_date.isoformat()},
+ "monthly": {"start": monthly_start.isoformat(), "end": end_date.isoformat()},
+ },
+ }
+
+
+@shared_task(
+ name="dashboard_metrics.cleanup_hourly_data",
+ max_retries=3,
+ autoretry_for=(DatabaseError, OperationalError),
+ retry_backoff=True,
+ retry_backoff_max=300,
+)
+def cleanup_hourly_metrics(
+ retention_days: int = DASHBOARD_HOURLY_METRICS_RETENTION_DAYS,
+) -> dict[str, Any]:
+ """Remove hourly metrics older than retention period.
+
+ Args:
+ retention_days: Number of days to retain hourly data (default: 30)
+
+ Returns:
+ Dict with deletion summary
+ """
+ cutoff = timezone.now() - timedelta(days=retention_days)
+
+ try:
+ # Use _base_manager to bypass DefaultOrganizationManagerMixin
+ # (UserContext is None in Celery tasks)
+ deleted_count, _ = EventMetricsHourly._base_manager.filter(
+ timestamp__lt=cutoff
+ ).delete()
+
+ logger.info(
+ f"Cleanup completed: deleted {deleted_count} hourly records "
+ f"older than {retention_days} days"
+ )
+
+ return {
+ "success": True,
+ "deleted": deleted_count,
+ "cutoff_date": cutoff.isoformat(),
+ "retention_days": retention_days,
+ }
+
+ except Exception as e:
+ logger.exception("Error during hourly cleanup")
+ return {
+ "success": False,
+ "error": str(e),
+ "retention_days": retention_days,
+ }
+
+
+@shared_task(
+ name="dashboard_metrics.cleanup_daily_data",
+ max_retries=3,
+ autoretry_for=(DatabaseError, OperationalError),
+ retry_backoff=True,
+ retry_backoff_max=300,
+)
+def cleanup_daily_metrics(
+ retention_days: int = DASHBOARD_DAILY_METRICS_RETENTION_DAYS,
+) -> dict[str, Any]:
+ """Remove daily metrics older than retention period.
+
+ Args:
+ retention_days: Number of days to retain daily data (default: 365)
+
+ Returns:
+ Dict with deletion summary
+ """
+ cutoff = (timezone.now() - timedelta(days=retention_days)).date()
+
+ try:
+ # Use _base_manager to bypass DefaultOrganizationManagerMixin
+ # (UserContext is None in Celery tasks)
+ deleted_count, _ = EventMetricsDaily._base_manager.filter(
+ date__lt=cutoff
+ ).delete()
+
+ logger.info(
+ f"Cleanup completed: deleted {deleted_count} daily records "
+ f"older than {retention_days} days"
+ )
+
+ return {
+ "success": True,
+ "deleted": deleted_count,
+ "cutoff_date": cutoff.isoformat(),
+ "retention_days": retention_days,
+ }
+
+ except Exception as e:
+ logger.exception("Error during daily cleanup")
+ return {
+ "success": False,
+ "error": str(e),
+ "retention_days": retention_days,
+ }
diff --git a/backend/dashboard_metrics/tests/__init__.py b/backend/dashboard_metrics/tests/__init__.py
new file mode 100644
index 000000000..2ff28605b
--- /dev/null
+++ b/backend/dashboard_metrics/tests/__init__.py
@@ -0,0 +1 @@
+"""Dashboard metrics tests."""
diff --git a/backend/dashboard_metrics/tests/test_tasks.py b/backend/dashboard_metrics/tests/test_tasks.py
new file mode 100644
index 000000000..2a9f25fd9
--- /dev/null
+++ b/backend/dashboard_metrics/tests/test_tasks.py
@@ -0,0 +1,200 @@
+"""Unit tests for Dashboard Metrics Celery tasks."""
+
+import uuid
+from datetime import timedelta
+
+from django.test import TestCase, TransactionTestCase
+from django.utils import timezone
+
+from dashboard_metrics.models import (
+ EventMetricsDaily,
+ EventMetricsHourly,
+ MetricType,
+)
+from dashboard_metrics.tasks import (
+ _truncate_to_day,
+ _truncate_to_hour,
+ _truncate_to_month,
+ cleanup_daily_metrics,
+ cleanup_hourly_metrics,
+)
+
+
+class TestTimeHelpers(TestCase):
+ """Tests for time truncation helper functions."""
+
+ def test_truncate_to_hour_from_timestamp(self):
+ """Test truncating a Unix timestamp to the hour."""
+ # 2024-01-15 14:35:22 UTC
+ timestamp = 1705329322.0
+ result = _truncate_to_hour(timestamp)
+
+ assert result.hour == 14
+ assert result.minute == 0
+ assert result.second == 0
+ assert result.microsecond == 0
+ assert result.tzinfo == timezone.utc
+
+ def test_truncate_to_hour_from_datetime(self):
+ """Test truncating a datetime to the hour."""
+ from datetime import datetime
+
+ dt = datetime(2024, 1, 15, 14, 35, 22, tzinfo=timezone.utc)
+ result = _truncate_to_hour(dt)
+
+ assert result.hour == 14
+ assert result.minute == 0
+ assert result.second == 0
+ assert result.microsecond == 0
+
+ def test_truncate_to_hour_naive_datetime(self):
+ """Test truncating a naive datetime makes it aware."""
+ from datetime import datetime
+
+ dt = datetime(2024, 1, 15, 14, 35, 22)
+ result = _truncate_to_hour(dt)
+
+ assert result.tzinfo is not None
+ assert result.hour == 14
+ assert result.minute == 0
+
+ def test_truncate_to_day(self):
+ """Test truncating a datetime to midnight."""
+ from datetime import datetime
+
+ dt = datetime(2024, 1, 15, 14, 35, 22, tzinfo=timezone.utc)
+ result = _truncate_to_day(dt)
+
+ assert result.day == 15
+ assert result.hour == 0
+ assert result.minute == 0
+ assert result.second == 0
+ assert result.microsecond == 0
+
+ def test_truncate_to_month(self):
+ """Test truncating a datetime to first day of month."""
+ from datetime import datetime
+
+ dt = datetime(2024, 1, 15, 14, 35, 22, tzinfo=timezone.utc)
+ result = _truncate_to_month(dt)
+
+ assert result.day == 1
+ assert result.hour == 0
+ assert result.minute == 0
+ assert result.second == 0
+ assert result.microsecond == 0
+
+
+class TestCleanupTasks(TransactionTestCase):
+ """Tests for cleanup tasks."""
+
+ def setUp(self):
+ """Set up test fixtures."""
+ self.org_id = str(uuid.uuid4())
+
+ def test_cleanup_hourly_metrics_deletes_old_records(self):
+ """Test that cleanup deletes hourly records older than retention."""
+ now = timezone.now()
+ old_timestamp = now - timedelta(days=35) # Older than 30 days
+ recent_timestamp = now - timedelta(days=5) # Within retention
+
+ # Create old record
+ EventMetricsHourly.objects.create(
+ organization_id=self.org_id,
+ timestamp=old_timestamp,
+ metric_name="old_metric",
+ metric_type=MetricType.COUNTER,
+ metric_value=10,
+ metric_count=1,
+ project="default",
+ )
+
+ # Create recent record
+ EventMetricsHourly.objects.create(
+ organization_id=self.org_id,
+ timestamp=recent_timestamp,
+ metric_name="recent_metric",
+ metric_type=MetricType.COUNTER,
+ metric_value=20,
+ metric_count=1,
+ project="default",
+ )
+
+ result = cleanup_hourly_metrics(retention_days=30)
+
+ assert result["success"] is True
+ assert result["deleted"] == 1
+ assert result["retention_days"] == 30
+
+ # Verify old is deleted, recent remains
+ assert not EventMetricsHourly.objects.filter(metric_name="old_metric").exists()
+ assert EventMetricsHourly.objects.filter(metric_name="recent_metric").exists()
+
+ def test_cleanup_daily_metrics_deletes_old_records(self):
+ """Test that cleanup deletes daily records older than retention."""
+ now = timezone.now()
+ old_date = (now - timedelta(days=400)).date() # Older than 365 days
+ recent_date = (now - timedelta(days=30)).date() # Within retention
+
+ # Create old record
+ EventMetricsDaily.objects.create(
+ organization_id=self.org_id,
+ date=old_date,
+ metric_name="old_daily_metric",
+ metric_type=MetricType.COUNTER,
+ metric_value=100,
+ metric_count=10,
+ project="default",
+ )
+
+ # Create recent record
+ EventMetricsDaily.objects.create(
+ organization_id=self.org_id,
+ date=recent_date,
+ metric_name="recent_daily_metric",
+ metric_type=MetricType.COUNTER,
+ metric_value=200,
+ metric_count=20,
+ project="default",
+ )
+
+ result = cleanup_daily_metrics(retention_days=365)
+
+ assert result["success"] is True
+ assert result["deleted"] == 1
+
+ # Verify old is deleted, recent remains
+ assert not EventMetricsDaily.objects.filter(
+ metric_name="old_daily_metric"
+ ).exists()
+ assert EventMetricsDaily.objects.filter(
+ metric_name="recent_daily_metric"
+ ).exists()
+
+ def test_cleanup_hourly_with_custom_retention(self):
+ """Test cleanup with custom retention period."""
+ now = timezone.now()
+ old_timestamp = now - timedelta(days=10)
+
+ EventMetricsHourly.objects.create(
+ organization_id=self.org_id,
+ timestamp=old_timestamp,
+ metric_name="custom_retention_metric",
+ metric_type=MetricType.COUNTER,
+ metric_value=10,
+ metric_count=1,
+ project="default",
+ )
+
+ # With 7-day retention, the 10-day-old record should be deleted
+ result = cleanup_hourly_metrics(retention_days=7)
+
+ assert result["success"] is True
+ assert result["deleted"] == 1
+
+ def test_cleanup_no_records_to_delete(self):
+ """Test cleanup when there are no old records."""
+ result = cleanup_hourly_metrics(retention_days=30)
+
+ assert result["success"] is True
+ assert result["deleted"] == 0
diff --git a/backend/dashboard_metrics/urls.py b/backend/dashboard_metrics/urls.py
new file mode 100644
index 000000000..36208a6b5
--- /dev/null
+++ b/backend/dashboard_metrics/urls.py
@@ -0,0 +1,48 @@
+"""URL configuration for Dashboard Metrics API."""
+
+from django.urls import path
+from rest_framework.urlpatterns import format_suffix_patterns
+
+from .views import DashboardMetricsViewSet
+
+# ViewSet action mappings
+metrics_list = DashboardMetricsViewSet.as_view({"get": "list"})
+metrics_detail = DashboardMetricsViewSet.as_view({"get": "retrieve"})
+metrics_summary = DashboardMetricsViewSet.as_view({"get": "summary"})
+metrics_series = DashboardMetricsViewSet.as_view({"get": "series"})
+metrics_overview = DashboardMetricsViewSet.as_view({"get": "overview"})
+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_workflow_token_usage = DashboardMetricsViewSet.as_view(
+ {"get": "workflow_token_usage"}
+)
+
+urlpatterns = format_suffix_patterns(
+ [
+ # Main list endpoint
+ path("", metrics_list, name="metrics-list"),
+ # Summary statistics
+ path("summary/", metrics_summary, name="metrics-summary"),
+ # Time series data
+ path("series/", metrics_series, name="metrics-series"),
+ # Quick overview (last 7 days)
+ path("overview/", metrics_overview, name="metrics-overview"),
+ # Live data from source tables
+ path("live-summary/", metrics_live_summary, name="metrics-live-summary"),
+ path("live-series/", metrics_live_series, name="metrics-live-series"),
+ # Recent activity (real-time processing events)
+ path("recent-activity/", metrics_recent_activity, name="metrics-recent-activity"),
+ # Per-workflow LLM token usage breakdown
+ path(
+ "workflow-token-usage/",
+ metrics_workflow_token_usage,
+ name="metrics-workflow-token-usage",
+ ),
+ # Health check endpoint
+ path("health/", metrics_health, name="metrics-health"),
+ # Individual metric detail
+ path("<uuid:pk>/", metrics_detail, name="metrics-detail"),
+ ]
+)
diff --git a/backend/dashboard_metrics/views.py b/backend/dashboard_metrics/views.py
new file mode 100644
index 000000000..658f85856
--- /dev/null
+++ b/backend/dashboard_metrics/views.py
@@ -0,0 +1,950 @@
+"""API views for Dashboard Metrics."""
+
+import logging
+from collections import defaultdict
+from datetime import datetime, timedelta
+
+from django.conf import settings
+from django.core.cache import cache
+from django.db.models import Avg, Max, Min, Sum
+from django.db.models.functions import TruncDay, TruncHour, TruncWeek
+from django.utils import timezone
+from django_filters.rest_framework import DjangoFilterBackend
+from permissions.permission import IsOrganizationMember
+from rest_framework import status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import PermissionDenied
+from rest_framework.filters import OrderingFilter
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.throttling import UserRateThrottle
+from utils.user_context import UserContext
+
+from .cache import (
+ cache_metrics_response,
+ mget_metrics_buckets,
+ mset_metrics_buckets,
+)
+from .models import (
+ EventMetricsDaily,
+ EventMetricsHourly,
+ EventMetricsMonthly,
+ Granularity,
+ MetricType,
+)
+from .serializers import (
+ EventMetricsHourlySerializer,
+ MetricsQuerySerializer,
+)
+from .services import MetricsQueryService
+
+logger = logging.getLogger(__name__)
+
+# Bucket caching for better cache reuse across overlapping queries
+BUCKET_CACHE_ENABLED = settings.DASHBOARD_BUCKET_CACHE_ENABLED
+
+# Thresholds for automatic source selection (in days)
+HOURLY_MAX_DAYS = 7 # Use hourly for ≤7 days
+DAILY_MAX_DAYS = 90 # Use daily for ≤90 days, monthly for >90 days
+
+
+class MetricsRateThrottle(UserRateThrottle):
+ """Rate throttle for metrics endpoints."""
+
+ rate = "1000/hour"
+
+
+class DashboardMetricsViewSet(viewsets.ReadOnlyModelViewSet):
+ """ViewSet for dashboard metrics API.
+
+ Provides read-only access to aggregated metrics data with
+ time series and summary endpoints. Automatically selects the
+ optimal data source (hourly/daily/monthly) based on date range.
+ """
+
+ permission_classes = [IsAuthenticated, IsOrganizationMember]
+ throttle_classes = [MetricsRateThrottle]
+ serializer_class = EventMetricsHourlySerializer
+ filter_backends = [DjangoFilterBackend, OrderingFilter]
+ ordering_fields = ["timestamp", "metric_name", "metric_value"]
+ ordering = ["-timestamp"]
+
+ def get_queryset(self):
+ """Return queryset filtered by user's organization.
+
+ The model manager (DefaultOrganizationManagerMixin) automatically
+ filters by UserContext.get_organization(). We call _get_organization()
+ here only as a guard to return 403 instead of empty results when
+ there's no org context.
+ """
+ self._get_organization()
+ return EventMetricsHourly.objects.all()
+
+ def _get_organization(self):
+ """Get the current organization or raise PermissionDenied."""
+ organization = UserContext.get_organization()
+ if not organization:
+ raise PermissionDenied("No organization context")
+ return organization
+
+ def _select_source(self, params: dict) -> str:
+ """Select the optimal data source based on date range or explicit source.
+
+ Args:
+ params: Validated query parameters containing start_date, end_date, source
+
+ Returns:
+ Source name: 'hourly', 'daily', or 'monthly'
+ """
+ source = params.get("source", "auto")
+ if source != "auto":
+ return source
+
+ # Auto-select based on date range
+ days = (params["end_date"] - params["start_date"]).days
+
+ if days <= HOURLY_MAX_DAYS:
+ return "hourly"
+ elif days <= DAILY_MAX_DAYS:
+ return "daily"
+ else:
+ return "monthly"
+
+ def _get_source_queryset(self, source: str):
+ """Get the queryset for the specified source table.
+
+ Organization filtering is handled automatically by the model manager
+ (DefaultOrganizationManagerMixin).
+
+ Args:
+ source: One of 'hourly', 'daily', 'monthly'
+
+ Returns:
+ QuerySet for the appropriate table
+ """
+ if source == "daily":
+ return EventMetricsDaily.objects.all()
+ elif source == "monthly":
+ return EventMetricsMonthly.objects.all()
+ return EventMetricsHourly.objects.all()
+
+ def _get_timestamp_field(self, source: str) -> str:
+ """Get the timestamp field name for the source table."""
+ if source == "hourly":
+ return "timestamp"
+ elif source == "daily":
+ return "date"
+ elif source == "monthly":
+ return "month"
+ return "timestamp"
+
+ def _apply_source_filters(self, queryset, params: dict, source: str):
+ """Apply filters based on the source table structure."""
+ ts_field = self._get_timestamp_field(source)
+
+ queryset = queryset.filter(
+ **{
+ f"{ts_field}__gte": params["start_date"]
+ if source == "hourly"
+ else params["start_date"].date(),
+ f"{ts_field}__lte": params["end_date"]
+ if source == "hourly"
+ else params["end_date"].date(),
+ }
+ )
+
+ if params.get("metric_name"):
+ queryset = queryset.filter(metric_name=params["metric_name"])
+
+ if params.get("project"):
+ queryset = queryset.filter(project=params["project"])
+
+ if "tag" in params and params["tag"] is not None:
+ queryset = queryset.filter(tag=params["tag"])
+
+ return queryset
+
+ def _fetch_hourly_with_bucket_cache(
+ self,
+ org_id: str,
+ params: dict,
+ metric_name: str | None = None,
+ ) -> list[dict]:
+ """Fetch hourly metrics using bucket-based caching.
+
+ Splits the time range into hourly buckets, fetches from cache,
+ queries DB for missing buckets, and saves to cache.
+
+ Organization filtering is handled automatically by the model manager.
+
+ Args:
+ org_id: Organization ID string
+ params: Query parameters with start_date, end_date
+ metric_name: Optional metric name filter
+
+ Returns:
+ List of metric records from EventMetricsHourly
+ """
+ start_date = params["start_date"]
+ end_date = params["end_date"]
+
+ # Try to get from bucket cache
+ cached_data, missing_buckets = mget_metrics_buckets(
+ org_id, start_date, end_date, "hourly", metric_name
+ )
+
+ # If we have missing buckets, query them from DB in a single query
+ db_data_by_bucket = {}
+ if missing_buckets:
+ min_ts = min(missing_buckets)
+ max_ts = max(missing_buckets) + timedelta(hours=1)
+
+ qs = EventMetricsHourly.objects.filter(
+ timestamp__gte=min_ts,
+ timestamp__lt=max_ts,
+ )
+
+ if metric_name:
+ qs = qs.filter(metric_name=metric_name)
+
+ if params.get("project"):
+ qs = qs.filter(project=params["project"])
+
+ if "tag" in params and params["tag"] is not None:
+ qs = qs.filter(tag=params["tag"])
+
+ all_db_records = list(
+ qs.values(
+ "metric_name",
+ "metric_type",
+ "metric_value",
+ "metric_count",
+ "project",
+ "tag",
+ "timestamp",
+ )
+ )
+
+ # Partition records into hourly buckets in memory
+ missing_set = set(missing_buckets)
+ for record in all_db_records:
+ bucket_ts = record["timestamp"].replace(minute=0, second=0, microsecond=0)
+ if bucket_ts in missing_set:
+ db_data_by_bucket.setdefault(bucket_ts, []).append(record)
+
+ # Ensure empty buckets are also cached (prevents re-querying)
+ for bucket_ts in missing_buckets:
+ db_data_by_bucket.setdefault(bucket_ts, [])
+
+ # Save to cache
+ if db_data_by_bucket:
+ mset_metrics_buckets(org_id, db_data_by_bucket, "hourly", metric_name)
+
+ # Combine cached and fresh data
+ all_records = []
+ for bucket_ts, records in cached_data.items():
+ all_records.extend(records)
+ for bucket_ts, records in db_data_by_bucket.items():
+ all_records.extend(records)
+
+ return all_records
+
+ @action(detail=False, methods=["get"], url_path="summary")
+ def summary(self, request: Request) -> Response:
+ """Get summary statistics for all metrics.
+
+ Automatically selects the optimal data source (hourly/daily/monthly)
+ based on the date range, or use ?source= to override.
+
+ Uses bucket-based caching for hourly data to maximize cache reuse
+ across overlapping queries.
+
+ Query Parameters:
+ start_date: Start of date range (ISO 8601)
+ end_date: End of date range (ISO 8601)
+ metric_name: Filter by specific metric name
+ project: Filter by project identifier
+ source: Data source (auto, hourly, daily, monthly). Default: auto
+
+ Returns:
+ Summary statistics for each metric including totals,
+ averages, min, and max values.
+ """
+ query_serializer = MetricsQuerySerializer(data=request.query_params)
+ query_serializer.is_valid(raise_exception=True)
+ params = query_serializer.validated_data
+
+ organization = self._get_organization()
+ org_id = str(organization.id)
+ source = self._select_source(params)
+
+ # Use bucket caching for hourly source (best cache reuse)
+ if source == "hourly" and BUCKET_CACHE_ENABLED:
+ records = self._fetch_hourly_with_bucket_cache(
+ org_id, params, params.get("metric_name")
+ )
+
+ # Aggregate the records manually
+ summary_dict = defaultdict(
+ lambda: {
+ "total_value": 0,
+ "total_count": 0,
+ "values": [],
+ "metric_type": MetricType.COUNTER,
+ }
+ )
+ for record in records:
+ name = record["metric_name"]
+ value = record.get("metric_value") or 0
+ count = record.get("metric_count") or 0
+ summary_dict[name]["total_value"] += value
+ summary_dict[name]["total_count"] += count
+ summary_dict[name]["values"].append(value)
+ summary_dict[name]["metric_type"] = record.get(
+ "metric_type", MetricType.COUNTER
+ )
+
+ summary_list = []
+ for name, agg in summary_dict.items():
+ values = agg["values"]
+ summary_list.append(
+ {
+ "metric_name": name,
+ "metric_type": agg["metric_type"],
+ "total_value": agg["total_value"],
+ "total_count": agg["total_count"],
+ "average_value": agg["total_value"] / len(values)
+ if values
+ else 0,
+ "min_value": min(values) if values else 0,
+ "max_value": max(values) if values else 0,
+ }
+ )
+ summary_list.sort(key=lambda x: x["metric_name"])
+
+ else:
+ # Use standard queryset for daily/monthly (existing behavior)
+ queryset = self._get_source_queryset(source)
+ queryset = self._apply_source_filters(queryset, params, source)
+
+ # Aggregate by metric name
+ summary = (
+ queryset.values("metric_name")
+ .annotate(
+ total_value=Sum("metric_value"),
+ total_count=Sum("metric_count"),
+ average_value=Avg("metric_value"),
+ min_value=Min("metric_value"),
+ max_value=Max("metric_value"),
+ )
+ .order_by("metric_name")
+ )
+
+ # Add metric_type from the first record of each metric
+ summary_list = []
+ for row in summary:
+ metric_type_record = (
+ queryset.filter(metric_name=row["metric_name"])
+ .values("metric_type")
+ .first()
+ )
+ row["metric_type"] = (
+ metric_type_record["metric_type"]
+ if metric_type_record
+ else MetricType.COUNTER
+ )
+ summary_list.append(row)
+
+ return Response(
+ {
+ "start_date": params["start_date"].isoformat(),
+ "end_date": params["end_date"].isoformat(),
+ "source": source,
+ "summary": summary_list,
+ },
+ status=status.HTTP_200_OK,
+ )
+
+ @action(detail=False, methods=["get"], url_path="series")
+ def series(self, request: Request) -> Response:
+ """Get time series data for metrics.
+
+ Automatically selects the optimal data source (hourly/daily/monthly)
+ based on the date range, or use ?source= to override.
+
+ Uses bucket-based caching for hourly data to maximize cache reuse
+ across overlapping queries.
+
+ Query Parameters:
+ start_date: Start of date range (ISO 8601)
+ end_date: End of date range (ISO 8601)
+ granularity: Time granularity (hour, day, week)
+ metric_name: Filter by specific metric name
+ project: Filter by project identifier
+ source: Data source (auto, hourly, daily, monthly). Default: auto
+
+ Returns:
+ Time series data grouped by the specified granularity.
+ """
+ query_serializer = MetricsQuerySerializer(data=request.query_params)
+ query_serializer.is_valid(raise_exception=True)
+ params = query_serializer.validated_data
+
+ organization = self._get_organization()
+ org_id = str(organization.id)
+ source = self._select_source(params)
+ granularity = params.get("granularity", Granularity.DAY)
+
+ # Use bucket caching for hourly source (best cache reuse)
+ if source == "hourly" and BUCKET_CACHE_ENABLED:
+ records = self._fetch_hourly_with_bucket_cache(
+ org_id, params, params.get("metric_name")
+ )
+
+ # Apply granularity-based grouping to cached records
+ from datetime import datetime
+
+ trunc_funcs = {
+ Granularity.HOUR: lambda ts: ts.replace(
+ minute=0, second=0, microsecond=0
+ ),
+ Granularity.DAY: lambda ts: ts.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ),
+ Granularity.WEEK: lambda ts: (ts - timedelta(days=ts.weekday())).replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ),
+ }
+ trunc_fn = trunc_funcs.get(granularity, trunc_funcs[Granularity.DAY])
+
+ # Group records by (period, metric_name, project, tag)
+ grouped = defaultdict(
+ lambda: {"value": 0, "count": 0, "metric_type": MetricType.COUNTER}
+ )
+ for record in records:
+ ts = record.get("timestamp")
+ if isinstance(ts, str):
+ ts = datetime.fromisoformat(ts.replace("Z", "+00:00"))
+ period = trunc_fn(ts)
+ key = (
+ period,
+ record["metric_name"],
+ record.get("project", ""),
+ record.get("tag"),
+ )
+ grouped[key]["value"] += record.get("metric_value") or 0
+ grouped[key]["count"] += record.get("metric_count") or 0
+ grouped[key]["metric_type"] = record.get(
+ "metric_type", MetricType.COUNTER
+ )
+
+ # Convert to series_data format
+ series_data = [
+ {
+ "period": key[0],
+ "metric_name": key[1],
+ "project": key[2],
+ "tag": key[3],
+ "value": data["value"],
+ "count": data["count"],
+ "metric_type": data["metric_type"],
+ }
+ for key, data in grouped.items()
+ ]
+ series_data.sort(key=lambda x: (x["period"], x["metric_name"]))
+
+ else:
+ # Use standard queryset for daily/monthly (existing behavior)
+ queryset = self._get_source_queryset(source)
+ queryset = self._apply_source_filters(queryset, params, source)
+ ts_field = self._get_timestamp_field(source)
+
+ # For daily/monthly tables, data is already at that granularity
+ # For hourly, we can truncate to day/week if requested
+ if source == "hourly":
+ trunc_func = {
+ "hour": TruncHour,
+ "day": TruncDay,
+ "week": TruncWeek,
+ }.get(granularity, TruncDay)
+ series_data = (
+ queryset.annotate(period=trunc_func(ts_field))
+ .values("period", "metric_name", "metric_type", "project", "tag")
+ .annotate(
+ value=Sum("metric_value"),
+ count=Sum("metric_count"),
+ )
+ .order_by("period", "metric_name")
+ )
+ elif source == "daily":
+ # Daily data - use date directly or truncate to week
+ if granularity == Granularity.WEEK:
+ series_data = (
+ queryset.annotate(period=TruncWeek(ts_field))
+ .values("period", "metric_name", "metric_type", "project", "tag")
+ .annotate(
+ value=Sum("metric_value"),
+ count=Sum("metric_count"),
+ )
+ .order_by("period", "metric_name")
+ )
+ else:
+ # Return daily data as-is
+ series_data = (
+ queryset.values(
+ "metric_name",
+ "metric_type",
+ "project",
+ "tag",
+ "metric_value",
+ "metric_count",
+ )
+ .annotate(period=TruncDay(ts_field))
+ .order_by("period", "metric_name")
+ )
+ series_data = [
+ {
+ "period": row["period"],
+ "metric_name": row["metric_name"],
+ "metric_type": row["metric_type"],
+ "project": row["project"],
+ "tag": row["tag"],
+ "value": row["metric_value"],
+ "count": row["metric_count"],
+ }
+ for row in series_data
+ ]
+ else: # monthly
+ # Monthly data - return as-is
+ series_data = (
+ queryset.values(
+ "metric_name",
+ "metric_type",
+ "project",
+ "tag",
+ "metric_value",
+ "metric_count",
+ )
+ .annotate(period=TruncDay(ts_field))
+ .order_by("period", "metric_name")
+ )
+ series_data = [
+ {
+ "period": row["period"],
+ "metric_name": row["metric_name"],
+ "metric_type": row["metric_type"],
+ "project": row["project"],
+ "tag": row["tag"],
+ "value": row["metric_value"],
+ "count": row["metric_count"],
+ }
+ for row in series_data
+ ]
+
+ # Group by metric
+ series_by_metric = defaultdict(
+ lambda: {
+ "metric_name": "",
+ "metric_type": "",
+ "project": "",
+ "tag": None,
+ "data": [],
+ "total_value": 0,
+ "total_count": 0,
+ }
+ )
+
+ for row in series_data:
+ key = (row["metric_name"], row["project"], row["tag"])
+ series = series_by_metric[key]
+ series["metric_name"] = row["metric_name"]
+ series["metric_type"] = row["metric_type"]
+ series["project"] = row["project"]
+ series["tag"] = row["tag"]
+ period = row["period"]
+ series["data"].append(
+ {
+ "timestamp": period.isoformat()
+ if hasattr(period, "isoformat")
+ else str(period),
+ "value": row["value"],
+ "count": row["count"],
+ }
+ )
+ series["total_value"] += row["value"] or 0
+ series["total_count"] += row["count"] or 0
+
+ return Response(
+ {
+ "start_date": params["start_date"].isoformat(),
+ "end_date": params["end_date"].isoformat(),
+ "granularity": granularity,
+ "source": source,
+ "series": list(series_by_metric.values()),
+ },
+ status=status.HTTP_200_OK,
+ )
+
+ @action(detail=False, methods=["get"], url_path="overview")
+ @cache_metrics_response(endpoint="overview")
+ def overview(self, request: Request) -> Response:
+ """Get a quick overview of recent metrics.
+
+ Query Parameters:
+ start_date: Start of date range (ISO 8601, optional)
+ end_date: End of date range (ISO 8601, optional)
+
+ If dates are not provided, defaults to last 7 days.
+ """
+ # Parse optional date parameters (default to last 7 days)
+ end_date_str = request.query_params.get("end_date")
+ start_date_str = request.query_params.get("start_date")
+
+ if end_date_str:
+ try:
+ end_date = datetime.fromisoformat(end_date_str.replace("Z", "+00:00"))
+ if timezone.is_naive(end_date):
+ end_date = timezone.make_aware(end_date)
+ except ValueError:
+ end_date = timezone.now()
+ else:
+ end_date = timezone.now()
+
+ if start_date_str:
+ try:
+ start_date = datetime.fromisoformat(start_date_str.replace("Z", "+00:00"))
+ if timezone.is_naive(start_date):
+ start_date = timezone.make_aware(start_date)
+ except ValueError:
+ start_date = end_date - timedelta(days=7)
+ else:
+ start_date = end_date - timedelta(days=7)
+
+ # Calculate days in range for response
+ days = (end_date - start_date).days
+
+ # Auto-select source based on date range
+ source = self._select_source({"start_date": start_date, "end_date": end_date})
+ ts_field = self._get_timestamp_field(source)
+ queryset = self._get_source_queryset(source).filter(
+ **{
+ f"{ts_field}__gte": start_date
+ if source == "hourly"
+ else start_date.date(),
+ f"{ts_field}__lte": end_date if source == "hourly" else end_date.date(),
+ }
+ )
+
+ # Get totals per metric
+ totals = (
+ queryset.values("metric_name")
+ .annotate(
+ total_value=Sum("metric_value"),
+ total_count=Sum("metric_count"),
+ )
+ .order_by("metric_name")
+ )
+
+ # Get daily trend per metric for the period
+ trunc_func = TruncDay(ts_field)
+ daily_trend_query = (
+ queryset.annotate(day=trunc_func)
+ .values("day", "metric_name")
+ .annotate(
+ total_value=Sum("metric_value"),
+ total_count=Sum("metric_count"),
+ )
+ .order_by("day", "metric_name")
+ )
+
+ # Restructure to nested format: {date: {metrics: {name: value}}}
+ daily_trend_map = {}
+ for row in daily_trend_query:
+ date_str = row["day"].isoformat()
+ if date_str not in daily_trend_map:
+ daily_trend_map[date_str] = {"date": date_str, "metrics": {}}
+ daily_trend_map[date_str]["metrics"][row["metric_name"]] = row["total_value"]
+
+ # Sort by date
+ daily_trend = sorted(daily_trend_map.values(), key=lambda x: x["date"])
+
+ return Response(
+ {
+ "period": {
+ "start_date": start_date.isoformat(),
+ "end_date": end_date.isoformat(),
+ "days": days,
+ },
+ "totals": list(totals),
+ "daily_trend": daily_trend,
+ },
+ status=status.HTTP_200_OK,
+ )
+
+ @action(detail=False, methods=["get"], url_path="live-summary")
+ @cache_metrics_response(endpoint="live_summary")
+ def live_summary(self, request: Request) -> Response:
+ """Get summary from existing source tables (live data).
+
+ This endpoint queries metrics directly from source tables
+ (usage, page_usage, workflow_execution, etc.) instead of
+ the aggregated event_metrics_hourly table.
+
+ Query Parameters:
+ start_date: Start of date range (ISO 8601)
+ end_date: End of date range (ISO 8601)
+
+ Returns:
+ Summary totals for all 9 metrics from live data.
+ """
+ query_serializer = MetricsQuerySerializer(data=request.query_params)
+ query_serializer.is_valid(raise_exception=True)
+ params = query_serializer.validated_data
+
+ organization = self._get_organization()
+ org_id = str(organization.id)
+
+ summary = MetricsQueryService.get_all_metrics_summary(
+ org_id,
+ params["start_date"],
+ params["end_date"],
+ )
+
+ # Format response to match /summary/ endpoint format for frontend compatibility
+ # MetricsTable expects: summary[] with metric_name, metric_type, total_value, etc.
+ summary_list = [
+ {
+ "metric_name": name,
+ "metric_type": MetricType.HISTOGRAM
+ if name == "llm_usage"
+ else MetricType.COUNTER,
+ "total_value": value,
+ "total_count": 1, # Not available from live queries
+ "average_value": value, # Same as total for live data
+ "min_value": value,
+ "max_value": value,
+ }
+ for name, value in summary.items()
+ ]
+
+ return Response(
+ {
+ "start_date": params["start_date"].isoformat(),
+ "end_date": params["end_date"].isoformat(),
+ "source": "live",
+ "summary": summary_list, # Changed from "metrics" to "summary"
+ },
+ status=status.HTTP_200_OK,
+ )
+
+ @action(detail=False, methods=["get"], url_path="live-series")
+ @cache_metrics_response(endpoint="live_series")
+ def live_series(self, request: Request) -> Response:
+ """Get time series from existing source tables (live data).
+
+ This endpoint queries metrics directly from source tables
+ with time-based aggregation (hourly, daily, weekly).
+
+ Query Parameters:
+ start_date: Start of date range (ISO 8601)
+ end_date: End of date range (ISO 8601)
+ granularity: Time granularity (hour, day, week)
+ metric_name: Filter by specific metric name (optional)
+
+ Returns:
+ Time series data for all metrics grouped by granularity.
+ """
+ query_serializer = MetricsQuerySerializer(data=request.query_params)
+ query_serializer.is_valid(raise_exception=True)
+ params = query_serializer.validated_data
+
+ organization = self._get_organization()
+ org_id = str(organization.id)
+ granularity = params.get("granularity", Granularity.DAY)
+
+ # Define metric query mapping
+ metric_queries = {
+ "documents_processed": MetricsQueryService.get_documents_processed,
+ "pages_processed": MetricsQueryService.get_pages_processed,
+ "llm_calls": MetricsQueryService.get_llm_calls,
+ "challenges": MetricsQueryService.get_challenges,
+ "summarization_calls": MetricsQueryService.get_summarization_calls,
+ "deployed_api_requests": MetricsQueryService.get_deployed_api_requests,
+ "etl_pipeline_executions": MetricsQueryService.get_etl_pipeline_executions,
+ "llm_usage": MetricsQueryService.get_llm_usage_cost,
+ "prompt_executions": MetricsQueryService.get_prompt_executions,
+ }
+
+ # Filter by specific metric if requested
+ if params.get("metric_name"):
+ metric_queries = {
+ k: v for k, v in metric_queries.items() if k == params["metric_name"]
+ }
+
+ series = []
+ errors = []
+ for metric_name, query_fn in metric_queries.items():
+ try:
+ data = query_fn(
+ org_id,
+ params["start_date"],
+ params["end_date"],
+ granularity,
+ )
+ series.append(
+ {
+ "metric_name": metric_name,
+ "metric_type": MetricType.HISTOGRAM
+ if metric_name == "llm_usage"
+ else MetricType.COUNTER,
+ "data": [
+ {
+ "timestamp": r["period"].isoformat(),
+ "value": r["value"] or 0,
+ }
+ for r in data
+ ],
+ "total_value": sum(r["value"] or 0 for r in data),
+ }
+ )
+ except Exception:
+ logger.exception("Failed to fetch metric %s", metric_name)
+ errors.append(metric_name)
+ series.append(
+ {
+ "metric_name": metric_name,
+ "error": "unavailable",
+ "data": [],
+ "total_value": 0,
+ }
+ )
+
+ response_data = {
+ "start_date": params["start_date"].isoformat(),
+ "end_date": params["end_date"].isoformat(),
+ "granularity": granularity,
+ "source": "live",
+ "series": series,
+ }
+
+ if errors:
+ response_data["partial_errors"] = errors
+
+ return Response(response_data, status=status.HTTP_200_OK)
+
+ @action(detail=False, methods=["get"], url_path="recent-activity")
+ @cache_metrics_response(endpoint="recent_activity")
+ def recent_activity(self, request: Request) -> Response:
+ """Get recent processing activity differentiated by type.
+
+ Returns recent file executions with type classification:
+ - etl: ETL pipeline executions
+ - api: API deployment requests
+ - workflow: Manual workflow/prompt studio executions
+
+ Query Parameters:
+ limit: Maximum records to return (default 10, max 50)
+
+ Returns:
+ 200: List of recent activity items
+ 500: Error occurred
+ """
+ organization = self._get_organization()
+ org_id = str(organization.id)
+ try:
+ limit = min(int(request.query_params.get("limit", 10)), 50)
+ except (ValueError, TypeError):
+ limit = 10
+
+ data = MetricsQueryService.get_recent_activity(org_id, limit)
+ return Response({"activity": data})
+
+ @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:
+ """Get per-workflow LLM token usage breakdown.
+
+ Returns token usage and cost aggregated per workflow for the
+ given date range. Cached for 1 hour; pass ?refresh=true to
+ bypass cache.
+
+ Query Parameters:
+ start_date: Start of date range (ISO 8601)
+ end_date: End of date range (ISO 8601)
+ refresh: If "true", bypass cache and fetch fresh data
+
+ Returns:
+ 200: List of workflows with token usage
+ 500: Error occurred
+ """
+ query_serializer = MetricsQuerySerializer(data=request.query_params)
+ query_serializer.is_valid(raise_exception=True)
+ params = query_serializer.validated_data
+
+ organization = self._get_organization()
+ org_id = str(organization.id)
+
+ data = MetricsQueryService.get_workflow_token_usage(
+ org_id,
+ params["start_date"],
+ params["end_date"],
+ )
+ return Response(
+ {
+ "start_date": params["start_date"].isoformat(),
+ "end_date": params["end_date"].isoformat(),
+ "workflows": data,
+ }
+ )
+
+ @action(detail=False, methods=["get"], url_path="health")
+ def health(self, request: Request) -> Response:
+ """Health check endpoint for metrics system.
+
+ Returns status of database and cache connectivity.
+ Useful for liveness/readiness probes.
+
+ Returns:
+ 200: All systems healthy
+ 503: One or more systems unhealthy
+ """
+ checks = {
+ "database": self._check_database(),
+ "cache": self._check_cache(),
+ }
+
+ healthy = all(check.get("status") == "ok" for check in checks.values())
+ http_status = (
+ status.HTTP_200_OK if healthy else status.HTTP_503_SERVICE_UNAVAILABLE
+ )
+
+ return Response(
+ {
+ "healthy": healthy,
+ "checks": checks,
+ "timestamp": timezone.now().isoformat(),
+ },
+ status=http_status,
+ )
+
+ def _check_database(self) -> dict:
+ """Check database connectivity."""
+ try:
+ EventMetricsHourly.objects.exists()
+ return {"status": "ok"}
+ except Exception as e:
+ logger.exception("Database health check failed")
+ return {"status": "error", "message": str(e)}
+
+ def _check_cache(self) -> dict:
+ """Check cache connectivity."""
+ try:
+ cache.set("metrics_health_check", "ok", 10)
+ result = cache.get("metrics_health_check")
+ if result == "ok":
+ return {"status": "ok"}
+ return {"status": "error", "message": "Cache read/write mismatch"}
+ except Exception as e:
+ logger.exception("Cache health check failed")
+ return {"status": "error", "message": str(e)}
diff --git a/backend/pyproject.toml b/backend/pyproject.toml
index 6a2363893..c779aee36 100644
--- a/backend/pyproject.toml
+++ b/backend/pyproject.toml
@@ -141,6 +141,10 @@ help = "Runs the Unstract file processing callback worker"
cmd = "celery -A backend.workers.file_processing_callback worker --loglevel=info -Q api_file_processing_callback --autoscale 4,1"
help = "Runs the Unstract api file processing callback worker"
+[tool.poe.tasks.worker-metrics]
+cmd = "celery -A backend worker --loglevel=info -Q dashboard_metric_events --autoscale 4,1"
+help = "Runs the Unstract dashboard metrics worker"
+
[tool.poe.tasks.flower]
cmd = "celery -A backend flower --port=5555"
help = "Runs the Unstract Celery Monitoring Tool"
diff --git a/backend/sample.env b/backend/sample.env
index 55bd3fe8f..909f02e1f 100644
--- a/backend/sample.env
+++ b/backend/sample.env
@@ -236,6 +236,14 @@ RUNNER_POLLING_INTERVAL_SECONDS=2
# Examples: 900 (15 min), 1800 (30 min), 3600 (60 min)
MIN_SCHEDULE_INTERVAL_SECONDS=1800
+# Dashboard Metrics Cache TTLs (in seconds)
+DASHBOARD_CACHE_TTL_CURRENT_BUCKET=60
+DASHBOARD_CACHE_TTL_HISTORICAL=28800
+DASHBOARD_CACHE_TTL_OVERVIEW=300
+DASHBOARD_CACHE_TTL_SUMMARY=900
+DASHBOARD_CACHE_TTL_SERIES=1800
+DASHBOARD_CACHE_TTL_WORKFLOW_USAGE=3600
+
# HITL Files Storage Configuration
HITL_FILES_FILE_STORAGE_CREDENTIALS='{"provider": "minio", "credentials": {"endpoint_url": "http://unstract-minio:9000", "key": "minio", "secret": "minio123"}}'
diff --git a/docker/docker-compose.yaml b/docker/docker-compose.yaml
index 24b00f0c6..09f100d19 100644
--- a/docker/docker-compose.yaml
+++ b/docker/docker-compose.yaml
@@ -118,6 +118,25 @@ services:
- ./workflow_data:/data
- ${TOOL_REGISTRY_CONFIG_SRC_PATH}:/data/tool_registry_config
+ # Celery worker for dashboard metrics processing
+ worker-metrics:
+ image: unstract/backend:${VERSION}
+ container_name: unstract-worker-metrics
+ restart: unless-stopped
+ entrypoint: .venv/bin/celery
+ command: "-A backend worker --loglevel=info -Q dashboard_metric_events --autoscale=${WORKER_METRICS_AUTOSCALE:-4,1}"
+ env_file:
+ - ../backend/.env
+ depends_on:
+ - rabbitmq
+ - db
+ environment:
+ - ENVIRONMENT=development
+ - APPLICATION_NAME=unstract-worker-metrics
+
+ labels:
+ - traefik.enable=false
+
# Celery Flower
celery-flower:
image: unstract/backend:${VERSION}
diff --git a/frontend/package.json b/frontend/package.json
index 280d109c7..931999929 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -51,6 +51,7 @@
"react-router-dom": "^6.11.2",
"react-social-login-buttons": "^3.9.1",
"react-syntax-highlighter": "^15.6.1",
+
"recharts": "^3.5.1",
"remark-gfm": "^3.0.1",
"socket.io-client": "^4.7.2",
diff --git a/frontend/src/assets/dashboard.svg b/frontend/src/assets/dashboard.svg
new file mode 100644
index 000000000..fdb5f1698
--- /dev/null
+++ b/frontend/src/assets/dashboard.svg
@@ -0,0 +1,5 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <rect x="3" y="13" width="4" height="8" rx="1" fill="#90A4B7" opacity="0.6"/>
+ <rect x="10" y="9" width="4" height="12" rx="1" fill="#90A4B7" opacity="0.8"/>
+ <rect x="17" y="3" width="4" height="18" rx="1" fill="#90A4B7"/>
+</svg>
diff --git a/frontend/src/components/metrics-dashboard/LLMUsageTable.jsx b/frontend/src/components/metrics-dashboard/LLMUsageTable.jsx
new file mode 100644
index 000000000..997123c67
--- /dev/null
+++ b/frontend/src/components/metrics-dashboard/LLMUsageTable.jsx
@@ -0,0 +1,136 @@
+import { InfoCircleOutlined, ReloadOutlined } from "@ant-design/icons";
+import { Button, Card, Empty, Spin, Table, Tooltip, Typography } from "antd";
+import PropTypes from "prop-types";
+
+import "./MetricsDashboard.css";
+
+const { Text } = Typography;
+
+const columns = [
+ {
+ title: "Workflow",
+ dataIndex: "workflow_name",
+ key: "workflow_name",
+ ellipsis: true,
+ render: (text) => <Text strong>{text}</Text>,
+ },
+ {
+ title: (
+ <span>
+ Tokens{" "}
+ <Tooltip title="Total LLM tokens consumed by this workflow">
+ <InfoCircleOutlined style={{ color: "#8c8c8c", fontSize: 12 }} />
+ </Tooltip>
+ </span>
+ ),
+ dataIndex: "total_tokens",
+ key: "total_tokens",
+ sorter: (a, b) => a.total_tokens - b.total_tokens,
+ defaultSortOrder: "descend",
+ render: (value) => (value || 0).toLocaleString(),
+ width: 140,
+ },
+ {
+ title: "LLM Calls",
+ dataIndex: "call_count",
+ key: "call_count",
+ sorter: (a, b) => a.call_count - b.call_count,
+ render: (value) => (value || 0).toLocaleString(),
+ width: 120,
+ },
+ {
+ title: "Cost",
+ dataIndex: "total_cost",
+ key: "total_cost",
+ sorter: (a, b) => a.total_cost - b.total_cost,
+ render: (value) => `$${(value || 0).toFixed(4)}`,
+ width: 120,
+ },
+];
+
+function LLMUsageTable({ data, loading, onRefresh }) {
+ const refreshButton = onRefresh ? (
+ <Tooltip title="Refresh (bypasses cache)">
+ <Button
+ icon={<ReloadOutlined />}
+ size="small"
+ onClick={onRefresh}
+ loading={loading}
+ />
+ </Tooltip>
+ ) : null;
+
+ if (loading) {
+ return (
+ <Card className="metrics-chart-card llm-usage-card">
+ <div className="llm-usage-header">
+ <Text strong className="llm-usage-title">
+ LLM Usage by Workflow
+ </Text>
+ {refreshButton}
+ </div>
+ <div className="metrics-loading">
+ <Spin />
+ </div>
+ </Card>
+ );
+ }
+
+ if (!data?.workflows?.length) {
+ return (
+ <Card className="metrics-chart-card llm-usage-card">
+ <div className="llm-usage-header">
+ <Text strong className="llm-usage-title">
+ LLM Usage by Workflow
+ </Text>
+ {refreshButton}
+ </div>
+ <Empty description="No LLM usage data for this period" />
+ </Card>
+ );
+ }
+
+ return (
+ <Card className="metrics-chart-card llm-usage-card">
+ <div className="llm-usage-header">
+ <Text strong className="llm-usage-title">
+ LLM Usage by Workflow
+ </Text>
+ {refreshButton}
+ </div>
+ <Table
+ dataSource={data.workflows}
+ columns={columns}
+ rowKey="workflow_id"
+ size="middle"
+ pagination={false}
+ scroll={{ y: 400 }}
+ className="llm-usage-table"
+ />
+ </Card>
+ );
+}
+
+LLMUsageTable.propTypes = {
+ data: PropTypes.shape({
+ workflows: PropTypes.arrayOf(
+ PropTypes.shape({
+ workflow_id: PropTypes.string.isRequired,
+ workflow_name: PropTypes.string.isRequired,
+ total_tokens: PropTypes.number,
+ total_cost: PropTypes.number,
+ call_count: PropTypes.number,
+ }),
+ ),
+ }),
+ loading: PropTypes.bool,
+ onRefresh: PropTypes.func,
+};
+
+LLMUsageTable.defaultProps = {
+ data: null,
+ loading: false,
+ onRefresh: null,
+};
+
+export { LLMUsageTable };
diff --git a/frontend/src/components/metrics-dashboard/MetricsChart.jsx b/frontend/src/components/metrics-dashboard/MetricsChart.jsx
new file mode 100644
index 000000000..855656d40
--- /dev/null
+++ b/frontend/src/components/metrics-dashboard/MetricsChart.jsx
@@ -0,0 +1,529 @@
+import { FilterOutlined } from "@ant-design/icons";
+import { Button, Card, Dropdown, Empty, Spin } from "antd";
+import PropTypes from "prop-types";
+import { useMemo, useState } from "react";
+import {
+ Bar,
+ BarChart,
+ CartesianGrid,
+ Legend,
+ Line,
+ LineChart,
+ ResponsiveContainer,
+ Tooltip,
+ XAxis,
+ YAxis,
+} from "recharts";
+
+import "./MetricsDashboard.css";
+
+// Colors for chart lines
+const TREND_COLORS = [
+ "#1890ff",
+ "#52c41a",
+ "#722ed1",
+ "#fa8c16",
+ "#eb2f96",
+ "#13c2c2",
+ "#2f54eb",
+ "#faad14",
+ "#a0d911",
+];
+
+// Metrics for Pages chart
+const PAGES_METRICS = ["pages_processed", "failed_pages"];
+
+/**
+ * Format a date string for display on chart axis.
+ *
+ * @param {string} dateStr - ISO date string
+ * @return {string} Formatted date
+ */
+function formatDate(dateStr) {
+ return new Date(dateStr).toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ });
+}
+
+/**
+ * Format a number for display in tooltips.
+ *
+ * @param {number} value - Number to format
+ * @return {string} Formatted number
+ */
+function formatValue(value) {
+ if (value === null || value === undefined) {
+ return "0";
+ }
+ if (value >= 1000000) {
+ return `${(value / 1000000).toFixed(1)}M`;
+ }
+ if (value >= 1000) {
+ return `${(value / 1000).toFixed(1)}K`;
+ }
+ return value.toLocaleString();
+}
+
+/**
+ * Format metric name for display.
+ *
+ * @param {string} metric - Metric name with underscores
+ * @return {string} Human-readable metric name
+ */
+function formatMetricName(metric) {
+ return metric.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
+}
+
+/**
+ * Custom tooltip for the chart.
+ *
+ * @return {JSX.Element|null} The rendered tooltip or null.
+ */
+function CustomTooltip({ active, payload, label }) {
+ if (!active || !payload?.length) {
+ return null;
+ }
+
+ return (
+ <div className="metrics-chart-tooltip">
+ <p className="tooltip-label">{formatDate(label)}</p>
+ {payload.map((entry, index) => (
+ <p key={index} style={{ color: entry.color }}>
+ {entry.name}: {formatValue(entry.value)}
+ </p>
+ ))}
+ </div>
+ );
+}
+
+CustomTooltip.propTypes = {
+ active: PropTypes.bool,
+ payload: PropTypes.array,
+ label: PropTypes.string,
+};
+
+/**
+ * Pages Processed chart - shows pages_processed and failed_pages.
+ *
+ * @return {JSX.Element} The rendered pages chart component.
+ */
+function PagesChart({ data, loading }) {
+ // Process data for the line chart
+ const chartData = useMemo(() => {
+ if (!data?.daily_trend || data.daily_trend.length === 0) {
+ return [];
+ }
+
+ return data.daily_trend.map((item) => ({
+ date: item.date,
+ pages_processed: item.metrics?.pages_processed || 0,
+ failed_pages: item.metrics?.failed_pages || 0,
+ }));
+ }, [data]);
+
+ if (loading) {
+ return (
+ <Card
+ title="Pages Processed (Last 30 Days)"
+ className="metrics-chart-card"
+ >
+ <div className="metrics-loading">
+ <Spin />
+ </div>
+ </Card>
+ );
+ }
+
+ if (!chartData.length) {
+ return (
+ <Card
+ title="Pages Processed (Last 30 Days)"
+ className="metrics-chart-card"
+ >
+ <Empty description="No data available" />
+ </Card>
+ );
+ }
+
+ return (
+ <Card
+ title="Pages Processed (Last 30 Days)"
+ className="metrics-chart-card chart-card"
+ >
+ <div className="chart-container">
+ <ResponsiveContainer width="100%" height={280}>
+ <LineChart
+ data={chartData}
+ margin={{ top: 5, right: 30, left: 10, bottom: 5 }}
+ >
+ <CartesianGrid
+ strokeDasharray="3 3"
+ vertical={false}
+ stroke="#f0f0f0"
+ />
+ <XAxis
+ dataKey="date"
+ tickFormatter={formatDate}
+ tick={{ fontSize: 12 }}
+ stroke="#8c8c8c"
+ />
+ <YAxis
+ tickFormatter={formatValue}
+ tick={{ fontSize: 12 }}
+ stroke="#8c8c8c"
+ width={50}
+ />
+ <Tooltip content={<CustomTooltip />} />
+ <Legend
+ formatter={(value) => (
+ <span style={{ color: "#262626" }}>{value}</span>
+ )}
+ />
+ <Line
+ type="monotone"
+ dataKey="pages_processed"
+ name="Pages Processed"
+ stroke="#1890ff"
+ strokeWidth={2}
+ dot={{ r: 3, strokeWidth: 2 }}
+ activeDot={{ r: 5 }}
+ />
+ <Line
+ type="monotone"
+ dataKey="failed_pages"
+ name="Failed Pages"
+ stroke="#ff4d4f"
+ strokeWidth={2}
+ dot={{ r: 3, strokeWidth: 2 }}
+ activeDot={{ r: 5 }}
+ />
+ </LineChart>
+ </ResponsiveContainer>
+ </div>
+ </Card>
+ );
+}
+
+PagesChart.propTypes = {
+ data: PropTypes.shape({
+ daily_trend: PropTypes.arrayOf(
+ PropTypes.shape({
+ date: PropTypes.string,
+ metrics: PropTypes.object,
+ }),
+ ),
+ }),
+ loading: PropTypes.bool,
+};
+
+/**
+ * Trend Analysis chart - shows other metrics (not pages).
+ *
+ * @return {JSX.Element} The rendered trend analysis chart component.
+ */
+function TrendAnalysisChart({ data, loading }) {
+ // State for selected metrics
+ const [selectedMetrics, setSelectedMetrics] = useState([
+ "documents_processed",
+ ]);
+
+ // Process data and extract available metrics (excluding pages metrics)
+ const { chartData, availableMetrics, metricOptions } = useMemo(() => {
+ if (!data?.daily_trend || data.daily_trend.length === 0) {
+ return { chartData: [], availableMetrics: [], metricOptions: [] };
+ }
+
+ // Collect all unique metric names, excluding pages metrics
+ const metricNamesSet = new Set();
+ data.daily_trend.forEach((item) => {
+ if (item.metrics) {
+ Object.keys(item.metrics).forEach((key) => {
+ if (!PAGES_METRICS.includes(key)) {
+ metricNamesSet.add(key);
+ }
+ });
+ }
+ });
+ const metricNames = Array.from(metricNamesSet).sort((a, b) =>
+ a.localeCompare(b),
+ );
+
+ const transformed = data.daily_trend.map((item) => ({
+ date: item.date,
+ ...item.metrics,
+ }));
+
+ const options = metricNames.map((metric) => ({
+ label: formatMetricName(metric),
+ value: metric,
+ }));
+
+ return {
+ chartData: transformed,
+ availableMetrics: metricNames,
+ metricOptions: options,
+ };
+ }, [data]);
+
+ // Filter to only show selected metrics that exist
+ const metricsToShow = useMemo(() => {
+ return selectedMetrics.filter((m) => availableMetrics.includes(m));
+ }, [selectedMetrics, availableMetrics]);
+
+ if (loading) {
+ return (
+ <Card
+ title="Trend Analysis (Last 30 Days)"
+ className="metrics-chart-card"
+ >
+ <div className="metrics-loading">
+ <Spin />
+ </div>
+ </Card>
+ );
+ }
+
+ if (!chartData.length) {
+ return (
+ <Card
+ title="Trend Analysis (Last 30 Days)"
+ className="metrics-chart-card"
+ >
+ <Empty description="No data available" />
+ </Card>
+ );
+ }
+
+ // Filter dropdown menu items
+ const filterMenuItems = metricOptions.map((opt) => ({
+ key: opt.value,
+ label: opt.label,
+ }));
+
+ const handleFilterClick = ({ key }) => {
+ if (selectedMetrics.includes(key)) {
+ setSelectedMetrics(selectedMetrics.filter((m) => m !== key));
+ } else {
+ setSelectedMetrics([...selectedMetrics, key]);
+ }
+ };
+
+ // Card extra content with filter dropdown
+ const cardExtra =
+ availableMetrics.length > 1 ? (
+ <Dropdown
+ menu={{
+ items: filterMenuItems,
+ onClick: handleFilterClick,
+ selectable: true,
+ multiple: true,
+ selectedKeys: selectedMetrics,
+ }}
+ trigger={["click"]}
+ >
+ <Button icon={<FilterOutlined />} size="small">
+ Filter
+ </Button>
+ </Dropdown>
+ ) : null;
+
+ // Colors for trend metrics
+ const TREND_BAR_COLORS = {
+ documents_processed: "#faad14",
+ llm_calls: "#722ed1",
+ prompt_executions: "#52c41a",
+ deployed_api_requests: "#13c2c2",
+ llm_usage: "#eb2f96",
+ etl_pipeline_executions: "#fa8c16",
+ challenges: "#2f54eb",
+ summarization_calls: "#a0d911",
+ };
+
+ const getTrendColor = (metric, idx) =>
+ TREND_BAR_COLORS[metric] || TREND_COLORS[idx % TREND_COLORS.length];
+
+ return (
+ <Card
+ title="Trend Analysis (Last 30 Days)"
+ extra={cardExtra}
+ className="metrics-chart-card chart-card"
+ >
+ <div className="chart-container">
+ <ResponsiveContainer width="100%" height={280}>
+ <LineChart
+ data={chartData}
+ margin={{ top: 5, right: 30, left: 10, bottom: 5 }}
+ >
+ <CartesianGrid
+ strokeDasharray="3 3"
+ vertical={false}
+ stroke="#f0f0f0"
+ />
+ <XAxis
+ dataKey="date"
+ tickFormatter={formatDate}
+ tick={{ fontSize: 12 }}
+ stroke="#8c8c8c"
+ />
+ <YAxis
+ tickFormatter={formatValue}
+ tick={{ fontSize: 12 }}
+ stroke="#8c8c8c"
+ width={50}
+ />
+ <Tooltip content={<CustomTooltip />} />
+ {metricsToShow.length > 1 && (
+ <Legend
+ formatter={(value) => (
+ <span style={{ color: "#262626" }}>{value}</span>
+ )}
+ />
+ )}
+ {metricsToShow.map((metric, idx) => (
+ <Line
+ key={metric}
+ type="monotone"
+ dataKey={metric}
+ name={formatMetricName(metric)}
+ stroke={getTrendColor(metric, idx)}
+ strokeWidth={2}
+ dot={{ r: 3, strokeWidth: 2 }}
+ activeDot={{ r: 5 }}
+ />
+ ))}
+ </LineChart>
+ </ResponsiveContainer>
+ </div>
+ </Card>
+ );
+}
+
+TrendAnalysisChart.propTypes = {
+ data: PropTypes.shape({
+ daily_trend: PropTypes.arrayOf(
+ PropTypes.shape({
+ date: PropTypes.string,
+ metrics: PropTypes.object,
+ }),
+ ),
+ }),
+ loading: PropTypes.bool,
+};
+
+// HITL bar colors (blue + yellow/gold)
+const HITL_COLORS = {
+ hitl_reviews: "#69b1ff",
+ hitl_completions: "#faad14",
+};
+
+/**
+ * HITL Reviews & Completions chart.
+ * Returns null when no HITL data is available (e.g. on OSS).
+ *
+ * @return {JSX.Element|null} The rendered HITL chart or null.
+ */
+function HITLChart({ data, loading }) {
+ const chartData = useMemo(() => {
+ if (!data?.daily_trend || data.daily_trend.length === 0) {
+ return [];
+ }
+
+ return data.daily_trend
+ .filter(
+ (item) =>
+ item.metrics?.hitl_reviews > 0 || item.metrics?.hitl_completions > 0,
+ )
+ .map((item) => ({
+ date: item.date,
+ hitl_reviews: item.metrics?.hitl_reviews || 0,
+ hitl_completions: item.metrics?.hitl_completions || 0,
+ }));
+ }, [data]);
+
+ if (loading) {
+ return (
+ <Card
+ title="HITL Reviews & Completions (Last 30 Days)"
+ className="metrics-chart-card"
+ >
+ <div className="metrics-loading">
+ <Spin />
+ </div>
+ </Card>
+ );
+ }
+
+ // No HITL data — return null so the component doesn't render on OSS
+ if (!chartData.length) {
+ return null;
+ }
+
+ return (
+ <Card
+ title="HITL Reviews & Completions (Last 30 Days)"
+ className="metrics-chart-card chart-card"
+ >
+ <div className="chart-container">
+ <ResponsiveContainer width="100%" height={280}>
+ <BarChart
+ data={chartData}
+ margin={{ top: 5, right: 30, left: 10, bottom: 5 }}
+ >
+ <CartesianGrid
+ strokeDasharray="3 3"
+ vertical={false}
+ stroke="#f0f0f0"
+ />
+ <XAxis
+ dataKey="date"
+ tickFormatter={formatDate}
+ tick={{ fontSize: 12 }}
+ stroke="#8c8c8c"
+ />
+ <YAxis
+ tickFormatter={formatValue}
+ tick={{ fontSize: 12 }}
+ stroke="#8c8c8c"
+ width={50}
+ />
+ <Tooltip content={<CustomTooltip />} />
+ <Legend
+ formatter={(value) => (
+ <span style={{ color: "#262626" }}>
+ {formatMetricName(value)}
+ </span>
+ )}
+ />
+ <Bar
+ dataKey="hitl_reviews"
+ name="hitl_reviews"
+ fill={HITL_COLORS.hitl_reviews}
+ radius={[4, 4, 0, 0]}
+ />
+ <Bar
+ dataKey="hitl_completions"
+ name="hitl_completions"
+ fill={HITL_COLORS.hitl_completions}
+ radius={[4, 4, 0, 0]}
+ />
+ </BarChart>
+ </ResponsiveContainer>
+ </div>
+ </Card>
+ );
+}
+
+HITLChart.propTypes = {
+ data: PropTypes.shape({
+ daily_trend: PropTypes.arrayOf(
+ PropTypes.shape({
+ date: PropTypes.string,
+ metrics: PropTypes.object,
+ }),
+ ),
+ }),
+ loading: PropTypes.bool,
+};
+
+export { PagesChart, TrendAnalysisChart, HITLChart };
diff --git a/frontend/src/components/metrics-dashboard/MetricsDashboard.css b/frontend/src/components/metrics-dashboard/MetricsDashboard.css
new file mode 100644
index 000000000..36ec49c8e
--- /dev/null
+++ b/frontend/src/components/metrics-dashboard/MetricsDashboard.css
@@ -0,0 +1,318 @@
+/* Metrics Dashboard Styles */
+
+.metrics-dashboard {
+ padding: 24px;
+ background: #f5f5f5;
+ height: calc(100vh - 64px);
+ overflow-y: auto;
+}
+
+/* Topbar - Full width covering entire space */
+.metrics-topbar {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin: -24px -24px 20px -24px;
+ padding: 12px 24px;
+ background: white;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
+}
+
+.metrics-topbar-left {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+
+.metrics-topbar-icon {
+ font-size: 20px;
+ color: #1890ff;
+}
+
+.metrics-topbar-left h4 {
+ font-weight: 600;
+ color: #262626;
+}
+
+.metrics-topbar-right {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.metrics-header-button {
+ padding: 0px 4px;
+}
+
+.metrics-error {
+ margin-bottom: 16px;
+}
+
+/* Summary Cards - Matching Reference Design */
+.metrics-summary {
+ margin-bottom: 24px;
+}
+
+.summary-card {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ padding: 20px;
+ border-radius: 12px;
+ height: 100%;
+ min-height: 90px;
+ transition:
+ transform 0.2s ease,
+ box-shadow 0.2s ease;
+}
+
+.summary-card:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
+}
+
+.summary-card-icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 48px;
+ height: 48px;
+ border-radius: 12px;
+ flex-shrink: 0;
+}
+
+.summary-card-icon span {
+ font-size: 24px;
+}
+
+.summary-card-content {
+ flex: 1;
+ min-width: 0;
+}
+
+.summary-card-label {
+ font-size: 14px;
+ color: #666;
+ margin-bottom: 4px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.summary-card-value {
+ font-size: 24px;
+ font-weight: 600;
+ color: #1a1a1a;
+ line-height: 1.2;
+}
+
+.summary-card-suffix {
+ font-size: 16px;
+ font-weight: 500;
+ color: #666;
+}
+
+/* Chart Card */
+.chart-card .ant-card-head-title {
+ font-weight: 600;
+}
+
+.metric-card {
+ height: 100%;
+ border-radius: 8px;
+ transition: box-shadow 0.3s ease;
+}
+
+.metric-card:hover {
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+}
+
+.metric-title {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 14px;
+}
+
+.metric-icon {
+ font-size: 16px;
+}
+
+.metric-count {
+ margin-top: 8px;
+ font-size: 12px;
+ color: #8c8c8c;
+}
+
+/* Loading State */
+.metrics-loading {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ padding: 40px;
+ min-height: 200px;
+}
+
+.metrics-empty {
+ padding: 40px;
+}
+
+/* Chart Components */
+.metrics-chart-card {
+ height: 100%;
+}
+
+.chart-container {
+ width: 100%;
+ min-height: 280px;
+}
+
+/* Chart Tooltip */
+.metrics-chart-tooltip {
+ background: rgba(255, 255, 255, 0.96);
+ border: 1px solid #e8e8e8;
+ border-radius: 4px;
+ padding: 10px 14px;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
+}
+
+.metrics-chart-tooltip .tooltip-label {
+ font-weight: 600;
+ margin-bottom: 6px;
+ color: #262626;
+ border-bottom: 1px solid #f0f0f0;
+ padding-bottom: 6px;
+}
+
+.metrics-chart-tooltip p {
+ margin: 4px 0;
+ font-size: 13px;
+}
+
+/* Responsive Adjustments */
+@media (max-width: 768px) {
+ .metrics-topbar {
+ flex-direction: column;
+ align-items: stretch;
+ gap: 12px;
+ margin: -16px -16px 16px -16px;
+ padding: 12px 16px;
+ }
+
+ .metrics-topbar-left {
+ justify-content: center;
+ }
+
+ .metrics-topbar-right {
+ flex-direction: row;
+ justify-content: center;
+ }
+
+ .metrics-dashboard {
+ padding: 16px;
+ }
+}
+
+/* Period Info */
+.period-info {
+ margin-bottom: 16px;
+ padding: 12px;
+ background: white;
+ border-radius: 6px;
+}
+
+/* Recent Activity Styles */
+.recent-activity-list {
+ max-height: 280px;
+ overflow-y: auto;
+}
+
+.recent-activity-item {
+ padding: 10px 0 !important;
+ border-bottom: 1px solid #f0f0f0;
+}
+
+.recent-activity-item:last-child {
+ border-bottom: none;
+}
+
+.recent-activity-content {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ width: 100%;
+}
+
+.recent-activity-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.recent-activity-type {
+ display: flex;
+ align-items: center;
+ font-size: 13px;
+}
+
+.recent-activity-file {
+ font-size: 13px;
+ color: #595959;
+ max-width: 100%;
+}
+
+.recent-activity-meta {
+ font-size: 12px;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.recent-activity-info {
+ font-size: 11px;
+ color: #8c8c8c;
+ cursor: help;
+}
+
+.recent-activity-time {
+ font-size: 12px;
+}
+
+/* LLM Usage Table */
+.llm-usage-card .ant-card-body {
+ padding: 0;
+}
+
+.llm-usage-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 16px 24px;
+ border-bottom: 1px solid #f0f0f0;
+}
+
+.llm-usage-title {
+ font-size: 16px;
+ color: #262626;
+}
+
+.llm-usage-table .ant-table-thead > tr > th {
+ background: #fafafa;
+ color: #595959;
+ font-weight: 600;
+ font-size: 13px;
+ border-bottom: 2px solid #f0f0f0;
+}
+
+.llm-usage-table .ant-table-tbody > tr > td {
+ color: #434343;
+ font-size: 14px;
+}
+
+.llm-usage-table .ant-table-tbody > tr:hover > td {
+ background: #f5f7fa;
+}
+
+.llm-usage-table .ant-table-tbody > tr > td:not(:first-child) {
+ font-variant-numeric: tabular-nums;
+}
diff --git a/frontend/src/components/metrics-dashboard/MetricsDashboard.jsx b/frontend/src/components/metrics-dashboard/MetricsDashboard.jsx
new file mode 100644
index 000000000..17f390b37
--- /dev/null
+++ b/frontend/src/components/metrics-dashboard/MetricsDashboard.jsx
@@ -0,0 +1,250 @@
+import {
+ BarChartOutlined,
+ DashboardOutlined,
+ FileSearchOutlined,
+ ReloadOutlined,
+ SlackOutlined,
+ ThunderboltOutlined,
+} from "@ant-design/icons";
+import {
+ Alert,
+ Button,
+ Col,
+ DatePicker,
+ Row,
+ Space,
+ Tabs,
+ Typography,
+} from "antd";
+import dayjs from "dayjs";
+import { useCallback, useMemo, useState } from "react";
+
+import {
+ useMetricsOverview,
+ useRecentActivity,
+ useWorkflowTokenUsage,
+} from "../../hooks/useMetricsData";
+import { LLMUsageTable } from "./LLMUsageTable";
+import { HITLChart, PagesChart, TrendAnalysisChart } from "./MetricsChart";
+import { MetricsSummary } from "./MetricsSummary";
+import { RecentActivity } from "./RecentActivity";
+
+import "./MetricsDashboard.css";
+
+// Cloud-only: Plan banner with subscription details
+let PlanBanner;
+try {
+ PlanBanner =
+ require("../../plugins/unstract-subscription/components/PlanBanner.jsx").PlanBanner;
+} catch {
+ // Plugin unavailable - no banner on OSS
+}
+
+const { Title } = Typography;
+const { RangePicker } = DatePicker;
+
+function MetricsDashboard() {
+ // Date range state (default: last 30 days)
+ const [dateRange, setDateRange] = useState([
+ dayjs().subtract(30, "day"),
+ dayjs(),
+ ]);
+
+ // Fixed 30-day range for activity charts (independent of date picker)
+ const chartStart = useMemo(
+ () => dayjs().subtract(30, "day").toISOString(),
+ [],
+ );
+ const chartEnd = useMemo(() => dayjs().toISOString(), []);
+
+ // API hooks - pass date range to overview (for summary cards)
+ const {
+ data: overviewData,
+ loading: overviewLoading,
+ error: overviewError,
+ refetch: refetchOverview,
+ } = useMetricsOverview(
+ dateRange[0]?.toISOString(),
+ dateRange[1]?.toISOString(),
+ );
+
+ // Fixed 30-day data for charts
+ const {
+ data: chartData,
+ loading: chartLoading,
+ refetch: refetchChart,
+ } = useMetricsOverview(chartStart, chartEnd);
+
+ // Recent activity (real-time, no date filter)
+ const {
+ data: activityData,
+ loading: activityLoading,
+ refetch: refetchActivity,
+ } = useRecentActivity(5);
+
+ // Per-workflow LLM token usage (uses same date range as summary cards)
+ const {
+ data: tokenUsageData,
+ loading: tokenUsageLoading,
+ refetch: refetchTokenUsage,
+ } = useWorkflowTokenUsage(
+ dateRange[0]?.toISOString(),
+ dateRange[1]?.toISOString(),
+ );
+
+ // Handle date range change
+ const handleDateChange = useCallback((dates) => {
+ if (dates && dates.length === 2) {
+ setDateRange(dates);
+ }
+ }, []);
+
+ // Handle refresh
+ const handleRefresh = useCallback(() => {
+ refetchOverview();
+ refetchChart();
+ refetchActivity();
+ refetchTokenUsage();
+ }, [refetchOverview, refetchChart, refetchActivity, refetchTokenUsage]);
+
+ const tabItems = [
+ {
+ key: "overview",
+ label: (
+ <span>
+ <DashboardOutlined /> Overview
+ </span>
+ ),
+ children: (
+ <>
+ <Row gutter={[16, 16]}>
+ <Col xs={24}>
+ <MetricsSummary data={overviewData} loading={overviewLoading} />
+ </Col>
+ <Col xs={24} lg={16}>
+ <PagesChart data={chartData} loading={chartLoading} />
+ </Col>
+ <Col xs={24} lg={8}>
+ <RecentActivity data={activityData} loading={activityLoading} />
+ </Col>
+ <Col xs={24} lg={12}>
+ <HITLChart data={chartData} loading={chartLoading} />
+ </Col>
+ <Col xs={24} lg={12}>
+ <TrendAnalysisChart data={chartData} loading={chartLoading} />
+ </Col>
+ </Row>
+ </>
+ ),
+ },
+ {
+ key: "llm-usage",
+ label: (
+ <span>
+ <ThunderboltOutlined /> LLM Usage
+ </span>
+ ),
+ children: (
+ <Row gutter={[16, 16]}>
+ <Col xs={24}>
+ <LLMUsageTable
+ data={tokenUsageData}
+ loading={tokenUsageLoading}
+ onRefresh={refetchTokenUsage}
+ />
+ </Col>
+ </Row>
+ ),
+ },
+ ];
+
+ return (
+ <div className="metrics-dashboard">
+ <div className="metrics-topbar">
+ <div className="metrics-topbar-left">
+ <BarChartOutlined className="metrics-topbar-icon" />
+ <Title level={4} style={{ margin: 0 }}>
+ Dashboard
+ </Title>
+ </div>
+
+ <Space className="metrics-topbar-right">
+ <Button
+ icon={<FileSearchOutlined />}
+ type="link"
+ onClick={() =>
+ window.open(
+ "https://docs.unstract.com/unstract/index.html",
+ "_blank",
+ "noopener,noreferrer",
+ )
+ }
+ className="metrics-header-button"
+ >
+ Documentation
+ </Button>
+ <Button
+ icon={<SlackOutlined />}
+ type="link"
+ onClick={() =>
+ window.open(
+ "https://join-slack.unstract.com/",
+ "_blank",
+ "noopener,noreferrer",
+ )
+ }
+ className="metrics-header-button"
+ >
+ Slack Community
+ </Button>
+ </Space>
+ </div>
+
+ {PlanBanner && <PlanBanner />}
+
+ {overviewError && (
+ <Alert
+ message="Error loading metrics"
+ description={overviewError}
+ type="error"
+ showIcon
+ closable
+ className="metrics-error"
+ />
+ )}
+
+ <Tabs
+ items={tabItems}
+ defaultActiveKey="overview"
+ tabBarExtraContent={
+ <Space>
+ <RangePicker
+ value={dateRange}
+ onChange={handleDateChange}
+ disabledDate={(current) => current && current > dayjs()}
+ allowClear={false}
+ size="middle"
+ presets={[
+ {
+ label: "Last 7 Days",
+ value: [dayjs().subtract(7, "day"), dayjs()],
+ },
+ {
+ label: "Last 30 Days",
+ value: [dayjs().subtract(30, "day"), dayjs()],
+ },
+ {
+ label: "Last 90 Days",
+ value: [dayjs().subtract(90, "day"), dayjs()],
+ },
+ ]}
+ />
+ <Button icon={<ReloadOutlined />} onClick={handleRefresh} />
+ </Space>
+ }
+ />
+ </div>
+ );
+}
+
+export { MetricsDashboard };
diff --git a/frontend/src/components/metrics-dashboard/MetricsSummary.jsx b/frontend/src/components/metrics-dashboard/MetricsSummary.jsx
new file mode 100644
index 000000000..756c96827
--- /dev/null
+++ b/frontend/src/components/metrics-dashboard/MetricsSummary.jsx
@@ -0,0 +1,255 @@
+import {
+ ApiOutlined,
+ CheckCircleOutlined,
+ DollarOutlined,
+ EyeOutlined,
+ FileTextOutlined,
+ RocketOutlined,
+ ThunderboltOutlined,
+ WarningOutlined,
+} from "@ant-design/icons";
+import { Col, Empty, Row, Spin } from "antd";
+import PropTypes from "prop-types";
+
+import "./MetricsDashboard.css";
+
+// Mapping metric names to display config with colors matching reference design
+const METRIC_CONFIG = {
+ pages_processed: {
+ label: "Pages Processed",
+ icon: <FileTextOutlined />,
+ bgColor: "#e8f5e9",
+ iconBg: "#c8e6c9",
+ iconColor: "#2e7d32",
+ suffix: "",
+ },
+ documents_processed: {
+ label: "Documents Processed",
+ icon: <FileTextOutlined />,
+ bgColor: "#fff3e0",
+ iconBg: "#ffe0b2",
+ iconColor: "#e65100",
+ suffix: "",
+ },
+ llm_calls: {
+ label: "LLM Calls",
+ icon: <ApiOutlined />,
+ bgColor: "#e0f2f1",
+ iconBg: "#b2dfdb",
+ iconColor: "#00695c",
+ suffix: "",
+ },
+ prompt_executions: {
+ label: "Prompt Executions",
+ icon: <ThunderboltOutlined />,
+ bgColor: "#ede7f6",
+ iconBg: "#d1c4e9",
+ iconColor: "#4527a0",
+ suffix: "",
+ },
+ deployed_api_requests: {
+ label: "API Requests",
+ icon: <RocketOutlined />,
+ bgColor: "#e3f2fd",
+ iconBg: "#bbdefb",
+ iconColor: "#1565c0",
+ suffix: "",
+ },
+ llm_usage: {
+ label: "LLM Usage Cost",
+ icon: <DollarOutlined />,
+ bgColor: "#fce4ec",
+ iconBg: "#f8bbd9",
+ iconColor: "#c2185b",
+ prefix: "$",
+ precision: 2,
+ suffix: "",
+ },
+ etl_pipeline_executions: {
+ label: "ETL Executions",
+ icon: <RocketOutlined />,
+ bgColor: "#ffebee",
+ iconBg: "#ffcdd2",
+ iconColor: "#c62828",
+ suffix: "",
+ },
+ challenges: {
+ label: "Challenges",
+ icon: <ThunderboltOutlined />,
+ bgColor: "#fce4ec",
+ iconBg: "#f8bbd9",
+ iconColor: "#ad1457",
+ suffix: "",
+ },
+ summarization_calls: {
+ label: "Summarizations",
+ icon: <ThunderboltOutlined />,
+ bgColor: "#e0f7fa",
+ iconBg: "#b2ebf2",
+ iconColor: "#00838f",
+ suffix: "",
+ },
+ failed_pages: {
+ label: "Failed Pages",
+ icon: <WarningOutlined />,
+ bgColor: "#fff1f0",
+ iconBg: "#ffccc7",
+ iconColor: "#cf1322",
+ suffix: "",
+ },
+ hitl_reviews: {
+ label: "HITL Reviews",
+ icon: <EyeOutlined />,
+ bgColor: "#f3e8ff",
+ iconBg: "#e0cffc",
+ iconColor: "#6d28d9",
+ suffix: "",
+ },
+ hitl_completions: {
+ label: "HITL Completions",
+ icon: <CheckCircleOutlined />,
+ bgColor: "#ecfdf5",
+ iconBg: "#d1fae5",
+ iconColor: "#059669",
+ suffix: "",
+ },
+};
+
+// Priority order for displaying metrics (show top 4 first like reference)
+const METRIC_PRIORITY = [
+ "pages_processed",
+ "documents_processed",
+ "failed_pages",
+ "llm_calls",
+ "prompt_executions",
+ "deployed_api_requests",
+ "llm_usage",
+ "hitl_reviews",
+ "hitl_completions",
+];
+
+/**
+ * Format large numbers for display.
+ *
+ * @param {number} value - The number to format
+ * @param {number} precision - Decimal precision (default 0)
+ * @return {string} Formatted number string
+ */
+function formatValue(value, precision = 0) {
+ if (value === null || value === undefined) {
+ return "0";
+ }
+ if (precision > 0) {
+ return value.toLocaleString(undefined, {
+ minimumFractionDigits: precision,
+ maximumFractionDigits: precision,
+ });
+ }
+ return Math.round(value).toLocaleString();
+}
+
+function MetricsSummary({ data, loading }) {
+ if (loading) {
+ return (
+ <div className="metrics-loading">
+ <Spin size="large" />
+ </div>
+ );
+ }
+
+ if (!data?.totals || data.totals.length === 0) {
+ return (
+ <Empty
+ description="No metrics data available"
+ className="metrics-empty"
+ />
+ );
+ }
+
+ // Sort metrics by priority, skip zero-value metrics
+ const sortedMetrics = [...data.totals]
+ .filter((m) => m.total_value > 0)
+ .sort((a, b) => {
+ const aIndex = METRIC_PRIORITY.indexOf(a.metric_name);
+ const bIndex = METRIC_PRIORITY.indexOf(b.metric_name);
+ if (aIndex === -1 && bIndex === -1) {
+ return 0;
+ }
+ if (aIndex === -1) {
+ return 1;
+ }
+ if (bIndex === -1) {
+ return -1;
+ }
+ return aIndex - bIndex;
+ });
+
+ return (
+ <Row gutter={[16, 16]} className="metrics-summary">
+ {sortedMetrics.map((metric) => {
+ const config = METRIC_CONFIG[metric.metric_name] || {
+ label: metric.metric_name,
+ icon: <ApiOutlined />,
+ bgColor: "#f5f5f5",
+ iconBg: "#e0e0e0",
+ iconColor: "#616161",
+ suffix: "",
+ };
+
+ const displayValue = formatValue(
+ metric.total_value || 0,
+ config.precision || 0,
+ );
+
+ return (
+ <Col xs={24} sm={12} md={8} lg={6} key={metric.metric_name}>
+ <div
+ className="summary-card"
+ style={{ backgroundColor: config.bgColor }}
+ >
+ <div
+ className="summary-card-icon"
+ style={{ backgroundColor: config.iconBg }}
+ >
+ <span style={{ color: config.iconColor }}>{config.icon}</span>
+ </div>
+ <div className="summary-card-content">
+ <div className="summary-card-label">{config.label}</div>
+ <div className="summary-card-value">
+ {config.prefix}
+ {displayValue}
+ {config.suffix && (
+ <span className="summary-card-suffix">
+ {" "}
+ {config.suffix}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ </Col>
+ );
+ })}
+ </Row>
+ );
+}
+
+MetricsSummary.propTypes = {
+ data: PropTypes.shape({
+ totals: PropTypes.arrayOf(
+ PropTypes.shape({
+ metric_name: PropTypes.string.isRequired,
+ total_value: PropTypes.number,
+ total_count: PropTypes.number,
+ }),
+ ),
+ }),
+ loading: PropTypes.bool,
+};
+
+MetricsSummary.defaultProps = {
+ data: null,
+ loading: false,
+};
+
+export { MetricsSummary };
diff --git a/frontend/src/components/metrics-dashboard/RecentActivity.jsx b/frontend/src/components/metrics-dashboard/RecentActivity.jsx
new file mode 100644
index 000000000..874c5e360
--- /dev/null
+++ b/frontend/src/components/metrics-dashboard/RecentActivity.jsx
@@ -0,0 +1,163 @@
+import {
+ ApiOutlined,
+ BranchesOutlined,
+ CheckCircleOutlined,
+ ClockCircleOutlined,
+ CloseCircleOutlined,
+ InfoCircleOutlined,
+ PlayCircleOutlined,
+ SyncOutlined,
+} from "@ant-design/icons";
+import { Card, Empty, List, Spin, Tag, Tooltip, Typography } from "antd";
+import dayjs from "dayjs";
+import relativeTime from "dayjs/plugin/relativeTime";
+import PropTypes from "prop-types";
+
+import "./MetricsDashboard.css";
+
+dayjs.extend(relativeTime);
+
+const { Text } = Typography;
+
+// Status configuration with colors and icons
+const STATUS_CONFIG = {
+ COMPLETED: {
+ color: "success",
+ icon: <CheckCircleOutlined />,
+ label: "Completed",
+ },
+ RUNNING: {
+ color: "processing",
+ icon: <SyncOutlined spin />,
+ label: "Processing",
+ },
+ QUEUED: {
+ color: "default",
+ icon: <ClockCircleOutlined />,
+ label: "Queued",
+ },
+ ERROR: {
+ color: "error",
+ icon: <CloseCircleOutlined />,
+ label: "Failed",
+ },
+};
+
+// Execution type configuration
+const TYPE_CONFIG = {
+ etl: {
+ label: "ETL Pipeline",
+ icon: <BranchesOutlined />,
+ color: "#722ed1",
+ },
+ api: {
+ label: "API Request",
+ icon: <ApiOutlined />,
+ color: "#1890ff",
+ },
+ workflow: {
+ label: "Workflow",
+ icon: <PlayCircleOutlined />,
+ color: "#52c41a",
+ },
+};
+
+/**
+ * Recent Activity component showing latest processing events.
+ * Displays file executions categorized by type (ETL, API, Workflow).
+ *
+ * @return {JSX.Element} The rendered recent activity component.
+ */
+function RecentActivity({ data, loading }) {
+ if (loading) {
+ return (
+ <Card title="Recent Activity" className="metrics-chart-card">
+ <div className="metrics-loading">
+ <Spin />
+ </div>
+ </Card>
+ );
+ }
+
+ if (!data?.activity?.length) {
+ return (
+ <Card title="Recent Activity" className="metrics-chart-card">
+ <Empty description="No recent activity" />
+ </Card>
+ );
+ }
+
+ return (
+ <Card title="Recent Activity" className="metrics-chart-card chart-card">
+ <List
+ className="recent-activity-list"
+ dataSource={data.activity}
+ size="small"
+ split={false}
+ renderItem={(item) => {
+ const statusConfig =
+ STATUS_CONFIG[item.status] || STATUS_CONFIG.QUEUED;
+ const typeConfig = TYPE_CONFIG[item.type] || TYPE_CONFIG.workflow;
+
+ return (
+ <List.Item className="recent-activity-item">
+ <div className="recent-activity-content">
+ <div className="recent-activity-header">
+ <span
+ className="recent-activity-type"
+ style={{ color: typeConfig.color }}
+ >
+ {typeConfig.icon}
+ <Text strong style={{ marginLeft: 6 }}>
+ {typeConfig.label}
+ </Text>
+ </span>
+ <Tag color={statusConfig.color}>{statusConfig.label}</Tag>
+ </div>
+ <Text className="recent-activity-file" ellipsis>
+ {item.file_name}
+ </Text>
+ {item.total_tokens > 0 && (
+ <Text type="secondary" className="recent-activity-meta">
+ <span>{item.total_tokens.toLocaleString()} tokens</span>
+ <Tooltip title="Total LLM tokens used to process this file">
+ <InfoCircleOutlined className="recent-activity-info" />
+ </Tooltip>
+ </Text>
+ )}
+ <Text type="secondary" className="recent-activity-time">
+ {dayjs(item.created_at).fromNow()}
+ </Text>
+ </div>
+ </List.Item>
+ );
+ }}
+ />
+ </Card>
+ );
+}
+
+RecentActivity.propTypes = {
+ data: PropTypes.shape({
+ activity: PropTypes.arrayOf(
+ PropTypes.shape({
+ id: PropTypes.string.isRequired,
+ type: PropTypes.oneOf(["etl", "api", "workflow"]).isRequired,
+ file_name: PropTypes.string.isRequired,
+ status: PropTypes.string.isRequired,
+ workflow_name: PropTypes.string,
+ created_at: PropTypes.string.isRequired,
+ execution_time: PropTypes.number,
+ total_tokens: PropTypes.number,
+ }),
+ ),
+ }),
+ loading: PropTypes.bool,
+};
+
+RecentActivity.defaultProps = {
+ data: null,
+ loading: false,
+};
+
+export { RecentActivity };
diff --git a/frontend/src/components/metrics-dashboard/index.js b/frontend/src/components/metrics-dashboard/index.js
new file mode 100644
index 000000000..4893ecedb
--- /dev/null
+++ b/frontend/src/components/metrics-dashboard/index.js
@@ -0,0 +1,5 @@
+export { LLMUsageTable } from "./LLMUsageTable";
+export { PagesChart, TrendAnalysisChart } from "./MetricsChart";
+export { MetricsDashboard } from "./MetricsDashboard";
+export { MetricsSummary } from "./MetricsSummary";
+export { RecentActivity } from "./RecentActivity";
diff --git a/frontend/src/components/navigations/side-nav-bar/SideNavBar.css b/frontend/src/components/navigations/side-nav-bar/SideNavBar.css
index 98caa875f..a2f925f7c 100644
--- a/frontend/src/components/navigations/side-nav-bar/SideNavBar.css
+++ b/frontend/src/components/navigations/side-nav-bar/SideNavBar.css
@@ -73,6 +73,15 @@
color: white;
}
+.sidebar-item-tag {
+ margin-left: 6px;
+ font-size: 10px;
+ line-height: 16px;
+ padding: 0 4px;
+ border-radius: 4px;
+ vertical-align: middle;
+}
+
.slider-wrap {
padding: 12px;
}
diff --git a/frontend/src/components/navigations/side-nav-bar/SideNavBar.jsx b/frontend/src/components/navigations/side-nav-bar/SideNavBar.jsx
index b37f64f66..a63f8cff0 100644
--- a/frontend/src/components/navigations/side-nav-bar/SideNavBar.jsx
+++ b/frontend/src/components/navigations/side-nav-bar/SideNavBar.jsx
@@ -15,6 +15,7 @@ import { useNavigate } from "react-router-dom";
import apiDeploy from "../../../assets/api-deployments.svg";
import ConnectorsIcon from "../../../assets/connectors.svg";
import CustomTools from "../../../assets/custom-tools-icon.svg";
+import DashboardIcon from "../../../assets/dashboard.svg";
import EmbeddingIcon from "../../../assets/embedding.svg";
import etl from "../../../assets/etl.svg";
import LlmIcon from "../../../assets/llm.svg";
@@ -118,10 +119,18 @@ const getSettingsMenuItems = (orgName) => [
const getActiveSettingsKey = () => {
const currentPath = globalThis.location.pathname;
- if (currentPath.includes("/settings/platform")) return "platform";
- if (currentPath.includes("/users")) return "users";
- if (currentPath.includes("/settings/triad")) return "triad";
- if (currentPath.includes("/settings/review")) return "review";
+ if (currentPath.includes("/settings/platform")) {
+ return "platform";
+ }
+ if (currentPath.includes("/users")) {
+ return "users";
+ }
+ if (currentPath.includes("/settings/triad")) {
+ return "triad";
+ }
+ if (currentPath.includes("/settings/review")) {
+ return "review";
+ }
return "platform";
};
@@ -168,7 +177,7 @@ const SideNavBar = ({ collapsed }) => {
(state) => state?.unstractSubscriptionPlan,
);
}
- } catch (error) {
+ } catch (_error) {
// Do nothing
}
@@ -319,9 +328,20 @@ const SideNavBar = ({ collapsed }) => {
},
];
+ // Add dashboard/metrics menu items
if (dashboardSideMenuItem) {
unstractMenuItems[1].subMenu.unshift(dashboardSideMenuItem(orgName));
}
+ // Add metrics dashboard menu item (available for both OSS and cloud)
+ unstractMenuItems[1].subMenu.unshift({
+ id: 2.0,
+ title: "Dashboard",
+ tag: "New",
+ description: "View platform usage metrics and analytics",
+ image: DashboardIcon,
+ path: `/${orgName}/metrics`,
+ active: globalThis.location.pathname.startsWith(`/${orgName}/metrics`),
+ });
// If selectedProduct is verticals and menu is null, don't show any sidebar items
const data =
@@ -485,6 +505,11 @@ const SideNavBar = ({ collapsed }) => {
<div>
<Typography className="sidebar-item-text fs-14 sidebar-title-row">
{el.title}
+ {el.tag && (
+ <Tag color="blue" className="sidebar-item-tag">
+ {el.tag}
+ </Tag>
+ )}
</Typography>
<Typography className="sidebar-item-text fs-11">
{el.description}
diff --git a/frontend/src/helpers/metricsCache.js b/frontend/src/helpers/metricsCache.js
new file mode 100644
index 000000000..6d182c942
--- /dev/null
+++ b/frontend/src/helpers/metricsCache.js
@@ -0,0 +1,133 @@
+/**
+ * LocalStorage cache utility for dashboard metrics.
+ * Provides TTL-based caching matching backend cache TTLs.
+ */
+
+const CACHE_PREFIX = "dashboard_metrics_";
+
+// Cache TTLs matching backend settings (in milliseconds)
+const CACHE_TTL = {
+ overview: 5 * 60 * 1000, // 5 minutes (DASHBOARD_CACHE_TTL_OVERVIEW)
+ summary: 15 * 60 * 1000, // 15 minutes (DASHBOARD_CACHE_TTL_SUMMARY)
+ series: 30 * 60 * 1000, // 30 minutes (DASHBOARD_CACHE_TTL_SERIES)
+ "live-summary": 15 * 60 * 1000, // Same as summary
+ "live-series": 30 * 60 * 1000, // Same as series
+ workflow_token_usage: 60 * 60 * 1000, // 1 hour (DASHBOARD_CACHE_TTL_WORKFLOW_USAGE)
+};
+
+/**
+ * Build a unique cache key from endpoint and params.
+ *
+ * @param {string} endpoint - API endpoint name
+ * @param {Object} params - Query parameters
+ * @return {string} Unique cache key
+ */
+function buildCacheKey(endpoint, params) {
+ const sortedKeys = Object.keys(params).sort((a, b) => a.localeCompare(b));
+ const paramStr = sortedKeys.map((k) => `${k}=${params[k]}`).join("&");
+ // Use simple encoding to avoid btoa issues with unicode
+ const hash = paramStr ? `_${encodeURIComponent(paramStr)}` : "";
+ return `${CACHE_PREFIX}${endpoint}${hash}`;
+}
+
+/**
+ * Get cached data if valid and not expired.
+ *
+ * @param {string} endpoint - API endpoint name
+ * @param {Object} params - Query parameters used in the request
+ * @return {Object|null} Cached data or null if not found/expired
+ */
+function getCached(endpoint, params = {}) {
+ try {
+ const key = buildCacheKey(endpoint, params);
+ const cached = localStorage.getItem(key);
+ if (!cached) {
+ return null;
+ }
+
+ const { data, expiry } = JSON.parse(cached);
+ if (Date.now() > expiry) {
+ localStorage.removeItem(key);
+ return null;
+ }
+ return data;
+ } catch (error) {
+ // Handle JSON parse errors or other issues
+ console.warn("Cache read error:", error);
+ return null;
+ }
+}
+
+/**
+ * Store data in cache with TTL.
+ *
+ * @param {string} endpoint - API endpoint name
+ * @param {Object} params - Query parameters used in the request
+ * @param {Object} data - Data to cache
+ */
+function setCache(endpoint, params = {}, data) {
+ try {
+ const key = buildCacheKey(endpoint, params);
+ const ttl = CACHE_TTL[endpoint] || CACHE_TTL.summary;
+ const entry = {
+ data,
+ expiry: Date.now() + ttl,
+ timestamp: Date.now(),
+ };
+ localStorage.setItem(key, JSON.stringify(entry));
+ } catch (error) {
+ // Handle localStorage quota errors
+ console.warn("Cache write error:", error);
+ // Try to clear old cache entries if quota exceeded
+ if (error.name === "QuotaExceededError") {
+ clearMetricsCache();
+ }
+ }
+}
+
+/**
+ * Clear all metrics cache entries.
+ * Useful when user manually refreshes or on logout.
+ */
+function clearMetricsCache() {
+ try {
+ const keys = Object.keys(localStorage).filter((k) =>
+ k.startsWith(CACHE_PREFIX),
+ );
+ keys.forEach((k) => {
+ localStorage.removeItem(k);
+ });
+ } catch (error) {
+ console.warn("Cache clear error:", error);
+ }
+}
+
+/**
+ * Get cache entry metadata (for debugging).
+ *
+ * @param {string} endpoint - API endpoint name
+ * @param {Object} params - Query parameters
+ * @return {Object|null} Cache metadata or null
+ */
+function getCacheInfo(endpoint, params = {}) {
+ try {
+ const key = buildCacheKey(endpoint, params);
+ const cached = localStorage.getItem(key);
+ if (!cached) {
+ return null;
+ }
+
+ const { expiry, timestamp } = JSON.parse(cached);
+ return {
+ key,
+ timestamp: new Date(timestamp).toISOString(),
+ expiry: new Date(expiry).toISOString(),
+ ttlRemaining: Math.max(0, expiry - Date.now()),
+ isExpired: Date.now() > expiry,
+ };
+ } catch (_error) {
+ return null;
+ }
+}
+
+export { getCached, setCache, clearMetricsCache, getCacheInfo, CACHE_TTL };
diff --git a/frontend/src/hooks/useMetricsData.js b/frontend/src/hooks/useMetricsData.js
new file mode 100644
index 000000000..7b16aade3
--- /dev/null
+++ b/frontend/src/hooks/useMetricsData.js
@@ -0,0 +1,212 @@
+import { useCallback, useEffect, useState } from "react";
+
+import { getCached, setCache } from "../helpers/metricsCache";
+import { useSessionStore } from "../store/session-store";
+import { useAxiosPrivate } from "./useAxiosPrivate";
+
+/**
+ * Hook for fetching metrics overview (quick stats for a date range).
+ * Uses localStorage caching with TTL matching backend.
+ *
+ * @param {string} startDate - Start date (ISO 8601, optional - defaults to 7 days ago)
+ * @param {string} endDate - End date (ISO 8601, optional - defaults to now)
+ * @return {Object} { data, loading, error, refetch }
+ */
+function useMetricsOverview(startDate = null, endDate = null) {
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const axiosPrivate = useAxiosPrivate();
+ const { sessionDetails } = useSessionStore();
+ const orgId = sessionDetails?.orgId;
+
+ const fetchOverview = useCallback(
+ async (skipCache = false) => {
+ // Guard: don't fetch if orgId is not available
+ if (!orgId) {
+ setLoading(false);
+ return;
+ }
+
+ setError(null);
+ const cacheParams = { org: orgId, startDate, endDate };
+
+ // Check cache first (unless skip requested)
+ if (!skipCache) {
+ const cached = getCached("overview", cacheParams);
+ if (cached) {
+ setData(cached);
+ setLoading(false);
+ return;
+ }
+ }
+
+ setLoading(true);
+
+ try {
+ const params = new URLSearchParams();
+ if (startDate) {
+ params.append("start_date", startDate);
+ }
+ if (endDate) {
+ params.append("end_date", endDate);
+ }
+
+ const url = `/api/v1/unstract/${orgId}/metrics/overview/${
+ params.toString() ? `?${params}` : ""
+ }`;
+ const response = await axiosPrivate.get(url);
+ setData(response.data);
+ // Cache the response
+ setCache("overview", cacheParams, response.data);
+ } catch (err) {
+ setError(err.response?.data?.message || "Failed to fetch overview");
+ } finally {
+ setLoading(false);
+ }
+ },
+ [axiosPrivate, orgId, startDate, endDate],
+ );
+
+ useEffect(() => {
+ if (orgId) {
+ fetchOverview();
+ } else {
+ setData(null);
+ setLoading(false);
+ setError(null);
+ }
+ }, [orgId, startDate, endDate]); // eslint-disable-line
+
+ // refetch bypasses cache
+ const refetch = useCallback(() => fetchOverview(true), [fetchOverview]);
+
+ return { data, loading, error, refetch };
+}
+
+/**
+ * Hook for fetching recent processing activity.
+ * Real-time data - no caching.
+ *
+ * @param {number} limit - Maximum records to return (default 10)
+ * @return {Object} { data, loading, error, refetch }
+ */
+function useRecentActivity(limit = 10) {
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const axiosPrivate = useAxiosPrivate();
+ const { sessionDetails } = useSessionStore();
+ const orgId = sessionDetails?.orgId;
+
+ const fetchActivity = useCallback(async () => {
+ if (!orgId) {
+ setLoading(false);
+ return;
+ }
+
+ setLoading(true);
+ setError(null);
+
+ try {
+ const url = `/api/v1/unstract/${orgId}/metrics/recent-activity/?limit=${limit}`;
+ const response = await axiosPrivate.get(url);
+ setData(response.data);
+ } catch (err) {
+ setError(err.response?.data?.message || "Failed to fetch activity");
+ } finally {
+ setLoading(false);
+ }
+ }, [axiosPrivate, orgId, limit]);
+
+ useEffect(() => {
+ if (orgId) {
+ fetchActivity();
+ } else {
+ setData(null);
+ setLoading(false);
+ setError(null);
+ }
+ }, [orgId, limit]); // eslint-disable-line
+
+ return { data, loading, error, refetch: fetchActivity };
+}
+
+/**
+ * Hook for fetching per-workflow LLM token usage.
+ * Uses localStorage caching with 1-hour TTL. Supports manual refresh
+ * that bypasses both frontend and backend caches.
+ *
+ * @param {string} startDate - Start date (ISO 8601)
+ * @param {string} endDate - End date (ISO 8601)
+ * @return {Object} { data, loading, error, refetch }
+ */
+function useWorkflowTokenUsage(startDate, endDate) {
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const axiosPrivate = useAxiosPrivate();
+ const { sessionDetails } = useSessionStore();
+ const orgId = sessionDetails?.orgId;
+
+ const fetchUsage = useCallback(
+ async (skipCache = false) => {
+ if (!orgId || !startDate || !endDate) {
+ setLoading(false);
+ return;
+ }
+
+ setError(null);
+ const cacheParams = { org: orgId, startDate, endDate };
+
+ // Check cache first (unless skip requested)
+ if (!skipCache) {
+ const cached = getCached("workflow_token_usage", cacheParams);
+ if (cached) {
+ setData(cached);
+ setLoading(false);
+ return;
+ }
+ }
+
+ setLoading(true);
+
+ try {
+ const params = new URLSearchParams();
+ params.append("start_date", startDate);
+ params.append("end_date", endDate);
+ if (skipCache) {
+ params.append("refresh", "true");
+ }
+ const url = `/api/v1/unstract/${orgId}/metrics/workflow-token-usage/?${params}`;
+ const response = await axiosPrivate.get(url);
+ setData(response.data);
+ setCache("workflow_token_usage", cacheParams, response.data);
+ } catch (err) {
+ setError(
+ err.response?.data?.message || "Failed to fetch workflow token usage",
+ );
+ } finally {
+ setLoading(false);
+ }
+ },
+ [axiosPrivate, orgId, startDate, endDate],
+ );
+
+ useEffect(() => {
+ if (orgId && startDate && endDate) {
+ fetchUsage();
+ } else {
+ setData(null);
+ setLoading(false);
+ setError(null);
+ }
+ }, [orgId, startDate, endDate]); // eslint-disable-line
+
+ // refetch bypasses both frontend and backend caches
+ const refetch = useCallback(() => fetchUsage(true), [fetchUsage]);
+
+ return { data, loading, error, refetch };
+}
+
+export { useMetricsOverview, useRecentActivity, useWorkflowTokenUsage };
diff --git a/frontend/src/pages/MetricsDashboardPage.jsx b/frontend/src/pages/MetricsDashboardPage.jsx
new file mode 100644
index 000000000..961c9ba93
--- /dev/null
+++ b/frontend/src/pages/MetricsDashboardPage.jsx
@@ -0,0 +1,7 @@
+import { MetricsDashboard } from "../components/metrics-dashboard";
+
+function MetricsDashboardPage() {
+ return <MetricsDashboard />;
+}
+
+export { MetricsDashboardPage };
diff --git a/frontend/src/routes/useMainAppRoutes.js b/frontend/src/routes/useMainAppRoutes.js
index 35f753e35..3f54c9f90 100644
--- a/frontend/src/routes/useMainAppRoutes.js
+++ b/frontend/src/routes/useMainAppRoutes.js
@@ -13,6 +13,7 @@ import { CustomTools } from "../pages/CustomTools.jsx";
import { DeploymentsPage } from "../pages/DeploymentsPage.jsx";
import { InviteEditUserPage } from "../pages/InviteEditUserPage.jsx";
import { LogsPage } from "../pages/LogsPage.jsx";
+import { MetricsDashboardPage } from "../pages/MetricsDashboardPage.jsx";
import { OnBoardPage } from "../pages/OnBoardPage.jsx";
import { OutputAnalyzerPage } from "../pages/OutputAnalyzerPage.jsx";
import { ProfilePage } from "../pages/ProfilePage.jsx";
@@ -187,6 +188,7 @@ function useMainAppRoutes() {
)}
<Route path="logs" element={<LogsPage />} />
<Route path="logs/:type/:id/" element={<LogsPage />} />
+ <Route path="metrics" element={<MetricsDashboardPage />} />
<Route
path="settings/llms"
element={<ToolsSettingsPage type="llm" />}