Skip to content

The platform for continuously improving AI agents.

Improve Overwatch customer lookup and model usage reports (#317)

SB44da9c148684
diff --git a/.agents/skills/backend-architecture/references/auth-and-billing.md b/.agents/skills/backend-architecture/references/auth-and-billing.md
index 66187e90..b3666778 100644
--- a/.agents/skills/backend-architecture/references/auth-and-billing.md
+++ b/.agents/skills/backend-architecture/references/auth-and-billing.md
@@ -28,7 +28,9 @@ 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 five 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.
+- `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.
+- 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.
The app lives in `sales-dashboard/` because the deployment workflow and Pages project use that path. It reuses the Console's `styles.css` (relative `@import`), `public/` (`publicDir`) and `components/ui` (the `@` alias), so keep those primitives free of app-level imports. It keeps the admin token in sessionStorage for 30 minutes and clears legacy localStorage tokens. `bun run dev` proxies `/api` to `SALES_API_PROXY` (default `http://localhost:8000`).
diff --git a/overbae/api/overwatch_agent.py b/overbae/api/overwatch_agent.py
index 15e4d17f..e6d7cf44 100644
--- a/overbae/api/overwatch_agent.py
+++ b/overbae/api/overwatch_agent.py
@@ -8,6 +8,7 @@ import hashlib
import hmac
import json
import logging
+from datetime import timedelta
from django.conf import settings
from django.core.cache import cache
@@ -27,7 +28,13 @@ logger = logging.getLogger(__name__)
TOOL_CACHE_SECONDS = 3600
# product_usage keeps its own PostHog cache and still reads product rows live.
CACHED_TOOLS = frozenset(
- {"activation_funnel", "billing_summary", "customer_activity", "customers_at_step"}
+ {
+ "activation_funnel",
+ "billing_summary",
+ "customer_activity",
+ "customers_at_step",
+ "model_usage",
+ }
)
DAYS = {"type": "integer", "minimum": 1, "maximum": 365}
SCHEMAS = {
@@ -37,12 +44,17 @@ SCHEMAS = {
"required": ["days"],
"additionalProperties": False,
}
- for name in ("activation_funnel", "product_usage", "billing_summary")
+ for name in ("activation_funnel", "product_usage", "billing_summary", "model_usage")
}
SCHEMAS["customer_activity"] = {
"type": "object",
- "properties": {"days": DAYS, "email": {"type": "string", "minLength": 3, "maxLength": 254}},
- "required": ["days", "email"],
+ "properties": {
+ "days": DAYS,
+ "email": {"type": "string", "minLength": 3, "maxLength": 254},
+ "query": {"type": "string", "minLength": 2, "maxLength": 120, "pattern": r"^\S(?:.*\S)?$"},
+ },
+ "required": ["days"],
+ "oneOf": [{"required": ["email"]}, {"required": ["query"]}],
"additionalProperties": False,
}
SCHEMAS["customers_at_step"] = {
@@ -78,7 +90,7 @@ class QuerySerializer(serializers.Serializer):
raise serializers.ValidationError("Invalid query fields.")
try:
validate(attrs["arguments"], SCHEMAS[attrs["tool"]])
- if attrs["tool"] == "customer_activity":
+ if attrs["tool"] == "customer_activity" and "email" in attrs["arguments"]:
serializers.EmailField().run_validation(attrs["arguments"]["email"])
except (ValidationError, serializers.ValidationError):
raise serializers.ValidationError("Invalid query arguments.") from None
@@ -90,12 +102,20 @@ def _tool_cache_key(tool: str, arguments: dict) -> str:
# not a Redis key, and never include the bearer token.
normalized = dict(arguments)
if tool == "customer_activity":
- normalized["email"] = normalized["email"].casefold()
+ field = "email" if "email" in normalized else "query"
+ normalized[field] = " ".join(normalized[field].split())
elif tool == "customers_at_step":
# The handler treats a missing limit as 25; the snapshot must too.
normalized["limit"] = normalized.get("limit", 25)
fingerprint = hashlib.sha256(
- json.dumps({"tool": tool, "arguments": normalized}, sort_keys=True).encode()
+ json.dumps(
+ {
+ "tool": tool,
+ "arguments": normalized,
+ "window_start": user_insights.window_start(arguments["days"]).isoformat(),
+ },
+ sort_keys=True,
+ ).encode()
).hexdigest()
return f"overwatch:agent:query:{fingerprint}"
@@ -107,6 +127,7 @@ class QueryResultSerializer(serializers.Serializer):
as_of = serializers.DateTimeField()
window_days = serializers.IntegerField()
window_start = serializers.DateTimeField()
+ refreshes_at = serializers.DateTimeField()
class OverwatchQueryView(APIView):
@@ -148,20 +169,23 @@ class OverwatchQueryView(APIView):
with connection.cursor() as cursor:
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
result = QueryResultSerializer(
{
"content": content,
"private": private,
"source": "Overmind product/billing records"
+ (" and PostHog aggregates" if tool == "product_usage" else ""),
- "as_of": timezone.now(),
+ "as_of": computed_at,
+ "refreshes_at": computed_at + timedelta(seconds=ttl if result_key else 0),
"window_days": args["days"],
"window_start": user_insights.window_start(args["days"]),
}
)
payload = dict(result.data)
if result_key is not None:
- cache.set(result_key, payload, TOOL_CACHE_SECONDS)
+ cache.set(result_key, payload, ttl)
return Response(payload)
except Exception:
logger.warning("overwatch_service_query_failed")
diff --git a/overbae/services/overwatch_tools.py b/overbae/services/overwatch_tools.py
index aea47f89..4188cfc5 100644
--- a/overbae/services/overwatch_tools.py
+++ b/overbae/services/overwatch_tools.py
@@ -6,7 +6,7 @@ import json
from decimal import Decimal
from typing import Any
-from overbae.services import overwatch_insights, user_insights
+from overbae.services import overwatch_insights, overwatch_usage, user_insights
def _activation_funnel(args: dict[str, Any]) -> dict[str, Any]:
@@ -50,32 +50,6 @@ def _billing_summary(args: dict[str, Any]) -> dict[str, Any]:
}
-def _customer_activity(args: dict[str, Any]) -> dict[str, Any]:
- email = str(args.get("email", "")).strip()[:254]
- days = args["days"]
- user = user_insights.users(user_insights.window_start(days)).filter(email__iexact=email).first()
- if user is None:
- return {"found": False}
- activity = user_insights.user_activity(user, user_insights.window_start(days))
- return {
- "found": True,
- "email": user.email,
- "signed_up_at": user.date_joined.isoformat(),
- "activation_stage": user_insights.stage(user),
- "subscription_status": activity["billing"]["subscription_status"],
- "lifetime_spend_usd": activity["billing"]["spend_usd"],
- "lifetime_topups_usd": activity["billing"]["topups_usd"],
- "current_credit_balance_usd": activity["billing"]["balance_usd"],
- "projects": user.projects,
- "trace_count_in_window": user.spans,
- "last_trace_at": user.last_span_at.isoformat() if user.last_span_at else None,
- "training": activity["training"]["totals"],
- "traces_total": activity["traces"]["total"],
- "inference_calls": activity["inference"]["calls"],
- "evaluations": activity["evaluations"]["total"],
- }
-
-
def _customers_at_step(args: dict[str, Any]) -> dict[str, Any]:
step = args["step"]
if step in user_insights.RESETTABLE_MILESTONE_STEPS:
@@ -100,22 +74,6 @@ def _customers_at_step(args: dict[str, Any]) -> dict[str, Any]:
def _private_result(name: str, result: dict[str, Any]) -> str:
"""Format customer records in-process, without another model request."""
- if name == "customer_activity":
- if not result.get("found"):
- return "No matching customer was found."
- return (
- f"Customer: {result['email']}\n"
- f"Signed up: {result['signed_up_at']}\n"
- f"Milestone: {result['activation_stage']}\n"
- f"Subscription: {result['subscription_status'] or 'None'}\n"
- f"Lifetime spend: ${result['lifetime_spend_usd']}\n"
- f"Lifetime top-ups: ${result['lifetime_topups_usd']}\n"
- f"Credit balance: ${result['current_credit_balance_usd']}\n"
- f"Spans in the selected UTC window: {result['trace_count_in_window']}\n"
- f"Project lifetime totals: {result['traces_total']} traces, "
- f"{result['inference_calls']} model calls, {result['evaluations']} evaluations.\n"
- "Project activity belongs to the customer's projects; it does not identify the actor."
- )
if not result["available"]:
return result["reason"]
rows = []
@@ -136,12 +94,19 @@ 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"}:
+ with user_insights.analytics_read_budget(seconds=10):
+ report = (
+ overwatch_usage.customer_activity(arguments)
+ if tool == "customer_activity"
+ else overwatch_usage.model_usage(arguments)
+ )
+ return report, True
handlers = {
"activation_funnel": _activation_funnel,
"product_usage": _product_usage,
"billing_summary": _billing_summary,
"customers_at_step": _customers_at_step,
- "customer_activity": _customer_activity,
}
if tool == "product_usage":
result = handlers[tool](arguments)
diff --git a/overbae/services/overwatch_usage.py b/overbae/services/overwatch_usage.py
new file mode 100644
index 00000000..b514a485
--- /dev/null
+++ b/overbae/services/overwatch_usage.py
@@ -0,0 +1,188 @@
+"""Private customer lookup and usage reports over retained product records."""
+
+from datetime import UTC, timedelta
+
+from django.db.models import Case, CharField, Count, F, Max, Q, Sum, Value, When
+from django.db.models.functions import TruncDate
+from django.utils import timezone
+
+from overbae.models import (
+ BillingService,
+ BillingTelemetry,
+ DeployedModel,
+ EvalRun,
+ FinetuningJob,
+ InferenceCall,
+ ProjectMembership,
+ Span,
+ Subscription,
+ User,
+)
+from overbae.services.user_insights import window_start
+
+
+def _label(value, limit=100):
+ return " ".join(str(value).split())[:limit]
+
+
+def _matches(arguments):
+ users = User.objects.filter(is_guest=False)
+ search = arguments.get("email", arguments.get("query", "")).strip()
+ if "@" in search:
+ users = users.filter(email__iexact=search)
+ else:
+ for word in search.split():
+ users = users.filter(
+ Q(first_name__icontains=word)
+ | Q(last_name__icontains=word)
+ | Q(email__icontains=word)
+ )
+ return list(
+ users.only("id", "email", "first_name", "last_name", "date_joined").order_by("email")[:6]
+ )
+
+
+def _totals(calls):
+ return calls.aggregate(
+ calls=Count("pk"),
+ succeeded=Count("pk", filter=Q(outcome="succeeded")),
+ input_tokens=Sum("prompt_tokens", default=0),
+ output_tokens=Sum("completion_tokens", default=0),
+ active_days=Count(
+ TruncDate("created_at", tzinfo=UTC), distinct=True, filter=Q(outcome="succeeded")
+ ),
+ projects=Count("project_id", distinct=True, filter=Q(outcome="succeeded")),
+ )
+
+
+def _usage(project_ids, days, now):
+ 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)
+ )
+ sources = list(
+ current.order_by()
+ .annotate(
+ origin=Case(
+ When(source__in=["application", "playground", "internal"], then=F("source")),
+ default=Value("unknown"),
+ output_field=CharField(),
+ )
+ )
+ .values("origin")
+ .annotate(
+ calls=Count("pk"),
+ succeeded=Count("pk", filter=Q(outcome="succeeded")),
+ input_tokens=Sum("prompt_tokens"),
+ output_tokens=Sum("completion_tokens"),
+ )
+ .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"),
+ )
+ .order_by("-calls", "deployed_model__model_id")[:5]
+ )
+ last = calls.filter(outcome="succeeded").aggregate(at=Max("created_at"))["at"]
+ return totals, previous, sources, models, last
+
+
+def model_usage(arguments, user=None):
+ days = arguments["days"]
+ now = timezone.now()
+ since = window_start(days)
+ memberships = (
+ ProjectMembership.objects.filter(user=user)
+ if user
+ 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'}.",
+ ]
+ source_labels = {
+ "application": "Application",
+ "playground": "Playground",
+ "internal": "Internal",
+ "unknown": "Unknown source",
+ }
+ for row in sources:
+ lines.append(
+ f"{source_labels[row['origin']]}: {row['succeeded']:,} successful / {row['calls'] - row['succeeded']:,} unsuccessful; {row['input_tokens'] + row['output_tokens']:,} tokens."
+ )
+ if user:
+ traces = Span.objects.filter(
+ project_id__in=project_ids,
+ parent_span_id__isnull=True,
+ received_at__gte=since,
+ received_at__lte=now,
+ ).count()
+ jobs = FinetuningJob.objects.filter(
+ project_id__in=project_ids, created_at__gte=since, created_at__lte=now
+ ).count()
+ evaluations = EvalRun.objects.filter(
+ project_id__in=project_ids, created_at__gte=since, created_at__lte=now
+ ).count()
+ ready = DeployedModel.objects.filter(
+ project_id__in=project_ids, status=DeployedModel.Status.READY
+ ).count()
+ ledger = BillingTelemetry.objects.filter(user=user, timestamp__lte=now).aggregate(
+ balance=Sum("amount", default=0),
+ lifetime_spend=Sum(-F("amount"), filter=Q(amount__lt=0), default=0),
+ lifetime_topups=Sum(
+ "amount", filter=Q(amount__gt=0, service=BillingService.STRIPE_TOPUP), default=0
+ ),
+ spend=Sum(-F("amount"), filter=Q(amount__lt=0, timestamp__gte=since), default=0),
+ )
+ subscription = (
+ Subscription.objects.filter(user=user).values_list("status", flat=True).first()
+ )
+ lines.extend(
+ [
+ f"In this window: {traces:,} root traces, {jobs} training jobs started, {evaluations} evaluations started. Ready deployments now: {ready}.",
+ f"User billing: ${ledger['spend']:.2f} spent in window; ${ledger['balance']:.2f} current balance.",
+ f"${ledger['lifetime_spend']:.2f} lifetime spend; ${ledger['lifetime_topups']:.2f} lifetime top-ups. Subscription: {subscription or 'none'}.",
+ ]
+ )
+ lines.extend(
+ [
+ "Calls belong to shared projects, not an identified individual caller. Application calls indicate API usage; they do not prove production use.",
+ "Tokens cover retained hosted-model calls only, not external models or training. Historical zero token fields may mean unavailable telemetry.",
+ ]
+ )
+ if models:
+ 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:
+ lines.append("Additional model rows omitted to fit Slack.")
+ break
+ lines.append(line)
+ return "\n".join(lines)
+
+
+def customer_activity(arguments):
+ matches = _matches(arguments)
+ if not matches:
+ return "No matching customer was found. Try their full name or exact email."
+ if len(matches) > 1:
+ choices = "\n".join(
+ f"{_label(user.get_full_name(), 60)}: {_label(user.email, 254)}" for user in matches[:5]
+ )
+ 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)}"
diff --git a/tests/test_overwatch_customer_usage.py b/tests/test_overwatch_customer_usage.py
new file mode 100644
index 00000000..cd04d8d6
--- /dev/null
+++ b/tests/test_overwatch_customer_usage.py
@@ -0,0 +1,192 @@
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from django.core.cache import cache
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
+from factories import make_project, make_user
+from rest_framework.test import APIClient
+
+from overbae.models import (
+ BillingTelemetry,
+ DeployedModel,
+ InferenceCall,
+ ProjectMembership,
+ Subscription,
+)
+
+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("measured-facts")]
+URL = "/api/internal/overwatch/agent/query/"
+
+
[email protected](autouse=True)
+def _sandbox(settings):
+ settings.SANDBOX_URL = "http://sandbox.test"
+ settings.SANDBOX_TOKEN = "analytics-test"
+
+
[email protected](autouse=True)
+def configured(settings, time_machine):
+ settings.OVERWATCH_SERVICE_TOKEN = "usage-test-token"
+ settings.SALES_DASHBOARD_TOKEN = "dashboard-test-token"
+ cache.clear()
+ time_machine.move_to(datetime(2026, 11, 9, 12, tzinfo=UTC), tick=False)
+
+
+def query(arguments, tool="customer_activity"):
+ client = APIClient()
+ client.credentials(HTTP_AUTHORIZATION="Bearer usage-test-token")
+ return client.post(URL, {"tool": tool, "arguments": arguments}, format="json")
+
+
[email protected]("search", ["Chandra", "chandra PATEL", "example.com", "[email protected]"])
+def test_name_full_name_domain_and_email_resolve_without_lifetime_report(search):
+ make_user(email="[email protected]", first_name="Chandra", last_name="Patel")
+ make_user(email="[email protected]", first_name="Chandra", is_guest=True)
+ with CaptureQueriesContext(connection) as queries:
+ response = query({"query": search, "days": 7})
+ assert response.status_code == 200
+ assert response.data["private"] is True
+ assert "[email protected]" in response.data["content"]
+ assert "[email protected]" not in response.data["content"]
+ assert "0 successful" in response.data["content"]
+ # Lookup plus a bounded report, not the dashboard's whole lifetime history.
+ assert len([q for q in queries if q["sql"].startswith("SELECT")]) <= 18
+
+
+def test_ambiguous_name_lists_bounded_candidates_and_never_picks_a_customer():
+ for index in range(8):
+ make_user(email=f"chandra{index}@example.com", first_name="Chandra")
+ response = query({"query": "Chandra", "days": 7})
+ assert response.status_code == 200
+ text = response.data["content"]
+ assert "Multiple customers" in text and "exact email" in text
+ assert text.count("@example.com") == 5
+ assert "successful" not in text
+
+
+def test_exact_email_never_falls_back_to_another_customer():
+ make_user(email="[email protected]")
+ response = query({"email": "[email protected]", "days": 7})
+ assert response.status_code == 200
+ assert "No matching customer" in response.data["content"]
+ assert "somebody" not in response.data["content"]
+
+
+ "arguments",
+ [
+ {"query": " ", "days": 7},
+ {"query": "x", "days": 7},
+ {"query": "person", "email": "[email protected]", "days": 7},
+ {"query": "person", "days": 7, "sql": "SELECT *"},
+ ],
+)
+def test_lookup_arguments_remain_bounded(arguments):
+ assert query(arguments).status_code == 400
+
+
+def test_usage_counts_window_sources_tokens_and_models_without_duplicate_memberships():
+ user = make_user(email="[email protected]", first_name="Usage")
+ project = make_project(member=user)
+ ProjectMembership.objects.create(project=project, user=make_user())
+ deployed = DeployedModel.objects.create(project=project, model_id="ft-test", status="ready")
+ for source, outcome, prompt, completion in [
+ ("application", "succeeded", 100, 20),
+ ("playground", "succeeded", 40, 10),
+ ("internal", "succeeded", 30, 5),
+ ("unknown", "succeeded", 0, 0),
+ ("application", "failed", 10, 0),
+ ]:
+ InferenceCall.objects.create(
+ project=project,
+ deployed_model=deployed,
+ source=source,
+ outcome=outcome,
+ prompt_tokens=prompt,
+ completion_tokens=completion,
+ )
+ older = InferenceCall.objects.create(
+ project=project,
+ deployed_model=deployed,
+ source="application",
+ prompt_tokens=900,
+ completion_tokens=100,
+ )
+ InferenceCall.objects.filter(pk=older.pk).update(created_at=datetime(2026, 10, 30, tzinfo=UTC))
+ response = query({"query": "Usage", "days": 7})
+ assert response.status_code == 200
+ text = response.data["content"]
+ assert "4 successful" in text and "1 unsuccessful" in text
+ assert "180 input / 35 output" in text
+ 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 "ft-test: 4 successful" in text
+ assert "individual caller" in text
+ assert "zero" in text.lower() and "unavailable" in text.lower()
+ global_response = query({"days": 7}, tool="model_usage")
+ assert global_response.status_code == 200
+ assert global_response.data["private"] is True
+ assert "4 successful" in global_response.data["content"]
+ assert "[email protected]" not in global_response.data["content"]
+
+
+def test_usage_omits_guest_only_projects_and_keeps_zero_activity_explicit():
+ guest_project = make_project(member=make_user(is_guest=True))
+ deployed = DeployedModel.objects.create(project=guest_project, model_id="ft-guest")
+ InferenceCall.objects.create(project=guest_project, deployed_model=deployed, prompt_tokens=999)
+ response = query({"days": 7}, tool="model_usage")
+ assert response.status_code == 200
+ assert "0 successful" in response.data["content"]
+ assert "ft-guest" not in response.data["content"]
+ assert "999" not in response.data["content"]
+
+
+def test_customer_snapshot_is_reused_briefly_and_not_across_utc_midnight(time_machine):
+ make_user(email="[email protected]")
+ first = query({"query": "fresh", "days": 7})
+ assert first.status_code == 200
+ time_machine.shift(timedelta(seconds=30))
+ cached = query({"query": "fresh", "days": 7})
+ assert cached.data["as_of"] == first.data["as_of"]
+ assert cached.data["refreshes_at"] > cached.data["as_of"]
+ time_machine.shift(timedelta(minutes=6))
+ assert query({"query": "fresh", "days": 7}).data["as_of"] != first.data["as_of"]
+ time_machine.move_to(datetime(2026, 11, 9, 23, 59, tzinfo=UTC), tick=False)
+ previous_day = query({"query": "fresh", "days": 7})
+ time_machine.shift(timedelta(minutes=2))
+ today = query({"query": "fresh", "days": 7})
+ assert today.data["window_start"] != previous_day.data["window_start"]
+
+
+def test_customer_billing_remains_user_attributed_and_keeps_lifetime_totals(settings):
+ settings.STRIPE_SECRET_KEY = ""
+ user = make_user(email="[email protected]")
+ other = make_user()
+ project = make_project(member=user)
+ ProjectMembership.objects.create(project=project, user=other)
+ Subscription.objects.create(user=user, status="active")
+ BillingTelemetry.objects.create(
+ user=user, project=project, amount="-2.50", service="inference-ft-model"
+ )
+ BillingTelemetry.objects.create(
+ user=user, project=project, amount="20.00", service="stripe-topup"
+ )
+ old = BillingTelemetry.objects.create(
+ user=user, project=project, amount="-5.00", service="inference-ft-model"
+ )
+ BillingTelemetry.objects.filter(pk=old.pk).update(timestamp=datetime(2026, 10, 1, tzinfo=UTC))
+ BillingTelemetry.objects.create(
+ user=other, project=project, amount="-99.00", service="inference-ft-model"
+ )
+ response = query({"email": user.email, "days": 7})
+ assert response.status_code == 200
+ text = response.data["content"]
+ assert "$2.50 spent in window" in text
+ assert "$7.50 lifetime spend" in text
+ assert "$20.00 lifetime top-ups" in text
+ assert "$12.50 current balance" in text
+ assert "Subscription: active" in text
+ assert "$99" not in text