Skip to content

The platform for continuously improving AI agents.

14.2 KB
Raw Blame
"""Credits ledger. Balance = SUM(BillingTelemetry.amount) per user.

Every usage row is one measured provider cost of a project's work, at the provider's price,
charged to the project's owner with what caused it and who started it.
"""

from __future__ import annotations

import logging
from dataclasses import asdict, dataclass, replace
from datetime import datetime
from decimal import Decimal
from typing import Any
from uuid import UUID

from django.db import IntegrityError, transaction
from django.db.models import Count, Q, Sum
from django.utils import timezone

from overbae.models import (
    AssistantThread,
    BillingService,
    BillingTelemetry,
    ExperimentStep,
    FinetuningJob,
    Project,
    User,
)
from overbae.services.billing_provider import get_billing

logger = logging.getLogger(__name__)

SIGNUP_CREDITS_USD = Decimal("50")

# Display/purchase denomination: the ledger stores USD, users buy and see credits.
CREDITS_PER_USD = 100
MIN_TOPUP_USD = 1
MAX_TOPUP_USD = 1000


def credit_report(
    user: User,
    *,
    since: datetime | None,
    observed_at: datetime,
) -> dict[str, Any]:
    window = Q(amount__lt=0) & (Q(timestamp__gte=since) if since is not None else Q())
    rows = list(
        BillingTelemetry.objects.filter(user=user, timestamp__lte=observed_at)
        .values("service")
        .annotate(
            balance=Sum("amount"),
            granted=Sum("amount", filter=Q(amount__gt=0), default=Decimal("0")),
            spent=Sum("amount", filter=Q(amount__lt=0), default=Decimal("0")),
            used=Sum("amount", filter=window, default=Decimal("0")),
        )
        .order_by("service")
    )
    by_service = [
        {"service": row["service"], "spent_credits": -row["used"] * CREDITS_PER_USD}
        for row in rows
        if row["used"]
    ]
    balance = sum((row["balance"] for row in rows), Decimal("0"))
    return {
        "background_paused": get_billing().enabled and balance <= 0,
        "balance_credits": balance * CREDITS_PER_USD,
        "granted_credits": sum((row["granted"] for row in rows), Decimal("0")) * CREDITS_PER_USD,
        "spent_credits": -sum((row["spent"] for row in rows), Decimal("0")) * CREDITS_PER_USD,
        "usage": {
            "spent_credits": -sum((row["used"] for row in rows), Decimal("0")) * CREDITS_PER_USD,
            "by_service": by_service,
        },
    }


# Causes an experiment's steps record as receipts, by receipt kind
# (services/experiments/stages.py).
_STEP_KINDS = {
    "finetune_job": "finetune_job",
    "eval_run": "eval_run",
    "native_evaluation": "native_evaluation",
    "deployed_model": "deployment",
}


@dataclass(frozen=True)
class Cause:
    """What a charge is for: the project whose owner pays, the work that caused the cost,
    and who started it. ``resolve`` reads the payer and the experiment the work belongs to; a
    call priced later carries the payer read when it was answered."""

    project_id: str
    service: str
    kind: str
    id: str
    actor_id: int | None = None
    payer_id: int | None = None
    experiment_id: str | None = None
    run_id: str | None = None
    resolved: bool = False

    @property
    def ref(self) -> str:
        return f"{self.kind}:{self.id}"

    def resolve(self) -> Cause:
        if self.resolved:
            return self
        payer = (
            Project.objects.filter(pk=self.project_id).values_list("owner_id", flat=True).first()
        )
        experiment = run = None
        if self.kind == "assistant_thread":
            experiment = (
                AssistantThread.objects.filter(pk=self.id)
                .values_list("experiment_id", flat=True)
                .first()
            )
        elif self.kind in _STEP_KINDS:
            step = (
                ExperimentStep.objects.filter(
                    receipts__contains=[{"kind": _STEP_KINDS[self.kind], "id": self.id}]
                )
                .values_list("run_id", "run__experiment_id")
                .first()
            )
            if step:
                run, experiment = step
        return replace(
            self,
            payer_id=payer,
            experiment_id=str(experiment) if experiment else None,
            run_id=str(run) if run else None,
            resolved=True,
        )

    def as_dict(self) -> dict[str, Any]:
        return asdict(self.resolve())


def cause(project_id, service: str, kind: str, id, *, actor=None) -> Cause:
    """The cause of work in a project. Nothing is read until a charge needs it."""
    return Cause(
        project_id=str(project_id),
        service=str(service),
        kind=kind,
        id=str(id),
        actor_id=getattr(actor, "pk", actor),
    )


def charge(
    found: Cause,
    usd: Decimal,
    *,
    key: str,
    resource: str,
    quantity: Decimal | None,
    unit: str,
    unit_usd: Decimal | None,
    provider_ref: str = "",
    started_at: datetime | None = None,
    ended_at: datetime | None = None,
    metadata: dict[str, Any] | None = None,
) -> BillingTelemetry | None:
    """Charge one measured provider cost to the project's owner. A repeated ``key`` is a
    no-op. A project with no owner has no one to charge: the cost is ours and named."""
    if usd <= 0:
        return None
    found = found.resolve()
    if found.payer_id is None:
        logger.error(
            "Provider cost with no payer: project %s has no owner, %s absorbed",
            found.project_id,
            key,
        )
        return None
    try:
        with transaction.atomic():
            return BillingTelemetry.objects.create(
                user_id=found.payer_id,
                actor_id=found.actor_id,
                project_id=found.project_id,
                amount=-usd,
                service=found.service,
                cause_kind=found.kind,
                cause_id=found.id,
                experiment_id=found.experiment_id,
                run_id=found.run_id,
                resource=resource[:128],
                quantity=quantity,
                unit=unit,
                unit_usd=unit_usd,
                provider_ref=provider_ref[:255],
                started_at=started_at,
                ended_at=ended_at,
                idempotency_key=key,
                metadata=metadata or {},
            )
    except IntegrityError:
        if BillingTelemetry.objects.filter(idempotency_key=key).exists():
            logger.info("billing ledger idempotent skip key=%s", key)
        else:
            logger.exception("Provider cost was not recorded and is absorbed: %s", key)
        return None


def accrue(
    found: Cause,
    usd: Decimal,
    *,
    key: str,
    resource: str,
    seconds: Decimal,
    provider_ref: str,
    started_at: datetime,
    ended_at: datetime,
    components: dict[str, float],
) -> None:
    """Add a container's new seconds to its one row for this cause, or start that row."""
    found = found.resolve()
    if found.payer_id is None:
        logger.error(
            "Provider cost with no payer: project %s has no owner, %s absorbed",
            found.project_id,
            key,
        )
        return
    row = BillingTelemetry.objects.select_for_update().filter(idempotency_key=key).first()
    if row is None:
        charge(
            found,
            usd,
            key=key,
            resource=resource,
            quantity=seconds,
            unit="second",
            unit_usd=usd / seconds if seconds else None,
            provider_ref=provider_ref,
            started_at=started_at,
            ended_at=ended_at,
            metadata=components,
        )
        return
    row.amount -= usd
    row.quantity = (row.quantity or 0) + seconds
    row.unit_usd = -row.amount / row.quantity if row.quantity else None
    row.ended_at = ended_at
    row.metadata = {
        name: (row.metadata or {}).get(name, 0) + value for name, value in components.items()
    }
    row.save(update_fields=["amount", "quantity", "unit_usd", "ended_at", "metadata"])


def mirror_job_spend(job_id) -> None:
    """A training job's cost is what its ledger rows hold; the job keeps a copy for lists."""
    spent = BillingTelemetry.objects.filter(
        cause_kind="finetune_job", cause_id=str(job_id)
    ).aggregate(total=Sum("amount"))["total"]
    if spent is not None:
        FinetuningJob.objects.filter(pk=job_id).update(
            cost_usd=-spent, cost_synced_at=timezone.now()
        )


def window_spend(rows, since: datetime) -> Decimal | None:
    """USD the rows charged from ``since`` on. A container row grows while its container
    runs, so its part inside the window is taken in proportion to its time there."""
    total, seen = Decimal(0), False
    for amount, started, ended, posted in rows.values_list(
        "amount", "started_at", "ended_at", "timestamp"
    ):
        seen = True
        if started is None or ended is None or ended <= started:
            total += -amount if posted >= since else 0
        elif ended > since:
            inside = (ended - max(started, since)) / (ended - started)
            total += -amount * Decimal(str(inside))
    return total if seen else None


def can_spend(project_id) -> bool:
    """Whether background work of the project runs: its owner has credits left. Work a
    person or agent starts checks the same balance at its start."""
    billing = get_billing()
    if not billing.enabled:
        return True
    owner = Project.objects.filter(pk=project_id).values_list("owner_id", flat=True).first()
    return owner is not None and balance_usd(owner) > 0


def to_credits(amount_usd: Decimal) -> Decimal:
    return (amount_usd * CREDITS_PER_USD).quantize(Decimal("0.01"))


def balance_usd(user: User | int) -> Decimal:
    total = BillingTelemetry.objects.filter(user=user).aggregate(s=Sum("amount"))["s"]
    return total if total is not None else Decimal("0")


def granted_usd(user: User) -> Decimal:
    """Lifetime credits granted (positive rows only) — the usage meters' denominator."""
    total = BillingTelemetry.objects.filter(user=user, amount__gt=0).aggregate(s=Sum("amount"))["s"]
    return total if total is not None else Decimal("0")


def spent_usd(user: User) -> Decimal:
    """Lifetime usage (absolute sum of negative rows)."""
    total = BillingTelemetry.objects.filter(user=user, amount__lt=0).aggregate(s=Sum("amount"))["s"]
    if total is None:
        return Decimal("0")
    return -total


def append_entry(
    *,
    user: User,
    amount: Decimal,
    service: str,
    project_id: UUID | str | None = None,
    idempotency_key: str | None = None,
    metadata: dict[str, Any] | None = None,
) -> BillingTelemetry | None:
    """Insert a ledger row. Duplicate ``idempotency_key`` → no-op (returns None)."""
    try:
        with transaction.atomic():
            return BillingTelemetry.objects.create(
                user=user,
                project_id=project_id,
                amount=amount,
                service=service,
                idempotency_key=idempotency_key,
                metadata=metadata or {},
            )
    except IntegrityError:
        logger.info(
            "billing ledger idempotent skip key=%s user_id=%s",
            idempotency_key,
            user.pk,
        )
        return None


def grant_signup_credits(user: User) -> BillingTelemetry | None:
    return get_billing().grant_signup_credits(user)


def grant_credit_purchase(user: User, amount: Decimal, session_id: str) -> BillingTelemetry | None:
    """Keyed on the Checkout Session, so the return confirmation and the webhook grant once."""
    if amount <= 0:
        return None
    return append_entry(
        user=user,
        amount=amount,
        service=BillingService.PURCHASE,
        idempotency_key=f"topup:{session_id}",
        metadata={"checkout_session_id": session_id},
    )


def account_payload(user: User) -> dict[str, Any]:
    enabled = get_billing().enabled
    balance, spent = balance_usd(user), spent_usd(user)
    return {
        "billing_enabled": enabled,
        "credits_usd": balance,
        "credits_granted_usd": granted_usd(user),
        "credits_spent_usd": spent,
        "balance_credits": to_credits(balance),
        "spent_credits": to_credits(spent),
        "background_paused": enabled and balance <= 0,
    }


def project_credit_report(
    project,
    *,
    since=None,
    before=None,
    experiment=None,
    run=None,
    service=None,
    cause_kind=None,
    cause_id=None,
    offset=0,
    limit=20,
):
    """The project's charges, grouped by what caused them."""
    observed_at = timezone.now()
    query = BillingTelemetry.objects.filter(
        project=project, amount__lt=0, timestamp__lte=observed_at
    )
    filters = {
        "timestamp__gte": since,
        "timestamp__lt": before,
        "experiment_id": experiment,
        "run_id": run,
        "service": service,
        "cause_kind": cause_kind,
        "cause_id": cause_id,
    }
    query = query.filter(**{key: value for key, value in filters.items() if value is not None})
    grouped = (
        query.values("service", "cause_kind", "cause_id", "experiment_id", "run_id")
        .annotate(spent_credits=-Sum("amount") * CREDITS_PER_USD, entries=Count("pk"))
        .order_by("service", "cause_kind", "cause_id", "experiment_id", "run_id")
    )
    total = grouped.count()
    spent = -query.aggregate(amount=Sum("amount", default=Decimal("0")))["amount"] * CREDITS_PER_USD
    groups = [
        {
            **group,
            "experiment_id": str(group["experiment_id"]) if group["experiment_id"] else None,
            "run_id": str(group["run_id"]) if group["run_id"] else None,
        }
        for group in grouped[offset : offset + limit]
    ]
    return {
        "project_id": str(project.pk),
        "observed_at": observed_at,
        "since": since,
        "before": before,
        "spent_credits": spent,
        "groups": groups,
        "total_groups": total,
        "next_offset": offset + limit if offset + limit < total else None,
        "limitations": [
            "A running container's charge grows each minute; a model call whose cost the "
            "provider reports later posts once it is priced.",
            "Storage and compute on Overmind's own servers are included and not charged.",
            "No spending cap: work a person or agent starts needs a balance above zero, and "
            "background work pauses at zero.",
        ],
    }