Skip to content

The platform for continuously improving AI agents.

Add concise Overwatch snapshots and project activity rankings (#321)

SBb34872104b4e
diff --git a/.agents/skills/backend-architecture/references/auth-and-billing.md b/.agents/skills/backend-architecture/references/auth-and-billing.md
index b3666778..7ac8dabb 100644
--- a/.agents/skills/backend-architecture/references/auth-and-billing.md
+++ b/.agents/skills/backend-architecture/references/auth-and-billing.md
@@ -28,8 +28,8 @@ Overwatch is the internal user-insights dashboard. Its dashboard endpoints under
- They skip user authentication, stay out of MCP and the OpenAPI schema, and exclude guests and guest-only projects.
- Overwatch only reads product records: no product models, migrations, notification ledger, periodic writer or event emitter in this backend. Notification state lives in Overwatch storage outside it. Shared backend dependency upgrades need a separate platform review.
- Optional PostHog aggregates need a project-query read key and project ID in the backend environment. The key stays server-side, and responses carry only validated aggregate event counts.
-- `POST /api/internal/overwatch/agent/query/` (`api/overwatch_agent.py`) uses a dedicated `OVERWATCH_SERVICE_TOKEN` and rejects dashboard, product and staff credentials. It validates six bounded read tools (`services/overwatch_tools.py`) inside a PostgreSQL read-only transaction. POST keeps customer emails out of URL logs, and the service key cannot authenticate product writes.
-- Customer lookup accepts exactly one exact email or a bounded name/domain query. Multiple matches return up to five choices privately; no customer is guessed. `customer_activity` and `model_usage` aggregate retained `InferenceCall` rows by window, outcome, source and model. Membership identifies shared projects, not the caller. Tokens are recorded hosted-model counts; historical zero fields may be missing telemetry. These reports use a ten-second read budget and five-minute snapshots; other cached agent tools retain their hourly cache. Cache keys include the UTC window, and replies preserve `as_of` and `refreshes_at`. Named reports never return to the model. No product models or writers change.
+- `POST /api/internal/overwatch/agent/query/` (`api/overwatch_agent.py`) uses a dedicated `OVERWATCH_SERVICE_TOKEN` and rejects dashboard, product and staff credentials. It validates seven bounded read tools (`services/overwatch_tools.py`) inside a PostgreSQL read-only transaction. POST keeps customer emails out of URL logs, and the service key cannot authenticate product writes.
+- Customer lookup accepts exactly one exact email or a bounded name/domain query. Multiple matches return up to five choices privately; no customer is guessed. `customer_activity`, `model_usage` and `project_activity` aggregate retained `InferenceCall` rows by window, outcome, source and model. Membership identifies shared projects, not the caller. Tokens are recorded hosted-model counts; historical zero fields may be missing telemetry. These reports use a ten-second read budget and five-minute snapshots; other cached agent tools retain their hourly cache. Cache keys include the UTC window, and replies preserve `as_of` and `refreshes_at`. Reports default to compact snapshots; `view=details` expands sources/models and customer billing. `project_activity` ranks named projects with bounded member labels (not caller attribution) by successful calls, recorded tokens or absolute call growth/decline. Comparisons use the same elapsed duration shifted back by the requested number of days. Named reports never return to the model. No product models or writers change.
- MCP impact: out of scope for the public/project MCP catalog. These cross-customer internal reports remain behind the dedicated service token and private Slack authorization boundary; they are excluded from OpenAPI.
- Slack Q&A runs as a separate profile in the Overlord repository; this backend has no Slack or model adapter, routes or Celery tasks for it. That profile needs its own app credentials, an explicit user-ID allowlist and a linked unrestricted internal employee (HR admins do not bypass it). Customer reports stay in private replies and never return records to the model. Overwatch must not use Overlord HR tools, conversation storage, extraction or training traces. Direct Anthropic use is off by default and needs an approved data and retention policy.
diff --git a/overbae/api/overwatch_agent.py b/overbae/api/overwatch_agent.py
index e6d7cf44..1a76b1f8 100644
--- a/overbae/api/overwatch_agent.py
+++ b/overbae/api/overwatch_agent.py
@@ -26,6 +26,7 @@ from overbae.services import overwatch_tools, user_insights
logger = logging.getLogger(__name__)
TOOL_CACHE_SECONDS = 3600
+REPORT_CACHE_SECONDS = 300
# product_usage keeps its own PostHog cache and still reads product rows live.
CACHED_TOOLS = frozenset(
{
@@ -34,6 +35,7 @@ CACHED_TOOLS = frozenset(
"customer_activity",
"customers_at_step",
"model_usage",
+ "project_activity",
}
)
DAYS = {"type": "integer", "minimum": 1, "maximum": 365}
@@ -68,6 +70,20 @@ SCHEMAS["customers_at_step"] = {
"additionalProperties": False,
}
+VIEW = {"enum": ["snapshot", "details"]}
+for name in ("customer_activity", "model_usage"):
+ SCHEMAS[name]["properties"]["view"] = VIEW
+SCHEMAS["project_activity"] = {
+ "type": "object",
+ "properties": {
+ "days": DAYS,
+ "view": VIEW,
+ "rank_by": {"enum": ["calls", "tokens", "growth", "decline"]},
+ },
+ "required": ["days"],
+ "additionalProperties": False,
+}
+
class HasOverwatchServiceToken(BasePermission):
def has_permission(self, request, view):
@@ -101,6 +117,10 @@ def _tool_cache_key(tool: str, arguments: dict) -> str:
# One snapshot per tool and arguments. Hash the query so a customer email is
# not a Redis key, and never include the bearer token.
normalized = dict(arguments)
+ if tool in {"customer_activity", "model_usage", "project_activity"}:
+ normalized["view"] = normalized.get("view", "snapshot")
+ if tool == "project_activity":
+ normalized["rank_by"] = normalized.get("rank_by", "calls")
if tool == "customer_activity":
field = "email" if "email" in normalized else "query"
normalized[field] = " ".join(normalized[field].split())
@@ -117,7 +137,7 @@ def _tool_cache_key(tool: str, arguments: dict) -> str:
sort_keys=True,
).encode()
).hexdigest()
- return f"overwatch:agent:query:{fingerprint}"
+ return f"overwatch:agent:snapshot:{fingerprint}"
class QueryResultSerializer(serializers.Serializer):
@@ -170,7 +190,11 @@ class OverwatchQueryView(APIView):
cursor.execute("SET TRANSACTION READ ONLY")
content, private = overwatch_tools.query(tool, args)
computed_at = timezone.now()
- ttl = 300 if tool in {"customer_activity", "model_usage"} else TOOL_CACHE_SECONDS
+ ttl = (
+ REPORT_CACHE_SECONDS
+ if tool in {"customer_activity", "model_usage", "project_activity"}
+ else TOOL_CACHE_SECONDS
+ )
result = QueryResultSerializer(
{
"content": content,
diff --git a/overbae/services/overwatch_tools.py b/overbae/services/overwatch_tools.py
index 4188cfc5..37e96914 100644
--- a/overbae/services/overwatch_tools.py
+++ b/overbae/services/overwatch_tools.py
@@ -94,13 +94,14 @@ def _private_result(name: str, result: dict[str, Any]) -> str:
def query(tool: str, arguments: dict[str, Any]) -> tuple[str, bool]:
"""Arguments are validated by the internal API before any query executes."""
- if tool in {"customer_activity", "model_usage"}:
+ reports = {
+ "customer_activity": overwatch_usage.customer_activity,
+ "model_usage": overwatch_usage.model_usage,
+ "project_activity": overwatch_usage.project_activity,
+ }
+ if tool in reports:
with user_insights.analytics_read_budget(seconds=10):
- report = (
- overwatch_usage.customer_activity(arguments)
- if tool == "customer_activity"
- else overwatch_usage.model_usage(arguments)
- )
+ report = reports[tool](arguments)
return report, True
handlers = {
"activation_funnel": _activation_funnel,
diff --git a/overbae/services/overwatch_usage.py b/overbae/services/overwatch_usage.py
index b514a485..0ac444df 100644
--- a/overbae/services/overwatch_usage.py
+++ b/overbae/services/overwatch_usage.py
@@ -55,13 +55,15 @@ def _totals(calls):
)
-def _usage(project_ids, days, now):
+def _usage(project_ids, days, now, details):
since = window_start(days)
calls = InferenceCall.objects.filter(project_id__in=project_ids, created_at__lte=now)
current = calls.filter(created_at__gte=since)
totals = _totals(current)
previous = _totals(
- calls.filter(created_at__gte=since - timedelta(days=days), created_at__lt=since)
+ calls.filter(
+ created_at__gte=since - timedelta(days=days), created_at__lte=now - timedelta(days=days)
+ )
)
sources = list(
current.order_by()
@@ -81,16 +83,20 @@ def _usage(project_ids, days, now):
)
.order_by("origin")
)
- models = list(
- current.order_by()
- .values("deployed_model__model_id")
- .annotate(
- calls=Count("pk"),
- succeeded=Count("pk", filter=Q(outcome="succeeded")),
- input_tokens=Sum("prompt_tokens"),
- output_tokens=Sum("completion_tokens"),
+ models = (
+ list(
+ current.order_by()
+ .values("deployed_model__model_id")
+ .annotate(
+ calls=Count("pk"),
+ succeeded=Count("pk", filter=Q(outcome="succeeded")),
+ input_tokens=Sum("prompt_tokens"),
+ output_tokens=Sum("completion_tokens"),
+ )
+ .order_by("-calls", "deployed_model__model_id")[:5]
)
- .order_by("-calls", "deployed_model__model_id")[:5]
+ if details
+ else []
)
last = calls.filter(outcome="succeeded").aggregate(at=Max("created_at"))["at"]
return totals, previous, sources, models, last
@@ -106,14 +112,50 @@ def model_usage(arguments, user=None):
else ProjectMembership.objects.filter(user__is_guest=False)
)
project_ids = memberships.values("project_id")
- totals, previous, sources, models, last = _usage(project_ids, days, now)
- lines = [
- f"Model usage in the last {days} UTC days (today is partial):",
- f"{totals['succeeded']:,} successful / {totals['calls'] - totals['succeeded']:,} unsuccessful recorded calls; {totals['active_days']} active days; {totals['projects']} active projects.",
- f"Recorded tokens: {totals['input_tokens']:,} input / {totals['output_tokens']:,} output (all outcomes).",
- f"Previous {days} UTC days: {previous['succeeded']:,} successful calls; {previous['input_tokens'] + previous['output_tokens']:,} recorded tokens. Previous period contains full days.",
- f"Last successful model call: {last.isoformat() if last else 'none recorded'}.",
- ]
+ totals, previous, sources, models, last = _usage(
+ project_ids, days, now, arguments.get("view") == "details"
+ )
+ tokens = totals["input_tokens"] + totals["output_tokens"]
+ label = _label(user.get_full_name() or user.email, 70) if user else "Model usage"
+ lines = [f"{label} · {since:%d %b}–{now:%d %b %Y} (UTC, today partial)"]
+ if totals["calls"]:
+ lines.extend(
+ [
+ f"{totals['succeeded']:,} successful calls across {totals['projects']} active projects.",
+ f"• {_compact(tokens)} recorded tokens · {totals['active_days']} active days",
+ f"• {100 * totals['succeeded'] / totals['calls']:.1f}% success · {totals['calls'] - totals['succeeded']:,} unsuccessful calls",
+ f"• {_change(totals['succeeded'], previous['succeeded'])}",
+ ]
+ )
+ if not tokens:
+ lines.append("Token counts are unavailable or zero in the retained records.")
+ else:
+ lines.append("No hosted-model calls recorded in this period (0 successful).")
+ if previous["succeeded"]:
+ lines.append(_change(0, previous["succeeded"]))
+ if totals["succeeded"] and sources:
+ dominant = max(sources, key=lambda row: row["succeeded"])
+ share = dominant["succeeded"] / totals["succeeded"] * 100
+ if share >= 50:
+ origin = {
+ "application": "API",
+ "playground": "Playground",
+ "internal": "Internal",
+ "unknown": "Unknown-source",
+ }[dominant["origin"]]
+ lines.append(f"{origin} traffic accounts for {share:.0f}% of successful calls.")
+ lines.append(f"Last successful call: {_when(last)}.")
+ if user:
+ lines.append("Shared-project activity; individual caller attribution is unavailable.")
+ lines.append("Recorded hosted-model activity only; ask ‘show details’ for sources and models.")
+ if arguments.get("view", "snapshot") != "details":
+ return "\n".join(lines)
+ lines.extend(
+ [
+ f"Recorded tokens: {totals['input_tokens']:,} input / {totals['output_tokens']:,} output (all outcomes).",
+ f"Previous matched period: {previous['succeeded']:,} successful calls; {previous['input_tokens'] + previous['output_tokens']:,} recorded tokens.",
+ ]
+ )
source_labels = {
"application": "Application",
"playground": "Playground",
@@ -168,7 +210,7 @@ def model_usage(arguments, user=None):
lines.append("Top models by recorded calls (up to 5):")
for row in models:
line = f"{_label(row['deployed_model__model_id'], 80)}: {row['succeeded']:,} successful / {row['calls'] - row['succeeded']:,} unsuccessful; {row['input_tokens']:,} input / {row['output_tokens']:,} output."
- if len("\n".join(lines)) + len(line) > 2300:
+ if len("\n".join(lines)) + len(line) > 2400:
lines.append("Additional model rows omitted to fit Slack.")
break
lines.append(line)
@@ -186,3 +228,107 @@ def customer_activity(arguments):
return f"Multiple customers match. Reply with the exact email. Showing up to 5 matches:\n{choices}"
user = matches[0]
return f"Customer: {_label(user.email, 254)}\nSigned up: {user.date_joined.date()}\n{model_usage(arguments, user)}"
+
+
+def _compact(value):
+ if value >= 1_000_000:
+ return f"{value / 1_000_000:.2f}m"
+ if value >= 10_000:
+ return f"{value / 1000:.1f}k"
+ return f"{value:,}"
+
+
+def _when(value):
+ return value.strftime("%d %b %Y, %H:%M UTC") if value else "none recorded"
+
+
+def _change(current, previous):
+ if not previous:
+ return "No successful calls in the matched previous period; no percentage comparison."
+ delta = (current - previous) / previous * 100
+ if not delta:
+ return "Successful calls unchanged from the matched previous period."
+ return f"Successful calls {'up' if delta > 0 else 'down'} {abs(delta):.0f}% vs matched previous period ({previous:,})."
+
+
+def project_activity(arguments):
+ """Rank project facts once, independently of how many customers share them."""
+ days, now = arguments["days"], timezone.now()
+ since = window_start(days)
+ previous_end = now - timedelta(days=days)
+ current = Q(created_at__gte=since)
+ previous = Q(created_at__lt=since, created_at__lte=previous_end)
+ succeeded = Q(outcome="succeeded")
+ project_ids = ProjectMembership.objects.filter(user__is_guest=False).values("project_id")
+ rows = (
+ InferenceCall.objects.filter(
+ project_id__in=project_ids,
+ created_at__gte=since - timedelta(days=days),
+ created_at__lte=now,
+ )
+ .order_by()
+ .values("project_id", "project__name")
+ .annotate(
+ successful=Count("pk", filter=current & succeeded),
+ previous=Count("pk", filter=previous & succeeded),
+ tokens=Sum(F("prompt_tokens") + F("completion_tokens"), filter=current, default=0),
+ last=Max("created_at", filter=current & succeeded),
+ )
+ .annotate(change=F("successful") - F("previous"))
+ )
+ rank = arguments.get("rank_by", "calls")
+ if rank == "growth":
+ rows = rows.filter(change__gt=0).order_by("-change", "project_id")
+ elif rank == "decline":
+ rows = rows.filter(change__lt=0).order_by("change", "project_id")
+ elif rank == "tokens":
+ rows = rows.filter(tokens__gt=0).order_by("-tokens", "project_id")
+ else:
+ rows = rows.filter(successful__gt=0).order_by("-successful", "project_id")
+ detail = arguments.get("view", "snapshot") == "details"
+ limit = 5 if detail else 3
+ found = list(rows[: limit + 1])
+ title = {
+ "calls": "Most active projects",
+ "tokens": "Projects using the most tokens",
+ "growth": "Projects with growing usage",
+ "decline": "Projects with declining usage",
+ }[rank]
+ lines = [f"{title} · {since:%d %b}–{now:%d %b %Y} (UTC, today partial)"]
+ lines.append("Project activity is measurable; individual user rankings are unavailable.")
+ if not found:
+ lines.append("No projects match this measure in the retained hosted-model records.")
+ for index, row in enumerate(found[:limit], 1):
+ lines.append(
+ f"{index}. {_label(row['project__name'], 60)} · {row['successful']:,} successful calls · {_compact(row['tokens'])} recorded tokens"
+ )
+ members = list(
+ ProjectMembership.objects.filter(project_id=row["project_id"], user__is_guest=False)
+ .select_related("user")
+ .order_by("user__email")[:3]
+ )
+ names = ", ".join(
+ _label(member.user.get_full_name() or member.user.email, 60) for member in members[:2]
+ )
+ lines.append(
+ f"Members: {names}{' + others' if len(members) > 2 else ''} (not identified callers)."
+ )
+ if rank in {"growth", "decline"} or detail:
+ lines.append(_change(row["successful"], row["previous"]))
+ if detail:
+ lines.append(f"Last successful call in period: {_when(row['last'])}.")
+ if len(found) > limit:
+ lines.append(f"Showing the top {limit}; more projects match.")
+ measure = (
+ "recorded tokens (all outcomes)"
+ if rank == "tokens"
+ else "successful calls"
+ if rank == "calls"
+ else "absolute change in successful calls vs matched previous period"
+ )
+ lines.append(
+ f"Ranked by {measure}; all sources, hosted models only. Zero tokens may mean missing telemetry."
+ )
+ if not detail:
+ lines.append("Ask ‘show details’, ‘who is growing?’ or ‘who is dropping off?’.")
+ return "\n".join(lines)
diff --git a/tests/test_overwatch_customer_usage.py b/tests/test_overwatch_customer_usage.py
index cd04d8d6..e45b2807 100644
--- a/tests/test_overwatch_customer_usage.py
+++ b/tests/test_overwatch_customer_usage.py
@@ -114,7 +114,7 @@ def test_usage_counts_window_sources_tokens_and_models_without_duplicate_members
completion_tokens=100,
)
InferenceCall.objects.filter(pk=older.pk).update(created_at=datetime(2026, 10, 30, tzinfo=UTC))
- response = query({"query": "Usage", "days": 7})
+ response = query({"query": "Usage", "days": 7, "view": "details"})
assert response.status_code == 200
text = response.data["content"]
assert "4 successful" in text and "1 unsuccessful" in text
@@ -122,7 +122,7 @@ def test_usage_counts_window_sources_tokens_and_models_without_duplicate_members
assert "Application: 1 successful" in text
assert "Playground: 1 successful" in text and "Internal: 1 successful" in text
assert "Unknown source: 1 successful" in text
- assert "Previous 7 UTC days: 1 successful" in text
+ assert "Previous matched period: 1 successful" in text
assert "ft-test: 4 successful" in text
assert "individual caller" in text
assert "zero" in text.lower() and "unavailable" in text.lower()
@@ -181,7 +181,7 @@ def test_customer_billing_remains_user_attributed_and_keeps_lifetime_totals(sett
BillingTelemetry.objects.create(
user=other, project=project, amount="-99.00", service="inference-ft-model"
)
- response = query({"email": user.email, "days": 7})
+ response = query({"email": user.email, "days": 7, "view": "details"})
assert response.status_code == 200
text = response.data["content"]
assert "$2.50 spent in window" in text
@@ -190,3 +190,86 @@ def test_customer_billing_remains_user_attributed_and_keeps_lifetime_totals(sett
assert "$12.50 current balance" in text
assert "Subscription: active" in text
assert "$99" not in text
+
+
+def record_calls(project, count, at, tokens=10, outcome="succeeded"):
+ deployed, _ = DeployedModel.objects.get_or_create(
+ project=project, model_id=f"ft-{project.slug}"
+ )
+ rows = [
+ InferenceCall(
+ project=project,
+ deployed_model=deployed,
+ outcome=outcome,
+ prompt_tokens=tokens,
+ completion_tokens=0,
+ source="application",
+ )
+ for _ in range(count)
+ ]
+ InferenceCall.objects.bulk_create(rows)
+ InferenceCall.objects.filter(pk__in=[row.pk for row in rows]).update(created_at=at)
+
+
+def test_project_rankings_use_successful_calls_not_memberships_or_failed_calls():
+ user = make_user(first_name="Avery", last_name="Chen")
+ alpha = make_project(member=user, name="Alpha")
+ beta = make_project(member=user, name="Beta")
+ ProjectMembership.objects.create(project=alpha, user=make_user())
+ now = datetime(2026, 11, 9, 10, tzinfo=UTC)
+ record_calls(alpha, 2, now, tokens=50)
+ record_calls(beta, 3, now)
+ record_calls(alpha, 5, now, outcome="failed")
+ record_calls(make_project(member=make_user(is_guest=True), name="Guest"), 10, now)
+ response = query({"days": 7}, tool="project_activity")
+ assert response.status_code == 200
+ text = response.data["content"]
+ assert text.index("Beta") < text.index("Alpha")
+ assert "Guest" not in text
+ assert "Avery Chen" in text and "not identified callers" in text
+ assert "3 successful" in text and "2 successful" in text
+ assert "individual" in text and "projects" in text
+ assert len(text) < 1400
+ token_rank = query({"days": 7, "rank_by": "tokens"}, tool="project_activity")
+ assert token_rank.status_code == 200
+ assert token_rank.data["content"].index("Alpha") < token_rank.data["content"].index("Beta")
+
+
+def test_snapshot_is_short_with_equal_elapsed_comparison_and_details_on_request():
+ project = make_project(member=make_user())
+ record_calls(project, 4, datetime(2026, 11, 9, 10, tzinfo=UTC), tokens=100)
+ record_calls(project, 2, datetime(2026, 11, 2, 10, tzinfo=UTC))
+ # The unelapsed part of the previous period must not depress the comparison.
+ record_calls(project, 10, datetime(2026, 11, 2, 18, tzinfo=UTC))
+ response = query({"days": 7}, tool="model_usage")
+ assert response.status_code == 200
+ text = response.data["content"]
+ assert "4 successful" in text and "100%" in text
+ assert "matched" in text.lower()
+ assert "ft-" not in text and len(text) < 1000
+ details = query({"days": 7, "view": "details"}, tool="model_usage")
+ assert details.status_code == 200
+ assert "ft-" in details.data["content"]
+ assert "100 input" not in text
+
+
+def test_declining_projects_include_stopped_usage_without_claiming_churn():
+ stopped = make_project(member=make_user(), name="Stopped")
+ growing = make_project(member=make_user(), name="Growing")
+ record_calls(stopped, 3, datetime(2026, 11, 2, 10, tzinfo=UTC))
+ record_calls(growing, 5, datetime(2026, 11, 9, 10, tzinfo=UTC))
+ response = query({"days": 7, "rank_by": "decline"}, tool="project_activity")
+ assert response.status_code == 200
+ text = response.data["content"]
+ assert "Stopped" in text and "Growing" not in text
+ assert "0 successful" in text and "100%" in text
+ assert "churned" not in text.lower()
+
+
+def test_no_calls_does_not_claim_zero_tokens_or_perfect_success():
+ make_project(member=make_user())
+ response = query({"days": 7}, tool="model_usage")
+ assert response.status_code == 200
+ assert "No hosted-model calls" in response.data["content"]
+ assert "100%" not in response.data["content"]
+ assert "0 tokens" not in response.data["content"]