Skip to content

The platform for continuously improving AI agents.

Honest billing: every provider cost on the owner's ledger, by cause (#373)

Freyam Mehta2f0012d3aade
diff --git a/.agents/skills/backend-architecture/references/assistant.md b/.agents/skills/backend-architecture/references/assistant.md
index 4339ce2c..158b2f81 100644
--- a/.agents/skills/backend-architecture/references/assistant.md
+++ b/.agents/skills/backend-architecture/references/assistant.md
@@ -12,7 +12,7 @@ The Console's assistant is a second author beside a customer's coding agent, and
- A message is delivered with `threads.brief` (`describe.brief`): the flow, the agent's notes, the runs, and for the first versions the flow pins (`describe.BRIEF_DATASETS`) `threads.dataset_brief`: the dataset's intent, the linked capability's contract, the split sibling, its pipeline, the version's `data/<cell>.parquet` path, `fit`, exact `duplicate_rows` and a column profile (`store.frame_profile`, cached per frame). It is attached again only when it changed or a summary replaced the message that carried it.
- When a reply's prompt passes `ASSISTANT_COMPACT_TOKENS`, the turn appends a `summary` of all but the last `COMPACT_KEEP` events. A model call reads the newest summary and the events after it; the transcript keeps everything. The cut never separates a tool call from its result.
- Stop sets `stop_requested`, drops queued messages and stops the conversation's kernel at once (`tasks/assistant.stop_kernel`), so a cell that runs answers. The turn sees the flag at its next step. Jobs the turn started continue.
-- Tools run with the project access of the newest message's sender, checked before each model call. The project's `owner` pays (gate and charges): a turn of a project without one fails. A reply and its charge are saved in one transaction; billing details are under Workspaces.
+- Tools run with the project access of the newest message's sender, checked before each model call. The project's `owner` pays (gate and charges): a turn of a project without one fails. Its model calls are charged by the model meter (`references/auth-and-billing.md`); workspace billing is under Workspaces.
## Tools
diff --git a/.agents/skills/backend-architecture/references/auth-and-billing.md b/.agents/skills/backend-architecture/references/auth-and-billing.md
index d5aa8b0f..59872588 100644
--- a/.agents/skills/backend-architecture/references/auth-and-billing.md
+++ b/.agents/skills/backend-architecture/references/auth-and-billing.md
@@ -15,11 +15,14 @@ Tenancy is project-scoped (`User` ↔ `Project` through `ProjectMembership`), wi
## Billing
-- Billing is credits only. Ledger charges always run. A project's `owner` (its creator; the claiming account for a guest project; never removable as a member) pays for the assistant's model calls (`assistant`) and its workspace sandbox (`workspace`): backend-architecture `references/assistant.md`. Remaining-credit 402s, the $50 signup `grant` and Stripe Checkout apply only when `STRIPE_SECRET_KEY` is set (`services/billing_provider.py`); otherwise spend is recorded and shown, and gates and grants are no-ops.
+- Billing is credits only (100 = $1; USD only at Checkout). Ledger charges always run. A project's `owner` (its creator; the claiming account for a guest project; never removable as a member) pays for all the project's work, at the provider's price with no markup. Each usage row (`BillingTelemetry`) is one measured provider cost: `billing_ledger.Cause` (project, service, cause kind and id, actor; experiment and run from the cause's step receipt or assistant thread), resource, quantity × unit price, provider ref. Every usage row recorded since migration 0078 has a project; a deleted project's id stays on it (no FK constraint). Older usage rows without a project keep a null one. Remaining-credit 402s, the $50 signup `grant` and Stripe Checkout apply only when `STRIPE_SECRET_KEY` is set (`services/billing_provider.py`); otherwise spend is recorded and shown, and gates and grants are no-ops.
+- Model calls: every answered OpenRouter request (`call_llm`, tools, streams, Jev `post_request`, the gateway proxies) goes through `services/model_meter.settle`, keyed `openrouter:<generation id>`, at `usage.cost`; a missing cost is priced later from `/generation` (`tasks/billing.price_generation`). The caller sets the cause with `model_meter.billed(cause)`; pool threads take it through `model_meter.carried`. A call with no cause logs an error and is absorbed. A request that times out after it was sent has no generation id and is absorbed.
+- Modal compute: each container that does customer work reports to the `overmind-container-meter` Dict once a minute (`modal_shared/container_meter.py`: GPU type × count, the greater of requested and used CPU and memory, request seconds per billing ref). `tasks/billing.collect_container_meters` (beat, 60 s) charges new seconds at Modal's live rates; a shared container splits by request seconds and idle time goes to the ref it served last. One row per container and ref grows while it runs. Refs: `finetune_job`, `training_run`, `training_preparation` (charged to the first job that used it), `base_model` (the job that asked first), `served_model` (adapter or model name; `dedicated/<id>` for dedicated), `decision_weights`, `native_evaluation`, `decision_performance`, `eval_run` (the `x-overmind-billing-ref` header). Gateways (`InferenceAPIServer`, `RegisterAPIServer`) and the LoRA pool snapshot boot during training carry no ref and are absorbed. Workspace sandboxes keep Modal's own measured cost (`references/assistant.md`).
+- Gates: work a person or agent starts calls `credit_gate.require_credits(project)`: the owner's balance must be above zero; a negative balance is allowed. Background scoring, signals, trajectories and trigger sends check `billing_ledger.can_spend` and wait at zero ("Paused: credits needed"); running work finishes and is charged. Storage and compute on our own AWS (pipelines, OCR, Celery) are included, not metered.
+- `tasks/billing.check_provider_bills` (daily, read-only) compares the ledger with Modal's billing report and this environment's OpenRouter key usage and logs an error past 2%.
- Money in is a `grant` (free: signup, promotions, `manage.py grant_credits`) or a `purchase` (a paid live Checkout session). A purchase is keyed `topup:<session id>` and lands from whichever comes first: `POST /api/billing/topup/confirm/` when the buyer returns from Checkout, or the webhook for payment methods that settle later (`services/credit_purchases.py`). The webhook endpoint's events live in `WEBHOOK_EVENTS`; `manage.py sync_stripe_webhook --url <endpoint>` applies them to Stripe.
-- Native-agent model choice and funding belong to the coding-agent environment. Training, evaluation and serving keep their own billing.
+- Native-agent model choice and funding belong to the coding-agent environment.
- Compute estimates use live provider rates with fetch timestamps (`services/provider_pricing.py`: Modal workspace rates, cached 300 s when current and 30 s when unavailable, no static fallback; `compute_costs.py` and the forecasts call it). They never create ledger charges. One quote uses one rate snapshot. Chat-training cost estimates are the exception: they use the fixed `_MODAL_H100_USD_PER_SECOND` in `finetuning_pricing.py`.
-- Modal training charges use deduplicated worker usage receipts and recorded hardware, never the delay before the collector notices completion. Missing usage stays unmeasured; historical ledger entries are not rewritten.
## Overwatch (internal insights)
diff --git a/.agents/skills/backend-architecture/references/experiments.md b/.agents/skills/backend-architecture/references/experiments.md
index d526fd5f..cddc6e23 100644
--- a/.agents/skills/backend-architecture/references/experiments.md
+++ b/.agents/skills/backend-architecture/references/experiments.md
@@ -21,7 +21,7 @@ An experiment is a saved flow of stages with its own conversation. The Console,
## The experiment's agent
- Its conversation is the experiment's `AssistantThread`; every conversation is one, and a dataset page has none. `records.dataset_links` gives each dataset the experiment that made it (a stage whose output version appeared during the stage) and those that read it; an experiment that pins a dataset blocks its delete. The brief (`describe.brief`) carries the flow, its problems and the newest runs; the experiment tools are in `tools.CATALOG_TOOLS`, so the assistant and an MCP client call the same tools.
-- When a top-level run ends, `operator.run_ended` queues a notice (`AssistantInput.origin=run`) as the run's starter, and the turn reads it as the platform's words. The agent starts at most `runs.AGENT_RUNS` runs (3) per person's message or trigger send, and while no person is in the loop none once a trigger's `max_spend_usd` is reached by `describe.spend` (measured costs only: agent calls, training charges, evaluation answers; workspace time and judging are named as not measured). A run the agent started stops the deployments it made when it ends, unless one became a capability's active model.
+- When a top-level run ends, `operator.run_ended` queues a notice (`AssistantInput.origin=run`) as the run's starter, and the turn reads it as the platform's words. The agent starts at most `runs.AGENT_RUNS` runs (3) per person's message or trigger send, and while no person is in the loop none once a trigger's `max_spend_credits` is reached by `describe.spend` (the ledger rows charged to the experiment; workspace time is the project's and named as not attributed). A run the agent started stops the deployments it made when it ends, unless one became a capability's active model.
- A person's save (Console or MCP) marks the settings it set on each node as `protected`. The agent's save that changes one is refused (`ProtectedSettingError`, MCP `protected_setting`) and logged as a `proposal` event; `records.resolve_proposal` applies it as the person's own revision, or dismisses it.
- `Experiment.notes` holds the agent's notes, written with `revise_experiment` `notes` and shown read-only in the Console.
- Your system (`system` kind, `services/experiments/system.py`): the stage waits on a `system_outputs` receipt; `overmind run` reads `GET /api/experiment-steps/<id>/rows/` and posts `outputs/`, which imports the rows with a `_overmind_output` column into the step's own dataset (`uuid5(step, "outputs")`, so the input's active version stays; provenance: step, label, commit) and replaces the receipt with the import's run. The same outputs again replay that import, also after the stage moved on. A final holdout is refused. Evaluate scores it with a `recorded` target, whose `recorded_output` reads `_overmind_output`.
diff --git a/.agents/skills/backend-architecture/references/serving.md b/.agents/skills/backend-architecture/references/serving.md
index 68136fc2..a6f1017d 100644
--- a/.agents/skills/backend-architecture/references/serving.md
+++ b/.agents/skills/backend-architecture/references/serving.md
@@ -10,7 +10,7 @@
## Dedicated deployments
-A ready `DeployedModel` has at most one live `DedicatedDeployment` on the private `overmind-dedicated` app. Bases where SGLang won the sentence bench use `{gpu}_sglang_dedicated` (`lmsysorg/sglang:v0.5.22`) and fold the LoRA into a local checkpoint before launch. Gemma 4, Muse, Qwen3-Coder, and Llama stay on `{gpu}_vllm_dedicated` (`vllm/vllm-openai:v0.33.0`), which still snapshots the slept engine. SGLang containers do not; they open the port forward once the server is healthy. The shared inference pool runs vLLM 0.33.0. Bases where the adapter bake-off measured a higher SGLang tok/s use `{gpu}_sglang_lora` (`lmsysorg/sglang:v0.5.22`) with runtime LoRA and no GPU snapshot. LFM3 uses `{gpu}_sglang_lfm3_lora` (`lmsysorg/sglang:dev-lfm3`). A snapshot captured on v0.30.0 does not restore onto v0.33.0; the next boot captures a new one. Engine choice is internal; MCP start, stop, and `run_inference` are unchanged. The menu is every GPU at or above the memory floor, including H100 whenever A100-80GB fits. Serverless `select_gpu` still skips H100. Chat shapes are `lora_bf16` and `merged_fp8`. Decision deployments use the same `{gpu}_vllm_dedicated` class and `POST /v1/systemone`. They report latency only. Serverless decision calls stay on `DecisionEndpoint` in the model's decision-serving app, which boots vLLM 0.33.0 and posts `/v1/systemone` in the container. One artifact still owns that container. A catalog base with no artifact is the same class with `base_repo` set and no LoRA. Speed comes from `overbae/modal/serving_benchmarks.json` (one bench per base, shape, and GPU); a missing cell stays unmeasured. The hourly price is the live Modal GPU rate plus that worker's CPU and memory (100 credits = $1); a missing rate refuses start. `min_containers` is the replica floor, `scaledown_window` is the idle timeout, and scale-up is demand up to `max_containers` (at most 8). Chat vLLM stores the KV cache in FP8. The sequence cap is how many full-context sequences fit on that GPU, at most 32; a lower cap is also that container's Modal input target. The 15-second deployment controller meters whole minutes of running replicas at the snapshotted rate and stops the deployment when billing is on and the balance cannot cover the next minute. Zero replicas cost nothing. Stopping drains the runtime with a zero replica floor while retaining the saved GPU and scaling configuration for restart; the Console joins Configure GPU and Start/Stop, and MCP uses the same start/stop services. A dedicated vLLM LoRA is applied while `{gpu}_vllm_dedicated` reads the base shards. Those shards are symlinked into the serve directory, not copied. An SGLang LoRA is written out as a folded checkpoint on container disk, with the same delta, and the server reads that directory. Dedicated chat turns thinking off on every request. Auto tool choice leaves parallel calls on unless the request disables them. A required or named tool choice is one call unless the request sets parallel_tool_calls. Gemma 4 and Muse constrain that choice to their native tool-call syntax, because their parsers skip JSON guided decoding. gpt-oss stops a required or named choice after one call. A harmony call left in the message text is returned as that tool call. tool_choice none omits the tool list. SGLang launch passes that family's tool parser, mapping openai to gpt-oss, llama3_json to llama3, and muse_glimmer to muse. That name is separate from the serverless `{gpu}_vllm` global, because Modal loads the class by module attribute. That container sleeps the loaded engine and Modal snapshots it; later replicas of the same deployment wake the snapshot. A chat or decision request connects to the container the controller already scaled; it does not call `update_autoscaler` or reread the base manifest. Dedicated chat looks up the worker once, then posts to the port forward on that container. A parametrized web endpoint cannot accept POST. Shared inference still uses the `infer` RPC. Chat completions with `stream: true` flush each server-sent event. `run_inference` and the inference-request job still wait for the finished reply, because a tool result has no open token stream. Gateway ids `dedicated/<trained model id>` skip `inference-ft-model` charges. The capability alias stays on the shared active model. The Console lists each model's current dedicated deployment and opens it on that model's inference page. MCP tools are `list_dedicated_gpus`, `start_dedicated_deployment`, `update_dedicated_deployment`, and `stop_dedicated_deployment`; `run_inference` accepts `dedicated/<trained model id>`. `seed_demo` does not create a live dedicated row.
+A ready `DeployedModel` has at most one live `DedicatedDeployment` on the private `overmind-dedicated` app. Bases where SGLang won the sentence bench use `{gpu}_sglang_dedicated` (`lmsysorg/sglang:v0.5.22`) and fold the LoRA into a local checkpoint before launch. Gemma 4, Muse, Qwen3-Coder, and Llama stay on `{gpu}_vllm_dedicated` (`vllm/vllm-openai:v0.33.0`), which still snapshots the slept engine. SGLang containers do not; they open the port forward once the server is healthy. The shared inference pool runs vLLM 0.33.0. Bases where the adapter bake-off measured a higher SGLang tok/s use `{gpu}_sglang_lora` (`lmsysorg/sglang:v0.5.22`) with runtime LoRA and no GPU snapshot. LFM3 uses `{gpu}_sglang_lfm3_lora` (`lmsysorg/sglang:dev-lfm3`). A snapshot captured on v0.30.0 does not restore onto v0.33.0; the next boot captures a new one. Engine choice is internal; MCP start, stop, and `run_inference` are unchanged. The menu is every GPU at or above the memory floor, including H100 whenever A100-80GB fits. Serverless `select_gpu` still skips H100. Chat shapes are `lora_bf16` and `merged_fp8`. Decision deployments use the same `{gpu}_vllm_dedicated` class and `POST /v1/systemone`. They report latency only. Serverless decision calls stay on `DecisionEndpoint` in the model's decision-serving app, which boots vLLM 0.33.0 and posts `/v1/systemone` in the container. One artifact still owns that container. A catalog base with no artifact is the same class with `base_repo` set and no LoRA. Speed comes from `overbae/modal/serving_benchmarks.json` (one bench per base, shape, and GPU); a missing cell stays unmeasured. The hourly price is the live Modal GPU rate plus that worker's CPU and memory (100 credits = $1); a missing rate refuses start. `min_containers` is the replica floor, `scaledown_window` is the idle timeout, and scale-up is demand up to `max_containers` (at most 8). Chat vLLM stores the KV cache in FP8. The sequence cap is how many full-context sequences fit on that GPU, at most 32; a lower cap is also that container's Modal input target. The container meter charges its containers (`references/auth-and-billing.md`); the 15-second controller reads `accrued_credits` from the ledger and stops the deployment when billing is on and the owner's balance cannot cover the next minute at the snapshotted rate. Zero replicas cost nothing. Stopping drains the runtime with a zero replica floor while retaining the saved GPU and scaling configuration for restart; the Console joins Configure GPU and Start/Stop, and MCP uses the same start/stop services. A dedicated vLLM LoRA is applied while `{gpu}_vllm_dedicated` reads the base shards. Those shards are symlinked into the serve directory, not copied. An SGLang LoRA is written out as a folded checkpoint on container disk, with the same delta, and the server reads that directory. Dedicated chat turns thinking off on every request. Auto tool choice leaves parallel calls on unless the request disables them. A required or named tool choice is one call unless the request sets parallel_tool_calls. Gemma 4 and Muse constrain that choice to their native tool-call syntax, because their parsers skip JSON guided decoding. gpt-oss stops a required or named choice after one call. A harmony call left in the message text is returned as that tool call. tool_choice none omits the tool list. SGLang launch passes that family's tool parser, mapping openai to gpt-oss, llama3_json to llama3, and muse_glimmer to muse. That name is separate from the serverless `{gpu}_vllm` global, because Modal loads the class by module attribute. That container sleeps the loaded engine and Modal snapshots it; later replicas of the same deployment wake the snapshot. A chat or decision request connects to the container the controller already scaled; it does not call `update_autoscaler` or reread the base manifest. Dedicated chat looks up the worker once, then posts to the port forward on that container. A parametrized web endpoint cannot accept POST. Shared inference still uses the `infer` RPC. Chat completions with `stream: true` flush each server-sent event. `run_inference` and the inference-request job still wait for the finished reply, because a tool result has no open token stream. The capability alias stays on the shared active model. The Console lists each model's current dedicated deployment and opens it on that model's inference page. MCP tools are `list_dedicated_gpus`, `start_dedicated_deployment`, `update_dedicated_deployment`, and `stop_dedicated_deployment`; `run_inference` accepts `dedicated/<trained model id>`. `seed_demo` does not create a live dedicated row.
## Workers
@@ -46,4 +46,4 @@ MCP `run_inference` and REST `POST /api/deployed-models/{id}/inference/` (chat o
Dedicated chat startup telemetry is collected by `services/dedicated_progress.py` after the controller transaction. It discovers container IDs from the deployment-specific served model name, filters app logs and journal receipts to those containers, and stores bounded, allowlisted startup messages in an `OperationalRun` keyed by probe attempt. REST and MCP expose `startup`; Console fills whole blocks by observed startup milestones in the endpoint header; detailed receipts and stage-local counters remain available through REST and MCP. Reads never wake a GPU; missing telemetry remains unavailable.
-Inference metrics include `dedicated_usage` for the selected period, independent of the request traffic-source filter. It sums project/model-scoped dedicated ledger entries in credits, derives billed GPU-hours only where every entry records replica-minutes, and groups spend by billing timestamp and GPU. It is not per-request estimated serving cost or a CPU/memory resource split.
+Inference metrics include `dedicated_usage` for the selected period, independent of the request traffic-source filter. It sums the deployment's container rows in credits, derives GPU-hours only where every row records GPU seconds, and groups spend by row timestamp and resource. Model `cost` is the serving containers' ledger total; no single request has a cost of its own.
diff --git a/frontend/src/components/billing/billing-ledger-table.tsx b/frontend/src/components/billing/billing-ledger-table.tsx
index 541fbea3..c233930e 100644
--- a/frontend/src/components/billing/billing-ledger-table.tsx
+++ b/frontend/src/components/billing/billing-ledger-table.tsx
@@ -1,5 +1,6 @@
import { type ReactNode, useMemo, useState } from "react";
+import { Link } from "@tanstack/react-router";
import type { ColumnDef } from "@tanstack/react-table";
import { CreditsAmount } from "@/components/ui/credits";
@@ -7,27 +8,107 @@ import { DataTable } from "@/components/ui/data-table";
import { DateTime } from "@/components/ui/datetime";
import { EmptyState } from "@/components/ui/empty-state";
import { Icon } from "@/components/ui/icons";
-import { useBillingLedgerQuery, useCommercialBilling } from "@/hooks/use-billing-account";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import {
+ type LedgerFilters,
+ useBillingLedgerQuery,
+ useCommercialBilling,
+} from "@/hooks/use-billing-account";
+import { useExperimentsQuery } from "@/hooks/use-experiments";
+import { useProjectsList } from "@/hooks/use-projects";
import { PROSE, TITLE } from "@/lib/typography";
-import { cn } from "@/lib/utils";
+import { cn, formatOvermindCredits } from "@/lib/utils";
import type { BillingTelemetry } from "@/openapi";
const PAGE_SIZE = 10;
+const ALL = "all";
-function amountCell(amount: string): { node: ReactNode; className: string } {
- const n = Number(amount);
- if (!Number.isFinite(n)) return { className: "text-foreground", node: amount };
+const SERVICES = [
+ ["finetuning-job", "Training"],
+ ["evaluation", "Evaluation"],
+ ["scoring", "Scoring"],
+ ["inference", "Inference"],
+ ["inference-ft-model", "Fine-tuned inference"],
+ ["dedicated-inference", "Dedicated inference"],
+ ["assistant", "Assistant"],
+ ["workspace", "Assistant workspace"],
+] as const;
+
+const CAUSES: Record<string, string> = {
+ api_key: "API key",
+ assistant_thread: "Assistant",
+ capability: "Capability",
+ decision_performance: "Decision performance",
+ dedicated_deployment: "Dedicated deployment",
+ deployed_model: "Deployed model",
+ eval_run: "Evaluation run",
+ finetune_job: "Training job",
+ native_evaluation: "Decision evaluation",
+ signals: "Signals",
+ span: "Span",
+ trace: "Trace",
+ training_preparation: "Training preparation",
+ user: "Console",
+ workspace_sandbox: "Workspace",
+};
+
+function amountCell(credits: number): { node: ReactNode; className: string } {
const value = (
<>
- {n > 0 ? "+" : n < 0 ? "−" : ""}
- <CreditsAmount usd={Math.abs(n)} />
+ {credits > 0 ? "+" : credits < 0 ? "−" : ""}
+ <CreditsAmount usd={Math.abs(credits) / 100} />
</>
);
- if (n > 0) return { className: "text-success", node: value };
- if (n < 0) return { className: "text-foreground", node: value };
+ if (credits > 0) return { className: "text-success", node: value };
+ if (credits < 0) return { className: "text-foreground", node: value };
return { className: "text-muted-foreground", node: value };
}
+function Cause({ row }: { row: BillingTelemetry }) {
+ if (!row.causeKind) return <span className="text-muted-foreground">—</span>;
+ const label = `${CAUSES[row.causeKind] ?? row.causeKind} ${row.causeId?.slice(0, 8) ?? ""}`;
+ const projectId = row.projectId ?? "";
+ if (row.causeKind === "eval_run" && row.causeId && projectId)
+ return (
+ <Link
+ className="font-medium text-foreground underline-offset-2 hover:underline"
+ params={{ runId: row.causeId }}
+ search={{ projectId }}
+ to="/evaluations/runs/$runId"
+ >
+ {label}
+ </Link>
+ );
+ if (row.causeKind === "finetune_job" && row.causeId && projectId)
+ return (
+ <Link
+ className="font-medium text-foreground underline-offset-2 hover:underline"
+ search={{ groupId: row.causeId, jobId: row.causeId, projectId }}
+ to="/training"
+ >
+ {label}
+ </Link>
+ );
+ return <span className="text-foreground">{label}</span>;
+}
+
+function Priced({ row }: { row: BillingTelemetry }) {
+ if (row.quantity == null || row.unitCredits == null)
+ return <span className="text-muted-foreground">{row.resource || "—"}</span>;
+ return (
+ <span className="text-muted-foreground" title={row.resource}>
+ {Number(row.quantity).toLocaleString("en-US", { maximumFractionDigits: 1 })} {row.unit} ×{" "}
+ {formatOvermindCredits(Number(row.unitCredits) / 100)} credits
+ </span>
+ );
+}
+
const columns: ColumnDef<BillingTelemetry>[] = [
{
accessorKey: "timestamp",
@@ -39,7 +120,7 @@ const columns: ColumnDef<BillingTelemetry>[] = [
header: "When",
meta: { orderingField: "timestamp" },
minSize: 140,
- size: 180,
+ size: 170,
},
{
accessorKey: "serviceLabel",
@@ -48,52 +129,154 @@ const columns: ColumnDef<BillingTelemetry>[] = [
),
header: "Service",
meta: { orderingField: "service" },
- minSize: 120,
- size: 160,
+ minSize: 110,
+ size: 140,
+ },
+ {
+ accessorKey: "causeKind",
+ cell: ({ row }) => <Cause row={row.original} />,
+ header: "Cause",
+ minSize: 140,
+ size: 180,
},
{
accessorKey: "projectName",
cell: ({ row }) => (
- <span className="text-muted-foreground">{row.original.projectName ?? "—"}</span>
+ <span className="text-muted-foreground">
+ {row.original.projectName ?? (row.original.projectId ? "Deleted project" : "—")}
+ </span>
),
header: "Project",
meta: { orderingField: "project__name" },
+ minSize: 110,
+ size: 140,
+ },
+ {
+ accessorKey: "experimentId",
+ cell: ({ row }) =>
+ row.original.experimentId && row.original.projectId ? (
+ <Link
+ className="text-foreground underline-offset-2 hover:underline"
+ params={{ experimentId: row.original.experimentId }}
+ search={{ projectId: row.original.projectId }}
+ to="/experiments/$experimentId"
+ >
+ Open
+ </Link>
+ ) : (
+ <span className="text-muted-foreground">—</span>
+ ),
+ header: "Experiment",
+ minSize: 90,
+ size: 100,
+ },
+ {
+ accessorKey: "actorEmail",
+ cell: ({ row }) => (
+ <span className="text-muted-foreground">{row.original.actorEmail ?? "—"}</span>
+ ),
+ header: "Started by",
minSize: 120,
- size: 160,
+ size: 170,
+ },
+ {
+ accessorKey: "quantity",
+ cell: ({ row }) => <Priced row={row.original} />,
+ header: "Quantity × price",
+ minSize: 160,
+ size: 220,
},
{
accessorKey: "amount",
cell: ({ row }) => {
- const amount = amountCell(row.original.amount);
+ const amount = amountCell(Number(row.original.credits));
return (
<span className={cn("font-medium tabular-nums", amount.className)}>{amount.node}</span>
);
},
- header: "Amount",
+ header: "Credits",
meta: { noTruncate: true, orderingField: "amount" },
minSize: 100,
size: 120,
},
];
+function FilterSelect({
+ label,
+ onChange,
+ options,
+ value,
+}: {
+ label: string;
+ onChange: (value: string | undefined) => void;
+ options: readonly (readonly [string, string])[];
+ value: string | undefined;
+}) {
+ const id = `ledger-${label.toLowerCase()}`;
+ return (
+ <div className="min-w-40 space-y-1">
+ <label className="text-xs text-muted-foreground" htmlFor={id}>
+ {label}
+ </label>
+ <Select
+ onValueChange={(next) => onChange(next === ALL ? undefined : next)}
+ value={value ?? ALL}
+ >
+ <SelectTrigger aria-label={label} className="w-full" id={id}>
+ <SelectValue>
+ {options.find(([key]) => key === value)?.[1] ?? `All ${label.toLowerCase()}s`}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={ALL}>All {label.toLowerCase()}s</SelectItem>
+ {options.map(([key, name]) => (
+ <SelectItem key={key} value={key}>
+ {name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+}
+
export function BillingLedgerTable({ className }: { className?: string }) {
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(PAGE_SIZE);
const [ordering, setOrdering] = useState<string | undefined>("-timestamp");
- const query = useBillingLedgerQuery(page, pageSize, ordering);
+ const [filters, setFilters] = useState<LedgerFilters>({});
+ const query = useBillingLedgerQuery(page, pageSize, ordering, filters);
const { enabled: commercial } = useCommercialBilling();
+ const projects = useProjectsList();
+ const experiments = useExperimentsQuery(filters.project);
+
+ const projectOptions = useMemo(
+ () => (projects.data?.projects ?? []).map((project) => [project.id, project.name] as const),
+ [projects.data]
+ );
+ const experimentOptions = useMemo(
+ () =>
+ (experiments.data?.pages.flat() ?? []).map(
+ (experiment) => [experiment.id, experiment.name] as const
+ ),
+ [experiments.data]
+ );
+ const filter = (next: LedgerFilters) => {
+ setFilters(next);
+ setPage(1);
+ };
const emptyState = useMemo(
() => (
<EmptyState
description={
commercial
- ? "Credits added and spent will show up here once your projects start using them."
- : "Usage will show up here once your projects start using compute."
+ ? "Credits added and spent show here once your projects use them."
+ : "Usage shows here once your projects use compute."
}
icon={Icon.credits}
size="section"
- title={commercial ? "No billing activity yet" : "No usage yet"}
+ title={commercial ? "No billing activity" : "No usage"}
/>
),
[commercial]
@@ -107,9 +290,31 @@ export function BillingLedgerTable({ className }: { className?: string }) {
Usage history
</h3>
<p className={cn(PROSE, "mt-1 text-sm text-muted-foreground")}>
- {commercial ? "Credits added and spent." : "Usage."}
+ Each charge is a provider's bill for your projects' work, at cost. 100 credits = $1.
</p>
</div>
+ <div className="flex flex-wrap gap-3">
+ <FilterSelect
+ label="Project"
+ onChange={(project) => filter({ ...filters, experiment: undefined, project })}
+ options={projectOptions}
+ value={filters.project}
+ />
+ {filters.project ? (
+ <FilterSelect
+ label="Experiment"
+ onChange={(experiment) => filter({ ...filters, experiment })}
+ options={experimentOptions}
+ value={filters.experiment}
+ />
+ ) : null}
+ <FilterSelect
+ label="Service"
+ onChange={(service) => filter({ ...filters, service })}
+ options={SERVICES}
+ value={filters.service}
+ />
+ </div>
<DataTable
columns={columns}
data={query.data}
diff --git a/frontend/src/components/billing/out-of-credits-dialog.tsx b/frontend/src/components/billing/out-of-credits-dialog.tsx
index 9f4a7e6e..61588d1a 100644
--- a/frontend/src/components/billing/out-of-credits-dialog.tsx
+++ b/frontend/src/components/billing/out-of-credits-dialog.tsx
@@ -35,7 +35,7 @@ export function OutOfCreditsDialog() {
);
const action = context?.action;
- const balanceUsd = Math.max(0, Number(sub?.creditsUsd) || 0);
+ const balanceUsd = Number(sub?.creditsUsd) || 0;
return (
<>
diff --git a/frontend/src/components/evaluations/cost-comparison.test.tsx b/frontend/src/components/evaluations/cost-comparison.test.tsx
index 2fee60dc..c0d24571 100644
--- a/frontend/src/components/evaluations/cost-comparison.test.tsx
+++ b/frontend/src/components/evaluations/cost-comparison.test.tsx
@@ -8,10 +8,10 @@ import { CostComparison } from "./cost-comparison";
afterEach(cleanup);
it.each([
- [undefined, undefined, "Cost unavailable"],
- [0, 0, "$0 (no change)"],
- [1, 0.25, "$1.00 (+$0.250)"],
- [1, -0.25, "$1.00 (−$0.250)"],
+ [undefined, undefined, "Estimate unavailable"],
+ [0, 0, "Estimate 0 credits (no change)"],
+ [100, 25, "Estimate 100 credits (+25 credits)"],
+ [100, -25, "Estimate 100 credits (−25 credits)"],
])("shows the estimate and signed difference", (cost, delta, expected) => {
const { container } = render(<CostComparison cost={cost} delta={delta} />);
expect(container.textContent).toBe(expected);
diff --git a/frontend/src/components/evaluations/cost-comparison.tsx b/frontend/src/components/evaluations/cost-comparison.tsx
index 333cc0f6..c17a9be1 100644
--- a/frontend/src/components/evaluations/cost-comparison.tsx
+++ b/frontend/src/components/evaluations/cost-comparison.tsx
@@ -1,15 +1,17 @@
-import { formatCost } from "@/lib/formatters";
+import { formatOvermindCredits } from "@/lib/utils";
+/** An estimate in credits, from published token rates; never a charge. */
export function CostComparison({ cost, delta }: { cost?: number | null; delta?: number | null }) {
- if (cost == null) return <>Cost unavailable</>;
+ if (cost == null) return <>Estimate unavailable</>;
+ const credits = (value: number) => {
+ const shown = formatOvermindCredits(value / 100);
+ return `${shown} ${shown === "1" ? "credit" : "credits"}`;
+ };
return (
<>
- {cost === 0 ? "$0" : formatCost(cost)}
+ Estimate {credits(cost)}
{delta != null && (
- <>
- {" "}
- ({delta === 0 ? "no change" : `${delta > 0 ? "+" : "−"}${formatCost(Math.abs(delta))}`})
- </>
+ <> ({delta === 0 ? "no change" : `${delta > 0 ? "+" : "−"}${credits(Math.abs(delta))}`})</>
)}
</>
);
diff --git a/frontend/src/components/evaluations/judge-model-select.tsx b/frontend/src/components/evaluations/judge-model-select.tsx
index 68907ec9..6fca65aa 100644
--- a/frontend/src/components/evaluations/judge-model-select.tsx
+++ b/frontend/src/components/evaluations/judge-model-select.tsx
@@ -88,8 +88,8 @@ export function JudgeModelSelect({
<SelectContent align="start" className="w-112 max-w-[calc(100vw-2rem)]" position="popper">
{!compact && (
<p className="max-w-80 px-2 py-1.5 text-xs text-muted-foreground">
- USD budget · all judges · one dataset pass per evaluated model · reserved output.
- Excludes retries and caching.
+ Estimate in credits · all judges · one dataset pass per evaluated model · reserved
+ output. Excludes retries and caching.
</p>
)}
<SelectItem
@@ -117,7 +117,7 @@ export function JudgeModelSelect({
{contextStatusLabel(option.status)}
</span>
<span className="text-muted-foreground">
- <CostComparison cost={option.estimatedCostUsd} delta={option.costDeltaUsd} />
+ <CostComparison cost={option.estimatedCredits} delta={option.creditsDelta} />
</span>
</span>
</ModelOptionLabel>
diff --git a/frontend/src/components/experiments/experiment-panel.tsx b/frontend/src/components/experiments/experiment-panel.tsx
index c033fc46..ddd4ba13 100644
--- a/frontend/src/components/experiments/experiment-panel.tsx
+++ b/frontend/src/components/experiments/experiment-panel.tsx
@@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import apiClient from "@/client";
import { Button } from "@/components/ui/button";
+import { CreditsAmount } from "@/components/ui/credits";
import { Icon } from "@/components/ui/icons";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { invalidateExperiment } from "@/hooks/use-experiments";
@@ -70,9 +71,10 @@ export function ProposalCards({ detail }: { detail: ExperimentDetail }) {
);
}
-/** What the work cost as measured, the parts no record prices, and the agent's notes. */
+/** What the ledger charged to the experiment, the costs charged to its project instead, and
+ * the agent's notes. */
export function NotesAndSpend({ detail }: { detail: ExperimentDetail }) {
- const { measuredUsd, unknown } = detail.spend;
+ const { notAttributed, spentCredits } = detail.spend;
return (
<Popover>
<PopoverTrigger asChild>
@@ -86,9 +88,13 @@ export function NotesAndSpend({ detail }: { detail: ExperimentDetail }) {
>
<section className="space-y-1">
<p className="font-medium">Spend</p>
- <p className="tabular-nums">${measuredUsd.toFixed(2)} measured</p>
- {unknown.length > 0 && (
- <p className="text-muted-foreground">Not measured: {unknown.join(", ")}</p>
+ <p className="tabular-nums">
+ <CreditsAmount usd={spentCredits / 100} /> charged
+ </p>
+ {notAttributed.length > 0 && (
+ <p className="text-muted-foreground">
+ Charged to the project: {notAttributed.join(", ")}
+ </p>
)}
</section>
<section className="space-y-1">
diff --git a/frontend/src/components/experiments/triggers.tsx b/frontend/src/components/experiments/triggers.tsx
index ab53b7b7..80326473 100644
--- a/frontend/src/components/experiments/triggers.tsx
+++ b/frontend/src/components/experiments/triggers.tsx
@@ -52,7 +52,7 @@ export function ExperimentTriggers({
instruction,
kind,
maxSends: sends,
- maxSpendUsd: cap.trim() ? cap.trim() : undefined,
+ maxSpendCredits: cap.trim() ? cap.trim() : undefined,
threshold: kind === "failing_traces" ? threshold : null,
},
id: experimentId,
@@ -97,7 +97,8 @@ export function ExperimentTriggers({
</span>
<span className="block text-muted-foreground">
{trigger.sends} of {trigger.maxSends} sent
- {trigger.maxSpendUsd && ` · stops at USD ${trigger.maxSpendUsd} measured`}
+ {trigger.maxSpendCredits &&
+ ` · stops at ${Number(trigger.maxSpendCredits).toLocaleString("en-US")} credits charged`}
{trigger.sends >= trigger.maxSends
? " · ended"
: trigger.nextAt
@@ -196,9 +197,9 @@ export function ExperimentTriggers({
value={sends}
/>
</Field>
- <Field label="Measured spend, at most (USD)">
+ <Field label="Charged credits, at most">
<Input
- aria-label="Measured spend, at most (USD)"
+ aria-label="Charged credits, at most"
inputMode="decimal"
onChange={(event) => setCap(event.target.value)}
placeholder="No cap"
diff --git a/frontend/src/components/finetuning/train/__tests__/judge-model-select.test.tsx b/frontend/src/components/finetuning/train/__tests__/judge-model-select.test.tsx
index fa471577..0d113fdb 100644
--- a/frontend/src/components/finetuning/train/__tests__/judge-model-select.test.tsx
+++ b/frontend/src/components/finetuning/train/__tests__/judge-model-select.test.tsx
@@ -18,15 +18,15 @@ function setup(overrides: Partial<TrainWizard> = {}) {
checks: [{ configuredModel: "small", model: "small", role: "judge", status: "warning" }],
judgeModels: [
{
- costDeltaUsd: 0,
- estimatedCostUsd: 1,
+ creditsDelta: 0,
+ estimatedCredits: 1,
model: "small",
name: "Small judge",
status: "warning",
},
{
- costDeltaUsd: 1,
- estimatedCostUsd: 2,
+ creditsDelta: 1,
+ estimatedCredits: 2,
model: "large",
name: "Large judge",
status: "fits",
@@ -66,13 +66,13 @@ it("prefills the saved judge and labels every option without disabling uncertain
openOptions();
const fitting = screen.getByRole("option", { name: /Large judge/ });
expect(within(fitting).getByText(/Fits estimated context/)).toBeTruthy();
- expect(fitting.textContent).toContain("+$1.00");
+ expect(fitting.textContent).toContain("Estimate 2 credits (+1 credit)");
const small = screen.getByRole("option", { name: /Small judge.*Context too small/ });
expect(small.getAttribute("aria-disabled")).not.toBe("true");
expect(small.className).toContain("text-muted-foreground");
const unknown = screen.getByRole("option", { name: /Unknown judge/ });
expect(unknown.textContent).toContain("Context unverified");
- expect(unknown.textContent).toContain("Cost unavailable");
+ expect(unknown.textContent).toContain("Estimate unavailable");
expect(unknown.getAttribute("aria-disabled")).not.toBe("true");
expect(unknown.classList.contains("text-muted-foreground")).toBe(false);
fireEvent.click(fitting);
diff --git a/frontend/src/components/finetuning/train/models-panel.tsx b/frontend/src/components/finetuning/train/models-panel.tsx
index 8b2c0fcf..fa868b7a 100644
--- a/frontend/src/components/finetuning/train/models-panel.tsx
+++ b/frontend/src/components/finetuning/train/models-panel.tsx
@@ -428,8 +428,11 @@ function ModelRow({
matchRank={draft.matchRank}
/>
{estimate?.costEstimate && (
- <span className="shrink-0 font-mono text-xs tabular-nums text-muted-foreground">
- <CreditsAmount usd={estimate.costEstimate.usd} />
+ <span
+ className="shrink-0 font-mono text-xs tabular-nums text-muted-foreground"
+ title="Estimate; the job is charged for what its containers use"
+ >
+ Est. <CreditsAmount usd={estimate.costEstimate.usd} />
</span>
)}
{estimate?.timeEstimate &&
diff --git a/frontend/src/components/finetuning/train/train-wizard.tsx b/frontend/src/components/finetuning/train/train-wizard.tsx
index 805801e4..14b6c22b 100644
--- a/frontend/src/components/finetuning/train/train-wizard.tsx
+++ b/frontend/src/components/finetuning/train/train-wizard.tsx
@@ -190,8 +190,17 @@ function TrainWizardForm({
{selectedDrafts.length} {selectedDrafts.length === 1 ? "model" : "models"} ·
</span>
<span className="font-mono tabular-nums text-foreground">
- {totals.pricedCount > 0 ? <CreditsAmount usd={totals.usd} /> : "No published price"}
+ {totals.pricedCount > 0 ? (
+ <>
+ Est. <CreditsAmount usd={totals.usd} />
+ </>
+ ) : (
+ "No estimate"
+ )}
</span>
+ {totals.pricedCount > 0 && totals.unpriced.length > 0 && (
+ <span>· excludes {totals.unpriced.join(", ")}</span>
+ )}
{totals.longest && <span>· ~{totals.longest}</span>}
</>
)}
diff --git a/frontend/src/components/finetuning/train/use-train-wizard.ts b/frontend/src/components/finetuning/train/use-train-wizard.ts
index abe2bf7c..549a3df6 100644
--- a/frontend/src/components/finetuning/train/use-train-wizard.ts
+++ b/frontend/src/components/finetuning/train/use-train-wizard.ts
@@ -510,6 +510,10 @@ export function useTrainWizard({
return {
longest,
pricedCount: priced.length,
+ // A total over priced models only; the rest are named, never counted as zero.
+ unpriced: selectedDrafts
+ .filter((d) => estimates.get(d.id)?.costEstimate == null)
+ .map((d) => d.displayName),
usd: priced.reduce((sum, e) => sum + (e?.costEstimate?.usd ?? 0), 0),
};
}, [selectedDrafts, estimates]);
diff --git a/frontend/src/components/header-credits.tsx b/frontend/src/components/header-credits.tsx
index a18af0e2..39a15542 100644
--- a/frontend/src/components/header-credits.tsx
+++ b/frontend/src/components/header-credits.tsx
@@ -33,7 +33,7 @@ export function HeaderCredits() {
if (!ready || !data) return null;
if (!commercial) {
- const spent = Math.max(0, Number(data.creditsSpentUsd) || 0);
+ const spent = Number(data.creditsSpentUsd) || 0;
return (
<TooltipProvider delayDuration={150}>
<Tooltip>
@@ -55,12 +55,12 @@ export function HeaderCredits() {
);
}
- const balance = Math.max(0, Number(data.creditsUsd) || 0);
+ const balance = Number(data.creditsUsd) || 0;
const out = balance <= 0;
const low = !out && balance < LOW_BALANCE_USD;
const detail = out
- ? "You're out of credits. Add credits in Settings."
+ ? "Paused: credits needed. Scoring, signals and scheduled work resume after a top-up in Settings."
: low
? "Credits are low. Add credits in Settings."
: "Credits pay for training, inference and analysis.";
diff --git a/frontend/src/hooks/use-billing-account.test.tsx b/frontend/src/hooks/use-billing-account.test.tsx
index 017b4fa1..a2d289bc 100644
--- a/frontend/src/hooks/use-billing-account.test.tsx
+++ b/frontend/src/hooks/use-billing-account.test.tsx
@@ -4,9 +4,10 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
-const billing = vi.hoisted(() => ({ account: vi.fn(), confirm: vi.fn() }));
+const billing = vi.hoisted(() => ({ account: vi.fn(), confirm: vi.fn(), me: vi.fn() }));
vi.mock("@/client", () => ({
default: {
+ auth: { authMeRetrieve: billing.me },
billing: {
billingAccountRetrieve: billing.account,
billingTopupConfirmCreate: billing.confirm,
@@ -14,7 +15,12 @@ vi.mock("@/client", () => ({
},
}));
-import { billingAccountQueryKey, useBillingAccount, useConfirmTopUp } from "./use-billing-account";
+import {
+ billingAccountQueryKey,
+ useBillingAccount,
+ useConfirmTopUp,
+ useCredits,
+} from "./use-billing-account";
afterEach(() => {
cleanup();
@@ -46,3 +52,16 @@ it("keeps the confirmed balance when an older account read lands after it", asyn
expect(client.getQueryData(billingAccountQueryKey)).toEqual(confirmed);
});
+
+it("shows a negative balance as it is and closes the start gate", async () => {
+ billing.me.mockResolvedValue({ billingEnabled: true });
+ billing.account.mockResolvedValue({ creditsUsd: "-12.5000" });
+ const client = new QueryClient();
+ const { result } = renderHook(() => useCredits(), {
+ wrapper: ({ children }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ });
+ await waitFor(() => expect(result.current.balanceUsd).toBe(-12.5));
+ await waitFor(() => expect(result.current.hasCredits).toBe(false));
+});
diff --git a/frontend/src/hooks/use-billing-account.ts b/frontend/src/hooks/use-billing-account.ts
index d91953a2..1ffec9f9 100644
--- a/frontend/src/hooks/use-billing-account.ts
+++ b/frontend/src/hooks/use-billing-account.ts
@@ -21,10 +21,21 @@ export function useCommercialBilling() {
return { enabled: me?.billingEnabled === true, ready: isSuccess };
}
-export function useBillingLedgerQuery(page = 1, pageSize = 25, ordering?: string) {
+export interface LedgerFilters {
+ project?: string;
+ experiment?: string;
+ service?: string;
+}
+
+export function useBillingLedgerQuery(
+ page = 1,
+ pageSize = 25,
+ ordering?: string,
+ filters: LedgerFilters = {}
+) {
return useQuery({
- queryFn: () => api.billing.billingLedgerList({ ordering, page, pageSize }),
- queryKey: [...billingLedgerQueryKey, page, pageSize, ordering],
+ queryFn: () => api.billing.billingLedgerList({ ordering, page, pageSize, ...filters }),
+ queryKey: [...billingLedgerQueryKey, page, pageSize, ordering, filters],
});
}
@@ -36,7 +47,7 @@ export function useBillingLedgerQuery(page = 1, pageSize = 25, ordering?: string
export function useCredits() {
const { enabled } = useCommercialBilling();
const { data, isLoading } = useBillingAccount();
- const balanceUsd = data ? Math.max(0, Number(data.creditsUsd) || 0) : undefined;
+ const balanceUsd = data ? Number(data.creditsUsd) || 0 : undefined;
return {
balanceUsd,
hasCredits: !enabled || balanceUsd === undefined || balanceUsd > 0,
diff --git a/frontend/src/openapi/apis/BillingApi.ts b/frontend/src/openapi/apis/BillingApi.ts
index 9fd7c2bb..8a9b2742 100644
--- a/frontend/src/openapi/apis/BillingApi.ts
+++ b/frontend/src/openapi/apis/BillingApi.ts
@@ -38,9 +38,16 @@ import {
} from '../models/index';
export interface BillingLedgerListRequest {
+ causeId?: string;
+ causeKind?: string;
+ experiment?: string;
ordering?: string;
page?: number;
pageSize?: number;
+ project?: string;
+ run?: string;
+ service?: string;
+ usage?: boolean;
}
export interface BillingTopupConfirmCreateRequest {
@@ -111,6 +118,18 @@ export class BillingApi extends runtime.BaseAPI {
async billingLedgerListRaw(requestParameters: BillingLedgerListRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<PaginatedBillingTelemetryList>> {
const queryParameters: any = {};
+ if (requestParameters['causeId'] != null) {
+ queryParameters['cause_id'] = requestParameters['causeId'];
+ }
+
+ if (requestParameters['causeKind'] != null) {
+ queryParameters['cause_kind'] = requestParameters['causeKind'];
+ }
+
+ if (requestParameters['experiment'] != null) {
+ queryParameters['experiment'] = requestParameters['experiment'];
+ }
+
if (requestParameters['ordering'] != null) {
queryParameters['ordering'] = requestParameters['ordering'];
}
@@ -123,6 +142,22 @@ export class BillingApi extends runtime.BaseAPI {
queryParameters['page_size'] = requestParameters['pageSize'];
}
+ if (requestParameters['project'] != null) {
+ queryParameters['project'] = requestParameters['project'];
+ }
+
+ if (requestParameters['run'] != null) {
+ queryParameters['run'] = requestParameters['run'];
+ }
+
+ if (requestParameters['service'] != null) {
+ queryParameters['service'] = requestParameters['service'];
+ }
+
+ if (requestParameters['usage'] != null) {
+ queryParameters['usage'] = requestParameters['usage'];
+ }
+
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.accessToken) {
diff --git a/frontend/src/openapi/models/BillingAccount.ts b/frontend/src/openapi/models/BillingAccount.ts
index 9fe6f1af..6351f1da 100644
--- a/frontend/src/openapi/models/BillingAccount.ts
+++ b/frontend/src/openapi/models/BillingAccount.ts
@@ -43,6 +43,24 @@ export interface BillingAccount {
* @memberof BillingAccount
*/
creditsSpentUsd: string;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingAccount
+ */
+ balanceCredits: string;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingAccount
+ */
+ spentCredits: string;
+ /**
+ *
+ * @type {boolean}
+ * @memberof BillingAccount
+ */
+ backgroundPaused: boolean;
}
/**
@@ -53,6 +71,9 @@ export function instanceOfBillingAccount(value: object): value is BillingAccount
if (!('creditsUsd' in value) || value['creditsUsd'] === undefined) return false;
if (!('creditsGrantedUsd' in value) || value['creditsGrantedUsd'] === undefined) return false;
if (!('creditsSpentUsd' in value) || value['creditsSpentUsd'] === undefined) return false;
+ if (!('balanceCredits' in value) || value['balanceCredits'] === undefined) return false;
+ if (!('spentCredits' in value) || value['spentCredits'] === undefined) return false;
+ if (!('backgroundPaused' in value) || value['backgroundPaused'] === undefined) return false;
return true;
}
@@ -70,6 +91,9 @@ export function BillingAccountFromJSONTyped(json: any, ignoreDiscriminator: bool
'creditsUsd': json['credits_usd'],
'creditsGrantedUsd': json['credits_granted_usd'],
'creditsSpentUsd': json['credits_spent_usd'],
+ 'balanceCredits': json['balance_credits'],
+ 'spentCredits': json['spent_credits'],
+ 'backgroundPaused': json['background_paused'],
};
}
@@ -88,5 +112,8 @@ export function BillingAccountToJSONTyped(value?: BillingAccount | null, ignoreD
'credits_usd': value['creditsUsd'],
'credits_granted_usd': value['creditsGrantedUsd'],
'credits_spent_usd': value['creditsSpentUsd'],
+ 'balance_credits': value['balanceCredits'],
+ 'spent_credits': value['spentCredits'],
+ 'background_paused': value['backgroundPaused'],
};
}
diff --git a/frontend/src/openapi/models/BillingTelemetry.ts b/frontend/src/openapi/models/BillingTelemetry.ts
index 7b4999c4..128db3aa 100644
--- a/frontend/src/openapi/models/BillingTelemetry.ts
+++ b/frontend/src/openapi/models/BillingTelemetry.ts
@@ -14,7 +14,8 @@
import { mapValues } from '../runtime';
/**
- * One credits ledger row for the authenticated user.
+ * One credits ledger row for the authenticated user: a provider cost at its price, with
+ * what caused it and who started it.
* @export
* @interface BillingTelemetry
*/
@@ -31,6 +32,12 @@ export interface BillingTelemetry {
* @memberof BillingTelemetry
*/
amount: string;
+ /**
+ *
+ * @type {number}
+ * @memberof BillingTelemetry
+ */
+ readonly credits: number;
/**
*
* @type {Date}
@@ -61,6 +68,78 @@ export interface BillingTelemetry {
* @memberof BillingTelemetry
*/
readonly projectName: string | null;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingTelemetry
+ */
+ causeKind?: string;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingTelemetry
+ */
+ causeId?: string;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingTelemetry
+ */
+ readonly experimentId: string | null;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingTelemetry
+ */
+ readonly runId: string | null;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingTelemetry
+ */
+ readonly actorEmail: string | null;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingTelemetry
+ */
+ resource?: string;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingTelemetry
+ */
+ quantity?: string | null;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingTelemetry
+ */
+ unit?: string;
+ /**
+ *
+ * @type {number}
+ * @memberof BillingTelemetry
+ */
+ readonly unitCredits: number | null;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingTelemetry
+ */
+ providerRef?: string;
+ /**
+ *
+ * @type {Date}
+ * @memberof BillingTelemetry
+ */
+ startedAt?: Date | null;
+ /**
+ *
+ * @type {Date}
+ * @memberof BillingTelemetry
+ */
+ endedAt?: Date | null;
}
/**
@@ -69,11 +148,16 @@ export interface BillingTelemetry {
export function instanceOfBillingTelemetry(value: object): value is BillingTelemetry {
if (!('id' in value) || value['id'] === undefined) return false;
if (!('amount' in value) || value['amount'] === undefined) return false;
+ if (!('credits' in value) || value['credits'] === undefined) return false;
if (!('timestamp' in value) || value['timestamp'] === undefined) return false;
if (!('service' in value) || value['service'] === undefined) return false;
if (!('serviceLabel' in value) || value['serviceLabel'] === undefined) return false;
if (!('projectId' in value) || value['projectId'] === undefined) return false;
if (!('projectName' in value) || value['projectName'] === undefined) return false;
+ if (!('experimentId' in value) || value['experimentId'] === undefined) return false;
+ if (!('runId' in value) || value['runId'] === undefined) return false;
+ if (!('actorEmail' in value) || value['actorEmail'] === undefined) return false;
+ if (!('unitCredits' in value) || value['unitCredits'] === undefined) return false;
return true;
}
@@ -89,11 +173,24 @@ export function BillingTelemetryFromJSONTyped(json: any, ignoreDiscriminator: bo
'id': json['id'],
'amount': json['amount'],
+ 'credits': json['credits'],
'timestamp': (new Date(json['timestamp'])),
'service': json['service'],
'serviceLabel': json['service_label'],
'projectId': json['project_id'],
'projectName': json['project_name'],
+ 'causeKind': json['cause_kind'] == null ? undefined : json['cause_kind'],
+ 'causeId': json['cause_id'] == null ? undefined : json['cause_id'],
+ 'experimentId': json['experiment_id'],
+ 'runId': json['run_id'],
+ 'actorEmail': json['actor_email'],
+ 'resource': json['resource'] == null ? undefined : json['resource'],
+ 'quantity': json['quantity'] == null ? undefined : json['quantity'],
+ 'unit': json['unit'] == null ? undefined : json['unit'],
+ 'unitCredits': json['unit_credits'],
+ 'providerRef': json['provider_ref'] == null ? undefined : json['provider_ref'],
+ 'startedAt': json['started_at'] == null ? undefined : (new Date(json['started_at'])),
+ 'endedAt': json['ended_at'] == null ? undefined : (new Date(json['ended_at'])),
};
}
@@ -101,7 +198,7 @@ export function BillingTelemetryToJSON(json: any): BillingTelemetry {
return BillingTelemetryToJSONTyped(json, false);
}
-export function BillingTelemetryToJSONTyped(value?: Omit<BillingTelemetry, 'id'|'timestamp'|'service'|'service_label'|'project_id'|'project_name'> | null, ignoreDiscriminator: boolean = false): any {
+export function BillingTelemetryToJSONTyped(value?: Omit<BillingTelemetry, 'id'|'credits'|'timestamp'|'service'|'service_label'|'project_id'|'project_name'|'experiment_id'|'run_id'|'actor_email'|'unit_credits'> | null, ignoreDiscriminator: boolean = false): any {
if (value == null) {
return value;
}
@@ -109,5 +206,13 @@ export function BillingTelemetryToJSONTyped(value?: Omit<BillingTelemetry, 'id'|
return {
'amount': value['amount'],
+ 'cause_kind': value['causeKind'],
+ 'cause_id': value['causeId'],
+ 'resource': value['resource'],
+ 'quantity': value['quantity'],
+ 'unit': value['unit'],
+ 'provider_ref': value['providerRef'],
+ 'started_at': value['startedAt'] == null ? value['startedAt'] : value['startedAt'].toISOString(),
+ 'ended_at': value['endedAt'] == null ? value['endedAt'] : value['endedAt'].toISOString(),
};
}
diff --git a/frontend/src/openapi/models/EvaluationContextCheck.ts b/frontend/src/openapi/models/EvaluationContextCheck.ts
index 93cadbfa..43f1cfe0 100644
--- a/frontend/src/openapi/models/EvaluationContextCheck.ts
+++ b/frontend/src/openapi/models/EvaluationContextCheck.ts
@@ -128,7 +128,7 @@ export interface EvaluationContextCheck {
* @type {number}
* @memberof EvaluationContextCheck
*/
- estimatedCostUsd?: number | null;
+ estimatedCredits?: number | null;
/**
*
* @type {string}
@@ -196,7 +196,7 @@ export function EvaluationContextCheckFromJSONTyped(json: any, ignoreDiscriminat
'estimated': json['estimated'],
'status': json['status'],
'message': json['message'],
- 'estimatedCostUsd': json['estimated_cost_usd'] == null ? undefined : json['estimated_cost_usd'],
+ 'estimatedCredits': json['estimated_credits'] == null ? undefined : json['estimated_credits'],
'costBasis': json['cost_basis'] == null ? undefined : json['cost_basis'],
'suggestions': json['suggestions'] == null ? undefined : ((json['suggestions'] as Array<any>).map(EvaluationContextSuggestionFromJSON)),
'suggestionNote': json['suggestion_note'] == null ? undefined : json['suggestion_note'],
@@ -230,7 +230,7 @@ export function EvaluationContextCheckToJSONTyped(value?: EvaluationContextCheck
'estimated': value['estimated'],
'status': value['status'],
'message': value['message'],
- 'estimated_cost_usd': value['estimatedCostUsd'],
+ 'estimated_credits': value['estimatedCredits'],
'cost_basis': value['costBasis'],
'suggestions': value['suggestions'] == null ? undefined : ((value['suggestions'] as Array<any>).map(EvaluationContextSuggestionToJSON)),
'suggestion_note': value['suggestionNote'],
diff --git a/frontend/src/openapi/models/EvaluationContextSuggestion.ts b/frontend/src/openapi/models/EvaluationContextSuggestion.ts
index 95dfcaf2..f394bf68 100644
--- a/frontend/src/openapi/models/EvaluationContextSuggestion.ts
+++ b/frontend/src/openapi/models/EvaluationContextSuggestion.ts
@@ -54,13 +54,13 @@ export interface EvaluationContextSuggestion {
* @type {number}
* @memberof EvaluationContextSuggestion
*/
- estimatedCostUsd: number | null;
+ estimatedCredits: number | null;
/**
*
* @type {number}
* @memberof EvaluationContextSuggestion
*/
- costDeltaUsd: number | null;
+ creditsDelta: number | null;
}
/**
@@ -72,8 +72,8 @@ export function instanceOfEvaluationContextSuggestion(value: object): value is E
if (!('contextWindow' in value) || value['contextWindow'] === undefined) return false;
if (!('maxOutputTokens' in value) || value['maxOutputTokens'] === undefined) return false;
if (!('reservedOutputTokens' in value) || value['reservedOutputTokens'] === undefined) return false;
- if (!('estimatedCostUsd' in value) || value['estimatedCostUsd'] === undefined) return false;
- if (!('costDeltaUsd' in value) || value['costDeltaUsd'] === undefined) return false;
+ if (!('estimatedCredits' in value) || value['estimatedCredits'] === undefined) return false;
+ if (!('creditsDelta' in value) || value['creditsDelta'] === undefined) return false;
return true;
}
@@ -92,8 +92,8 @@ export function EvaluationContextSuggestionFromJSONTyped(json: any, ignoreDiscri
'contextWindow': json['context_window'],
'maxOutputTokens': json['max_output_tokens'],
'reservedOutputTokens': json['reserved_output_tokens'],
- 'estimatedCostUsd': json['estimated_cost_usd'],
- 'costDeltaUsd': json['cost_delta_usd'],
+ 'estimatedCredits': json['estimated_credits'],
+ 'creditsDelta': json['credits_delta'],
};
}
@@ -113,7 +113,7 @@ export function EvaluationContextSuggestionToJSONTyped(value?: EvaluationContext
'context_window': value['contextWindow'],
'max_output_tokens': value['maxOutputTokens'],
'reserved_output_tokens': value['reservedOutputTokens'],
- 'estimated_cost_usd': value['estimatedCostUsd'],
- 'cost_delta_usd': value['costDeltaUsd'],
+ 'estimated_credits': value['estimatedCredits'],
+ 'credits_delta': value['creditsDelta'],
};
}
diff --git a/frontend/src/openapi/models/EvaluationJudgeOption.ts b/frontend/src/openapi/models/EvaluationJudgeOption.ts
index e25e68e0..950c6881 100644
--- a/frontend/src/openapi/models/EvaluationJudgeOption.ts
+++ b/frontend/src/openapi/models/EvaluationJudgeOption.ts
@@ -54,13 +54,13 @@ export interface EvaluationJudgeOption {
* @type {number}
* @memberof EvaluationJudgeOption
*/
- estimatedCostUsd: number | null;
+ estimatedCredits: number | null;
/**
*
* @type {number}
* @memberof EvaluationJudgeOption
*/
- costDeltaUsd: number | null;
+ creditsDelta: number | null;
/**
*
* @type {string}
@@ -78,8 +78,8 @@ export function instanceOfEvaluationJudgeOption(value: object): value is Evaluat
if (!('contextWindow' in value) || value['contextWindow'] === undefined) return false;
if (!('maxOutputTokens' in value) || value['maxOutputTokens'] === undefined) return false;
if (!('reservedOutputTokens' in value) || value['reservedOutputTokens'] === undefined) return false;
- if (!('estimatedCostUsd' in value) || value['estimatedCostUsd'] === undefined) return false;
- if (!('costDeltaUsd' in value) || value['costDeltaUsd'] === undefined) return false;
+ if (!('estimatedCredits' in value) || value['estimatedCredits'] === undefined) return false;
+ if (!('creditsDelta' in value) || value['creditsDelta'] === undefined) return false;
if (!('status' in value) || value['status'] === undefined) return false;
return true;
}
@@ -99,8 +99,8 @@ export function EvaluationJudgeOptionFromJSONTyped(json: any, ignoreDiscriminato
'contextWindow': json['context_window'],
'maxOutputTokens': json['max_output_tokens'],
'reservedOutputTokens': json['reserved_output_tokens'],
- 'estimatedCostUsd': json['estimated_cost_usd'],
- 'costDeltaUsd': json['cost_delta_usd'],
+ 'estimatedCredits': json['estimated_credits'],
+ 'creditsDelta': json['credits_delta'],
'status': json['status'],
};
}
@@ -121,8 +121,8 @@ export function EvaluationJudgeOptionToJSONTyped(value?: EvaluationJudgeOption |
'context_window': value['contextWindow'],
'max_output_tokens': value['maxOutputTokens'],
'reserved_output_tokens': value['reservedOutputTokens'],
- 'estimated_cost_usd': value['estimatedCostUsd'],
- 'cost_delta_usd': value['costDeltaUsd'],
+ 'estimated_credits': value['estimatedCredits'],
+ 'credits_delta': value['creditsDelta'],
'status': value['status'],
};
}
diff --git a/frontend/src/openapi/models/ExperimentTrigger.ts b/frontend/src/openapi/models/ExperimentTrigger.ts
index f61fc974..db17ea23 100644
--- a/frontend/src/openapi/models/ExperimentTrigger.ts
+++ b/frontend/src/openapi/models/ExperimentTrigger.ts
@@ -80,7 +80,7 @@ export interface ExperimentTrigger {
* @type {string}
* @memberof ExperimentTrigger
*/
- maxSpendUsd: string | null;
+ maxSpendCredits: string | null;
/**
*
* @type {Date}
@@ -109,7 +109,7 @@ export function instanceOfExperimentTrigger(value: object): value is ExperimentT
if (!('threshold' in value) || value['threshold'] === undefined) return false;
if (!('sends' in value) || value['sends'] === undefined) return false;
if (!('maxSends' in value) || value['maxSends'] === undefined) return false;
- if (!('maxSpendUsd' in value) || value['maxSpendUsd'] === undefined) return false;
+ if (!('maxSpendCredits' in value) || value['maxSpendCredits'] === undefined) return false;
if (!('nextAt' in value) || value['nextAt'] === undefined) return false;
if (!('lastSentAt' in value) || value['lastSentAt'] === undefined) return false;
return true;
@@ -133,7 +133,7 @@ export function ExperimentTriggerFromJSONTyped(json: any, ignoreDiscriminator: b
'threshold': json['threshold'],
'sends': json['sends'],
'maxSends': json['max_sends'],
- 'maxSpendUsd': json['max_spend_usd'],
+ 'maxSpendCredits': json['max_spend_credits'],
'nextAt': (json['next_at'] == null ? null : new Date(json['next_at'])),
'lastSentAt': (json['last_sent_at'] == null ? null : new Date(json['last_sent_at'])),
};
@@ -158,7 +158,7 @@ export function ExperimentTriggerToJSONTyped(value?: ExperimentTrigger | null, i
'threshold': value['threshold'],
'sends': value['sends'],
'max_sends': value['maxSends'],
- 'max_spend_usd': value['maxSpendUsd'],
+ 'max_spend_credits': value['maxSpendCredits'],
'next_at': value['nextAt'] == null ? value['nextAt'] : value['nextAt'].toISOString(),
'last_sent_at': value['lastSentAt'] == null ? value['lastSentAt'] : value['lastSentAt'].toISOString(),
};
diff --git a/frontend/src/openapi/models/ExperimentTriggerInputRequest.ts b/frontend/src/openapi/models/ExperimentTriggerInputRequest.ts
index e8409d7e..fce476d0 100644
--- a/frontend/src/openapi/models/ExperimentTriggerInputRequest.ts
+++ b/frontend/src/openapi/models/ExperimentTriggerInputRequest.ts
@@ -56,7 +56,7 @@ export interface ExperimentTriggerInputRequest {
* @type {string}
* @memberof ExperimentTriggerInputRequest
*/
- maxSpendUsd?: string;
+ maxSpendCredits?: string;
/**
*
* @type {string}
@@ -98,7 +98,7 @@ export function ExperimentTriggerInputRequestFromJSONTyped(json: any, ignoreDisc
'instruction': json['instruction'],
'hours': json['hours'],
'maxSends': json['max_sends'],
- 'maxSpendUsd': json['max_spend_usd'] == null ? undefined : json['max_spend_usd'],
+ 'maxSpendCredits': json['max_spend_credits'] == null ? undefined : json['max_spend_credits'],
'capability': json['capability'] == null ? undefined : json['capability'],
'threshold': json['threshold'] == null ? undefined : json['threshold'],
};
@@ -119,7 +119,7 @@ export function ExperimentTriggerInputRequestToJSONTyped(value?: ExperimentTrigg
'instruction': value['instruction'],
'hours': value['hours'],
'max_sends': value['maxSends'],
- 'max_spend_usd': value['maxSpendUsd'],
+ 'max_spend_credits': value['maxSpendCredits'],
'capability': value['capability'],
'threshold': value['threshold'],
};
diff --git a/frontend/src/openapi/models/InferenceMetrics.ts b/frontend/src/openapi/models/InferenceMetrics.ts
index c1831cc1..71ab505a 100644
--- a/frontend/src/openapi/models/InferenceMetrics.ts
+++ b/frontend/src/openapi/models/InferenceMetrics.ts
@@ -46,12 +46,6 @@ export interface InferenceMetrics {
* @memberof InferenceMetrics
*/
lastRequestAt: Date | null;
- /**
- *
- * @type {number}
- * @memberof InferenceMetrics
- */
- costRecordedRequestCount: number;
/**
*
* @type {number}
@@ -174,7 +168,6 @@ export interface InferenceMetrics {
export function instanceOfInferenceMetrics(value: object): value is InferenceMetrics {
if (!('dedicatedUsage' in value) || value['dedicatedUsage'] === undefined) return false;
if (!('lastRequestAt' in value) || value['lastRequestAt'] === undefined) return false;
- if (!('costRecordedRequestCount' in value) || value['costRecordedRequestCount'] === undefined) return false;
if (!('failedRequestCount' in value) || value['failedRequestCount'] === undefined) return false;
if (!('coldRequestCount' in value) || value['coldRequestCount'] === undefined) return false;
if (!('endToEndP50Ms' in value) || value['endToEndP50Ms'] === undefined) return false;
@@ -209,7 +202,6 @@ export function InferenceMetricsFromJSONTyped(json: any, ignoreDiscriminator: bo
'dedicatedUsage': DedicatedUsageFromJSON(json['dedicated_usage']),
'lastRequestAt': (json['last_request_at'] == null ? null : new Date(json['last_request_at'])),
- 'costRecordedRequestCount': json['cost_recorded_request_count'],
'failedRequestCount': json['failed_request_count'],
'coldRequestCount': json['cold_request_count'],
'endToEndP50Ms': json['end_to_end_p50_ms'],
@@ -245,7 +237,6 @@ export function InferenceMetricsToJSONTyped(value?: InferenceMetrics | null, ign
'dedicated_usage': DedicatedUsageToJSON(value['dedicatedUsage']),
'last_request_at': value['lastRequestAt'] == null ? value['lastRequestAt'] : value['lastRequestAt'].toISOString(),
- 'cost_recorded_request_count': value['costRecordedRequestCount'],
'failed_request_count': value['failedRequestCount'],
'cold_request_count': value['coldRequestCount'],
'end_to_end_p50_ms': value['endToEndP50Ms'],
diff --git a/frontend/src/openapi/models/Spend.ts b/frontend/src/openapi/models/Spend.ts
index 081bcaeb..f89fc951 100644
--- a/frontend/src/openapi/models/Spend.ts
+++ b/frontend/src/openapi/models/Spend.ts
@@ -24,21 +24,21 @@ export interface Spend {
* @type {number}
* @memberof Spend
*/
- measuredUsd: number;
+ spentCredits: number;
/**
*
* @type {Array<string>}
* @memberof Spend
*/
- unknown: Array<string>;
+ notAttributed: Array<string>;
}
/**
* Check if a given object implements the Spend interface.
*/
export function instanceOfSpend(value: object): value is Spend {
- if (!('measuredUsd' in value) || value['measuredUsd'] === undefined) return false;
- if (!('unknown' in value) || value['unknown'] === undefined) return false;
+ if (!('spentCredits' in value) || value['spentCredits'] === undefined) return false;
+ if (!('notAttributed' in value) || value['notAttributed'] === undefined) return false;
return true;
}
@@ -52,8 +52,8 @@ export function SpendFromJSONTyped(json: any, ignoreDiscriminator: boolean): Spe
}
return {
- 'measuredUsd': json['measured_usd'],
- 'unknown': json['unknown'],
+ 'spentCredits': json['spent_credits'],
+ 'notAttributed': json['not_attributed'],
};
}
@@ -68,7 +68,7 @@ export function SpendToJSONTyped(value?: Spend | null, ignoreDiscriminator: bool
return {
- 'measured_usd': value['measuredUsd'],
- 'unknown': value['unknown'],
+ 'spent_credits': value['spentCredits'],
+ 'not_attributed': value['notAttributed'],
};
}
diff --git a/modal_shared/container_meter.py b/modal_shared/container_meter.py
new file mode 100644
index 00000000..0d3064ba
--- /dev/null
+++ b/modal_shared/container_meter.py
@@ -0,0 +1,242 @@
+"""What a Modal container that does a customer's work holds and whom it served.
+
+Every container reports to one Dict, about once a minute: its GPU type and count, the CPU
+cores and memory Modal bills it for (the greater of the request and the use, sampled every
+few seconds) and the seconds it spent on each billing ref, such as ``finetune_job:<id>``.
+The API reads the Dict and charges container seconds at Modal's rates
+(overbae/services/container_meter.py). Nothing here prices anything.
+"""
+
+import asyncio
+import atexit
+import contextlib
+import functools
+import inspect
+import logging
+import os
+import subprocess
+import threading
+import time
+
+import modal
+
+STORE = "overmind-container-meter"
+# Overrides the container's own ref for one request, as for an evaluation that calls a
+# fine-tuned model. The API checks that the ref is of the same project.
+REF_HEADER = "x-overmind-billing-ref"
+REF_ENV = "OVERMIND_BILLING_REF"
+PUBLISH_SECONDS = 60
+SAMPLE_SECONDS = 5
+# Modal's request for a function that names no CPU or memory.
+DEFAULT_CPU = 0.125
+DEFAULT_MEMORY_GIB = 0.125
+
+logger = logging.getLogger(__name__)
+
+_GPU_NAMES = (
+ ("H200", "H200"),
+ ("H100", "H100"),
+ ("B200", "B200"),
+ ("A100-SXM4-80GB", "A100-80GB"),
+ ("A100 80GB", "A100-80GB"),
+ ("A100", "A100-40GB"),
+ ("L40S", "L40S"),
+ ("A10", "A10"),
+ ("L4", "L4"),
+ ("T4", "T4"),
+ ("RTX PRO 6000", "RTX-PRO-6000"),
+)
+
+
+def gpus():
+ """The container's GPU type, in Modal's names, and count; none without a GPU."""
+ try:
+ names = subprocess.run( # noqa: S603
+ ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], # noqa: S607
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=True,
+ ).stdout.split("\n")
+ except (OSError, subprocess.SubprocessError):
+ return None, 0
+ names = [name.strip() for name in names if name.strip()]
+ if not names:
+ return None, 0
+ for marker, modal_name in _GPU_NAMES:
+ if marker in names[0]:
+ return modal_name, len(names)
+ return names[0], len(names)
+
+
+def _cpu_seconds():
+ """CPU seconds the container's processes used, from the sandbox's /proc/stat."""
+ try:
+ with open("/proc/stat") as stat:
+ fields = stat.readline().split()[1:]
+ ticks = os.sysconf("SC_CLK_TCK")
+ user, nice, system = (int(value) for value in fields[:3])
+ return (user + nice + system) / ticks
+ except (OSError, ValueError, IndexError):
+ return None
+
+
+def _memory_gib():
+ try:
+ with open("/proc/meminfo") as meminfo:
+ values = {line.split(":")[0]: int(line.split()[1]) for line in meminfo if ":" in line}
+ return (values["MemTotal"] - values["MemAvailable"]) / 1024**2
+ except (OSError, ValueError, KeyError, IndexError):
+ return None
+
+
+class ContainerMeter:
+ def __init__(self):
+ self.lock = threading.Lock()
+ self.function = ""
+ self.gpu, self.gpu_count = None, 0
+ self.cpu, self.memory_gib = DEFAULT_CPU, DEFAULT_MEMORY_GIB
+ self.default_ref = None
+ self.active = {}
+ self.thread = None
+ self._start()
+
+ def _start(self):
+ """This container's identity and zero counters. A container restored from a memory
+ snapshot runs this again: the snapshot holds another container's identity and time."""
+ self.container = os.environ.get("MODAL_TASK_ID", "")
+ self.started_at = time.time()
+ self.refs = {}
+ self.last_ref = None
+ self.cpu_core_seconds = 0.0
+ self.memory_gib_seconds = 0.0
+ self.measured = True
+ self.sampled_at = time.monotonic()
+ self.cpu_seen = _cpu_seconds()
+
+ def configure(self, function, *, cpu=None, memory_gib=None, ref=None):
+ """Name the container's function, its CPU and memory request, and the ref its idle
+ and unattributed time goes to."""
+ with self.lock:
+ self.function = function or self.function
+ self.cpu = cpu if cpu is not None else self.cpu
+ self.memory_gib = memory_gib if memory_gib is not None else self.memory_gib
+ self.default_ref = ref or self.default_ref
+ if self.container != os.environ.get("MODAL_TASK_ID", ""):
+ self._start()
+ if self.thread is None and self.container:
+ self.gpu, self.gpu_count = gpus()
+ self.thread = threading.Thread(target=self._run, daemon=True)
+ self.thread.start()
+ atexit.register(self.publish, stopped=True)
+
+ @contextlib.contextmanager
+ def serving(self, ref):
+ """Count the seconds inside the block toward ``ref``."""
+ ref = ref or self.default_ref
+ token = object()
+ with self.lock:
+ if ref:
+ self.active[token] = (ref, time.monotonic())
+ try:
+ yield
+ finally:
+ with self.lock:
+ started = self.active.pop(token, None)
+ if started:
+ self.refs[ref] = self.refs.get(ref, 0.0) + time.monotonic() - started[1]
+ self.last_ref = ref
+
+ def _sample(self):
+ if self.container != os.environ.get("MODAL_TASK_ID", ""):
+ self._start()
+ return
+ now = time.monotonic()
+ elapsed, self.sampled_at = now - self.sampled_at, now
+ cpu, memory = _cpu_seconds(), _memory_gib()
+ if cpu is None or memory is None or self.cpu_seen is None:
+ # Billed at the request alone, which is below what Modal bills for heavier use.
+ self.measured = False
+ used = cpu - self.cpu_seen if cpu is not None and self.cpu_seen is not None else 0.0
+ # A failed read restarts the baseline: the request already covered that interval.
+ self.cpu_seen = cpu
+ self.cpu_core_seconds += max(self.cpu * elapsed, used)
+ self.memory_gib_seconds += max(self.memory_gib, memory or 0.0) * elapsed
+
+ def beat(self, *, stopped=False):
+ with self.lock:
+ self._sample()
+ now = time.monotonic()
+ refs = dict(self.refs)
+ for ref, started in self.active.values():
+ refs[ref] = refs.get(ref, 0.0) + now - started
+ return {
+ "container": self.container,
+ "function": self.function,
+ "environment": os.environ.get("MODAL_ENVIRONMENT", ""),
+ "gpu": self.gpu,
+ "gpu_count": self.gpu_count,
+ "cpu": self.cpu,
+ "memory_gib": self.memory_gib,
+ "started_at": self.started_at,
+ "seen_at": time.time(),
+ "wall_seconds": time.time() - self.started_at,
+ "cpu_core_seconds": self.cpu_core_seconds,
+ "memory_gib_seconds": self.memory_gib_seconds,
+ "usage_measured": self.measured,
+ "refs": refs,
+ "last_ref": self.last_ref or self.default_ref,
+ "default_ref": self.default_ref,
+ "stopped": stopped,
+ }
+
+ def publish(self, *, stopped=False):
+ # Losing a report must never fail the customer's work; the next one carries totals.
+ try:
+ value = self.beat(stopped=stopped)
+ store = modal.Dict.from_name(STORE, create_if_missing=True)
+
+ async def put():
+ await asyncio.wait_for(store.put.aio(self.container, value), timeout=10)
+
+ asyncio.run(put())
+ except Exception:
+ logger.warning("Container meter report unavailable", exc_info=False)
+
+ def _run(self):
+ published = time.monotonic()
+ self.publish()
+ while True:
+ time.sleep(SAMPLE_SECONDS)
+ if time.monotonic() - published >= PUBLISH_SECONDS:
+ self.publish()
+ published = time.monotonic()
+ else:
+ with self.lock:
+ self._sample()
+
+
+METER = ContainerMeter()
+
+
+def serving(ref, *, function, cpu=None, memory_gib=None):
+ """Meter this container from now on and count the block toward ``ref``."""
+ METER.configure(function, cpu=cpu, memory_gib=memory_gib, ref=ref)
+ return METER.serving(ref)
+
+
+def metered(ref_of, *, cpu=None, memory_gib=None):
+ """Meter a Modal function: ``ref_of`` maps its keyword arguments to the billing ref."""
+
+ def wrap(fn):
+ signature = inspect.signature(fn)
+
+ @functools.wraps(fn)
+ def run(*args, **kwargs):
+ arguments = signature.bind(*args, **kwargs).arguments
+ with serving(ref_of(**arguments), function=fn.__name__, cpu=cpu, memory_gib=memory_gib):
+ return fn(*args, **kwargs)
+
+ return run
+
+ return wrap
diff --git a/overbae/api/billing.py b/overbae/api/billing.py
index 04407838..e9f856d3 100644
--- a/overbae/api/billing.py
+++ b/overbae/api/billing.py
@@ -4,10 +4,12 @@ import logging
import stripe
from django.conf import settings
+from django.core.exceptions import ValidationError as DjangoValidationError
from django.db.models import Case, F, Value, When
from django.db.models.functions import Concat, Replace, Substr, Upper
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.utils import OpenApiParameter, extend_schema
from rest_framework import generics, status
+from rest_framework import serializers as drf_serializers
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
@@ -63,6 +65,11 @@ class BillingLedgerView(generics.ListAPIView):
@extend_schema(
summary="List billing ledger entries",
+ parameters=[
+ OpenApiParameter(name, str, required=False)
+ for name in ("project", "experiment", "run", "service", "cause_kind", "cause_id")
+ ]
+ + [OpenApiParameter("usage", bool, required=False, description="Only charges")],
responses={200: BillingTelemetrySerializer(many=True)},
)
def get(self, request, *args, **kwargs):
@@ -73,8 +80,23 @@ class BillingLedgerView(generics.ListAPIView):
if isinstance(self.request.auth, APIToken) and not self.request.auth.is_account_scoped:
# A project key reads its project's entries, not the whole account's.
rows = rows.filter(project_id__in=self.request.auth.allowed_project_ids())
+ query = self.request.query_params
+ filters = {
+ "project_id": query.get("project"),
+ "experiment_id": query.get("experiment"),
+ "run_id": query.get("run"),
+ "service": query.get("service"),
+ "cause_kind": query.get("cause_kind"),
+ "cause_id": query.get("cause_id"),
+ }
+ try:
+ rows = rows.filter(**{key: value for key, value in filters.items() if value})
+ except DjangoValidationError:
+ raise drf_serializers.ValidationError("A filter names no valid id.") from None
+ if query.get("usage") in ("true", "1"):
+ rows = rows.filter(amount__lt=0)
return (
- rows.select_related("project")
+ rows.select_related("project", "actor")
.annotate(
service_name=Case(
*[
diff --git a/overbae/api/completions.py b/overbae/api/completions.py
index 69e15a44..939066f0 100644
--- a/overbae/api/completions.py
+++ b/overbae/api/completions.py
@@ -13,7 +13,6 @@ import logging
import math
import time
import uuid
-from decimal import Decimal
from itertools import chain
from typing import Any
@@ -29,7 +28,12 @@ from rest_framework.request import Request
from rest_framework.response import Response
from modal_shared.context_budget import is_context_limit_error, reserve_output
-from overbae.api.scoping import project_ids_for
+from overbae.api.scoping import (
+ PROJECT_REQUIRED,
+ charged_project,
+ project_ids_for,
+ request_cause_id,
+)
from overbae.api.streaming import (
JSON_IDLE_PING,
SSE_IDLE_PING,
@@ -42,9 +46,8 @@ from overbae.models import (
BillingService,
Capability,
DeployedModel,
- User,
)
-from overbae.services.billing_ledger import InsufficientCredits, charge_credits, ensure_credits
+from overbae.services import billing_ledger, model_meter
from overbae.services.deployed_chat import is_cold_start, record_inference_call
from overbae.services.inference_client import (
CONTEXT_BUDGET_MESSAGE,
@@ -53,7 +56,6 @@ from overbae.services.inference_client import (
InferenceClientError,
get_inference_client,
)
-from overbae.services.model_catalog import estimate_cost
logger = logging.getLogger(__name__)
@@ -70,34 +72,23 @@ def _credits_required_response() -> Response:
)
-def _charge_frontier_usage(user: User, model_id: str, usage: dict | None) -> None:
- """Prefers OpenRouter's own ``usage.cost`` so a routed model is billed exactly
- what OpenRouter charged, else catalog pricing. A model with no known price is
- not charged at all, never charged zero. Never raises."""
- if not usage:
- return
- try:
- reported = usage.get("cost")
- cost = (
- reported
- if isinstance(reported, (int, float)) and reported > 0
- else estimate_cost(
- model_id,
- int(usage.get("prompt_tokens") or 0),
- int(usage.get("completion_tokens") or 0),
- )
- )
- if not cost:
- return
- charge_credits(
- user,
- Decimal(str(cost)),
- BillingService.INFERENCE,
- idempotency_key=f"inference:{user.pk}:{uuid.uuid4()}",
- metadata={"model_id": model_id, "usage": usage},
- )
- except Exception:
- logger.exception("Failed to charge frontier inference for user_id=%s", user.pk)
+def _project_required_response() -> Response:
+ return Response(
+ {"error": {"message": PROJECT_REQUIRED, "type": "invalid_request_error"}},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+
+def _settle_frontier(found, model_id: str, captured: dict | None) -> None:
+ usage = (captured or {}).get("usage") or {}
+ model_meter.settle(
+ (captured or {}).get("id"),
+ usage.get("cost"),
+ model=(captured or {}).get("model") or model_id,
+ prompt_tokens=usage.get("prompt_tokens"),
+ completion_tokens=usage.get("completion_tokens"),
+ found=found,
+ )
def _process_stream_chunk(raw: str, captured: dict[str, Any], include_usage: bool) -> str | None:
@@ -123,6 +114,9 @@ def _process_stream_chunk(raw: str, captured: dict[str, Any], include_usage: boo
metrics = obj.get("metrics")
if metrics:
captured["metrics"] = metrics
+ # The generation id that the provider bills the stream under.
+ if obj.get("id") and "id" not in captured:
+ captured["id"], captured["model"] = obj["id"], obj.get("model")
usage = obj.get("usage")
if usage:
@@ -395,11 +389,6 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:
status=status.HTTP_400_BAD_REQUEST,
)
- try:
- ensure_credits(request.user)
- except InsufficientCredits:
- return _credits_required_response()
-
extra: dict = {}
for key in ("top_p", "frequency_penalty", "presence_penalty"):
val = data.get(key)
@@ -458,11 +447,20 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:
status=status.HTTP_503_SERVICE_UNAVAILABLE,
)
+ project = charged_project(request)
+ if project is None:
+ return _project_required_response()
+ if not billing_ledger.can_spend(project):
+ return _credits_required_response()
+ found = billing_ledger.cause(
+ project, BillingService.INFERENCE, *request_cause_id(request), actor=request.user
+ )
payload: dict = {
"model": model_id,
"messages": messages,
"stream": stream,
"temperature": temperature,
+ "usage": {"include": True},
**extra,
}
if max_tokens:
@@ -482,7 +480,7 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:
if forwarded is not None:
yield forwarded
finally:
- _charge_frontier_usage(request.user, model_id, captured.get("usage"))
+ _settle_frontier(found, model_id, captured)
return StreamingHttpResponse(
AsyncStream(event_stream()),
@@ -510,7 +508,7 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:
status=status.HTTP_502_BAD_GATEWAY,
)
if isinstance(result, dict):
- _charge_frontier_usage(request.user, model_id, result.get("usage"))
+ _settle_frontier(found, model_id, result)
return Response(result, status=status.HTTP_200_OK)
if deployed is None:
@@ -529,6 +527,9 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:
},
status=status.HTTP_404_NOT_FOUND,
)
+ # The model's project owner pays for its serving time.
+ if not billing_ledger.can_spend(deployed.project_id):
+ return _credits_required_response()
if deployed.status != DeployedModel.Status.READY:
return Response(
@@ -550,7 +551,6 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:
client = _get_client()
- billing_user = request.user
request_id = uuid.uuid4()
call_context = {
"request_id": request_id,
@@ -637,7 +637,6 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:
captured["usage"],
latency_ms,
cold,
- user=billing_user,
metrics=captured.get("metrics"),
outcome=outcome,
error_code=error_code,
@@ -702,7 +701,6 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:
held.get("usage"),
round((time.monotonic() - t_start) * 1000, 1),
cold,
- user=billing_user,
metrics=held.get("metrics"),
outcome=held["outcome"],
error_code=held["error_code"],
@@ -757,6 +755,8 @@ def _dedicated_chat(request, model_id: str, data: dict, started_at):
},
status=status.HTTP_404_NOT_FOUND,
)
+ if not billing_ledger.can_spend(row.project_id):
+ return _credits_required_response()
if data.get("stream"):
return _dedicated_chat_stream(request, row, data, started_at)
try:
@@ -789,12 +789,10 @@ def _dedicated_chat(request, model_id: str, data: dict, started_at):
row.deployed_model,
usage,
(timezone.now() - started_at).total_seconds() * 1000,
- user=request.user,
outcome="succeeded" if upstream < 400 else "failed",
error_code="" if upstream < 400 else "inference_rejected",
source="application" if isinstance(request.auth, APIToken) else "internal",
requested_model=model_id,
- bill=False,
)
if "text/event-stream" in content_type:
return StreamingHttpResponse(
@@ -906,13 +904,11 @@ def _dedicated_chat_stream(request, row, data: dict, started_at):
row.deployed_model,
captured["usage"],
(timezone.now() - started_at).total_seconds() * 1000,
- user=request.user,
metrics=captured.get("metrics"),
outcome=outcome,
error_code=error_code,
source="application" if isinstance(request.auth, APIToken) else "internal",
requested_model=public_id,
- bill=False,
)
return StreamingHttpResponse(
diff --git a/overbae/api/credit_gate.py b/overbae/api/credit_gate.py
index b9bf3833..bf7e3d4f 100644
--- a/overbae/api/credit_gate.py
+++ b/overbae/api/credit_gate.py
@@ -1,13 +1,13 @@
-"""Credit gate for user-initiated paid work.
+"""Credit gate for paid work a person or agent starts.
-Binary: any positive balance passes, whatever the job costs. ``completions.py``
-gates separately to answer in OpenAI's error shape; background work (webhooks,
-cron, OTLP ingest, reconcilers) is never gated.
+The project's owner pays, so their balance must be above zero, whatever the work costs;
+a negative balance is allowed and shown. ``completions.py`` gates separately to answer in
+OpenAI's error shape. Background work pauses at zero instead (``billing_ledger.can_spend``).
"""
from rest_framework.exceptions import APIException
-from overbae.services.billing_ledger import InsufficientCredits, ensure_credits
+from overbae.services.billing_ledger import can_spend
__all__ = ["PaymentRequired", "require_credits"]
@@ -18,8 +18,7 @@ class PaymentRequired(APIException):
default_code = "insufficient_credits"
-def require_credits(user) -> None:
- try:
- ensure_credits(user)
- except InsufficientCredits as exc:
- raise PaymentRequired() from exc
+def require_credits(project) -> None:
+ """``project`` is a project or its id."""
+ if not can_spend(getattr(project, "pk", project)):
+ raise PaymentRequired()
diff --git a/overbae/api/decision.py b/overbae/api/decision.py
index ac40bd6e..46e2d128 100644
--- a/overbae/api/decision.py
+++ b/overbae/api/decision.py
@@ -119,7 +119,7 @@ class DecisionJobViewSet(
def admit_new_training():
from overbae.api.credit_gate import require_credits
- require_credits(request.user)
+ require_credits(project)
try:
job = decision_jobs.create(
diff --git a/overbae/api/decision_performance.py b/overbae/api/decision_performance.py
index 83518ec8..2b3da1e1 100644
--- a/overbae/api/decision_performance.py
+++ b/overbae/api/decision_performance.py
@@ -80,7 +80,7 @@ class DecisionPerformanceViewSet(
pk=values.pop("evaluation"),
project_id__in=project_ids_for(request.user, request.auth),
)
- require_credits(request.user)
+ require_credits(evaluation.project_id)
try:
run = decision_performance.create(evaluation, **values)
except InputValidationError as exc:
@@ -100,6 +100,7 @@ class DecisionPerformanceViewSet(
run = self.get_object()
if run.state != "failed":
raise ValidationError("Only stopped measurements can be resumed")
+ require_credits(run.project_id)
DecisionPerformanceRun.objects.filter(pk=run.pk, state="failed").update(
state="queued", error=""
)
diff --git a/overbae/api/eval_serializers.py b/overbae/api/eval_serializers.py
index d4471e09..588f1704 100644
--- a/overbae/api/eval_serializers.py
+++ b/overbae/api/eval_serializers.py
@@ -215,8 +215,8 @@ class EvaluationContextSuggestionSerializer(serializers.Serializer):
context_window = serializers.IntegerField()
max_output_tokens = serializers.IntegerField()
reserved_output_tokens = serializers.IntegerField()
- estimated_cost_usd = serializers.FloatField(allow_null=True)
- cost_delta_usd = serializers.FloatField(allow_null=True)
+ estimated_credits = serializers.FloatField(allow_null=True)
+ credits_delta = serializers.FloatField(allow_null=True)
class EvaluationContextCheckSerializer(serializers.Serializer):
@@ -236,7 +236,7 @@ class EvaluationContextCheckSerializer(serializers.Serializer):
estimated = serializers.BooleanField()
status = serializers.CharField()
message = serializers.CharField(allow_blank=True)
- estimated_cost_usd = serializers.FloatField(allow_null=True, default=None)
+ estimated_credits = serializers.FloatField(allow_null=True, default=None)
cost_basis = serializers.CharField(allow_blank=True, default="")
suggestions = EvaluationContextSuggestionSerializer(many=True, default=list)
suggestion_note = serializers.CharField(allow_blank=True, default="")
@@ -395,7 +395,7 @@ class EvalRunCreateSerializer(EvaluationScopeSerializer):
)
return {"group": prior[0].group, "runs": prior}
if gate:
- gate()
+ gate(data["project"])
return self._create(data, key, asked, **kwargs)
def _create(self, data, key, asked, **kwargs) -> dict:
diff --git a/overbae/api/eval_views.py b/overbae/api/eval_views.py
index 2a262c0f..923f48e7 100644
--- a/overbae/api/eval_views.py
+++ b/overbae/api/eval_views.py
@@ -246,9 +246,7 @@ class EvalRunViewSet(
serializer = EvalRunCreateSerializer(data=request.data, context={"request": request})
serializer.is_valid(raise_exception=True)
try:
- created = serializer.save(
- gate=lambda: require_credits(request.user), triggered_by=request.user
- )
+ created = serializer.save(gate=require_credits, triggered_by=request.user)
except runs.RunError as exc:
raise ValidationError({"detail": str(exc)}) from exc
return Response(
@@ -340,7 +338,7 @@ class EvalRunViewSet(
@action(detail=True, methods=["post"])
def run(self, request, id=None):
run = self.get_object()
- require_credits(request.user)
+ require_credits(run.project_id)
try:
launched = runs.relaunch(run)
except runs.RunError as exc:
diff --git a/overbae/api/experiments.py b/overbae/api/experiments.py
index d043773e..91258c97 100644
--- a/overbae/api/experiments.py
+++ b/overbae/api/experiments.py
@@ -63,7 +63,7 @@ class ExperimentTriggerSerializer(serializers.Serializer):
threshold = serializers.IntegerField(allow_null=True)
sends = serializers.IntegerField()
max_sends = serializers.IntegerField()
- max_spend_usd = serializers.DecimalField(max_digits=10, decimal_places=2, allow_null=True)
+ max_spend_credits = serializers.DecimalField(max_digits=12, decimal_places=2, allow_null=True)
next_at = serializers.DateTimeField(allow_null=True)
last_sent_at = serializers.DateTimeField(allow_null=True)
@@ -93,8 +93,8 @@ class ProposalSerializer(serializers.Serializer):
class SpendSerializer(serializers.Serializer):
- measured_usd = serializers.FloatField()
- unknown = serializers.ListField(child=serializers.CharField())
+ spent_credits = serializers.FloatField()
+ not_attributed = serializers.ListField(child=serializers.CharField())
class ExperimentDetailSerializer(ExperimentSerializer):
@@ -234,8 +234,8 @@ class ExperimentTriggerInputSerializer(serializers.Serializer):
instruction = serializers.CharField(max_length=8000)
hours = serializers.IntegerField(min_value=1, max_value=720)
max_sends = serializers.IntegerField(min_value=1, max_value=100)
- max_spend_usd = serializers.DecimalField(
- max_digits=10, decimal_places=2, min_value=Decimal("0.01"), required=False, default=None
+ max_spend_credits = serializers.DecimalField(
+ max_digits=12, decimal_places=2, min_value=Decimal("1"), required=False, default=None
)
capability = serializers.UUIDField(required=False, allow_null=True, default=None)
threshold = serializers.IntegerField(min_value=1, required=False, allow_null=True, default=None)
diff --git a/overbae/api/inference_requests.py b/overbae/api/inference_requests.py
index 2c30a84f..202f1c93 100644
--- a/overbae/api/inference_requests.py
+++ b/overbae/api/inference_requests.py
@@ -5,10 +5,10 @@ from rest_framework.response import Response
from rest_framework.views import APIView
from overbae.api.credit_gate import require_credits
-from overbae.api.scoping import project_ids_for
+from overbae.api.scoping import PROJECT_REQUIRED, charged_project, project_ids_for, request_cause_id
from overbae.core.errors import InputValidationError
-from overbae.models import APIToken, DeployedModel, InferenceRequest
-from overbae.services import inference_requests, systemone
+from overbae.models import APIToken, BillingService, DeployedModel, InferenceRequest
+from overbae.services import billing_ledger, inference_requests, systemone
class DecisionInputSerializer(serializers.Serializer):
@@ -67,7 +67,7 @@ class DeploymentInferenceView(APIView):
try:
receipt = inference_requests.recover_existing(deployed, key, inputs)
if receipt is None:
- require_credits(request.user)
+ require_credits(deployed.project_id)
receipt = inference_requests.submit(
deployed,
request.user,
@@ -99,6 +99,7 @@ def _dedicated_systemone(request, model):
},
status=404,
)
+ require_credits(row.project_id)
started = timezone.now()
try:
result = serve_systemone(row, request.data)
@@ -115,10 +116,8 @@ def _dedicated_systemone(request, model):
row.deployed_model,
result.get("usage"),
elapsed_ms,
- user=request.user,
source="application" if isinstance(request.auth, APIToken) else "playground",
requested_model=model,
- bill=False,
)
answers = result.get("answers")
if not isinstance(answers, dict):
@@ -166,14 +165,27 @@ class SystemOneView(APIView):
},
status=404,
)
- require_credits(request.user)
try:
if deployment is not None:
+ require_credits(deployment.project_id)
status_code, payload = systemone.call_deployment(
deployment, request.user, request.auth, names, decisions
)
else:
- status_code, payload = systemone.call_openrouter(request.user, body)
+ project = charged_project(request)
+ if project is None:
+ return Response(
+ {"error": {"message": PROJECT_REQUIRED, "type": "invalid_request"}},
+ status=400,
+ )
+ require_credits(project)
+ found = billing_ledger.cause(
+ project,
+ BillingService.INFERENCE,
+ *request_cause_id(request),
+ actor=request.user,
+ )
+ status_code, payload = systemone.call_openrouter(found, body)
except InputValidationError as exc:
return Response(
{"error": {"message": exc.detail, "type": "invalid_request"}},
diff --git a/overbae/api/native_evaluation.py b/overbae/api/native_evaluation.py
index 2756fc04..8b91f8c1 100644
--- a/overbae/api/native_evaluation.py
+++ b/overbae/api/native_evaluation.py
@@ -353,8 +353,9 @@ class NativeEvaluationViewSet(
@extend_schema(request=None, responses={202: NativeEvaluationSerializer})
@action(detail=True, methods=["post"], url_path="launch")
def launch_evaluation(self, request, pk=None):
- require_credits(request.user)
- plan = launch(self.get_object(), user=request.user)
+ plan = self.get_object()
+ require_credits(plan.project_id)
+ plan = launch(plan, user=request.user)
return Response(NativeEvaluationSerializer(plan).data, status=202)
@extend_schema(request=None, responses=NativeEvaluationSerializer)
@@ -371,7 +372,9 @@ class NativeEvaluationViewSet(
@extend_schema(request=None, responses={202: NativeEvaluationSerializer})
@action(detail=True, methods=["post"])
def prepare(self, request, pk=None):
- return Response(NativeEvaluationSerializer(prepare(self.get_object())).data, status=202)
+ plan = self.get_object()
+ require_credits(plan.project_id)
+ return Response(NativeEvaluationSerializer(prepare(plan)).data, status=202)
@extend_schema(request=EvaluationReuseSerializer, responses=NativeEvaluationSerializer)
@action(detail=True, methods=["post"], url_path="reuse")
@@ -399,8 +402,10 @@ class NativeEvaluationViewSet(
def resume_evaluation(self, request, pk=None):
body = EvaluationResumeSerializer(data=request.data)
body.is_valid(raise_exception=True)
+ plan = self.get_object()
+ require_credits(plan.project_id)
try:
- plan = resume(self.get_object(), user=request.user, **body.validated_data)
+ plan = resume(plan, user=request.user, **body.validated_data)
except InputValidationError as exc:
raise ValidationError(exc.detail) from None
except ValueError:
diff --git a/overbae/api/scoping.py b/overbae/api/scoping.py
index f3e4b590..5460c63c 100644
--- a/overbae/api/scoping.py
+++ b/overbae/api/scoping.py
@@ -14,3 +14,26 @@ def project_ids_for(user, auth=None):
if isinstance(auth, APIToken):
return auth.allowed_project_ids()
return ProjectMembership.objects.filter(user=user).values_list("project_id", flat=True)
+
+
+PROJECT_HEADER = "X-Overmind-Project"
+PROJECT_REQUIRED = (
+ "Name the project to charge: use a project API key or send the X-Overmind-Project header."
+)
+
+
+def charged_project(request) -> str | None:
+ """The project a gateway call is charged to: the key's one project, the one the caller
+ names in ``X-Overmind-Project``, or the caller's only project."""
+ allowed = [str(pk) for pk in project_ids_for(request.user, request.auth)]
+ named = request.headers.get(PROJECT_HEADER)
+ if named:
+ return named if named in allowed else None
+ return allowed[0] if len(allowed) == 1 else None
+
+
+def request_cause_id(request) -> tuple[str, str]:
+ """What started a gateway call: the API key, or the signed-in user."""
+ if isinstance(request.auth, APIToken):
+ return "api_key", str(request.auth.pk)
+ return "user", str(request.user.pk)
diff --git a/overbae/api/serializers.py b/overbae/api/serializers.py
index 2d5e93ba..98620903 100644
--- a/overbae/api/serializers.py
+++ b/overbae/api/serializers.py
@@ -1,6 +1,7 @@
import logging
import math
from datetime import timedelta
+from decimal import Decimal
from types import SimpleNamespace
from django.conf import settings
@@ -43,7 +44,7 @@ from overbae.models import (
User,
UserOnboarding,
)
-from overbae.services.billing_ledger import MAX_TOPUP_USD, MIN_TOPUP_USD
+from overbae.services.billing_ledger import CREDITS_PER_USD, MAX_TOPUP_USD, MIN_TOPUP_USD
from overbae.services.codebase.flow import (
build_capability_flow,
capability_input_keys,
@@ -2792,6 +2793,10 @@ class BillingAccountSerializer(serializers.Serializer):
credits_usd = serializers.DecimalField(max_digits=12, decimal_places=4)
credits_granted_usd = serializers.DecimalField(max_digits=12, decimal_places=4)
credits_spent_usd = serializers.DecimalField(max_digits=12, decimal_places=4)
+ balance_credits = serializers.DecimalField(max_digits=16, decimal_places=2)
+ spent_credits = serializers.DecimalField(max_digits=16, decimal_places=2)
+ # Scoring, signals and scheduled work of the account's projects wait for a top-up.
+ background_paused = serializers.BooleanField()
class CreditTopUpConfirmationSerializer(serializers.Serializer):
@@ -2800,28 +2805,53 @@ class CreditTopUpConfirmationSerializer(serializers.Serializer):
class BillingTelemetrySerializer(serializers.ModelSerializer):
- """One credits ledger row for the authenticated user."""
+ """One credits ledger row for the authenticated user: a provider cost at its price, with
+ what caused it and who started it."""
project_id = serializers.UUIDField(allow_null=True, read_only=True)
project_name = serializers.CharField(source="project.name", allow_null=True, read_only=True)
# Append-only receipts can outlive the service that created them.
service = serializers.CharField(read_only=True)
service_label = serializers.SerializerMethodField()
+ experiment_id = serializers.UUIDField(allow_null=True, read_only=True)
+ run_id = serializers.UUIDField(allow_null=True, read_only=True)
+ actor_email = serializers.EmailField(source="actor.email", allow_null=True, read_only=True)
+ credits = serializers.SerializerMethodField()
+ unit_credits = serializers.SerializerMethodField()
def get_service_label(self, obj) -> str:
label = obj.get_service_display()
return obj.service.replace("-", " ").capitalize() if label == obj.service else label
+ def get_credits(self, obj) -> Decimal:
+ return obj.amount * CREDITS_PER_USD
+
+ def get_unit_credits(self, obj) -> Decimal | None:
+ return None if obj.unit_usd is None else obj.unit_usd * CREDITS_PER_USD
+
class Meta:
model = BillingTelemetry
fields = [
"id",
"amount",
+ "credits",
"timestamp",
"service",
"service_label",
"project_id",
"project_name",
+ "cause_kind",
+ "cause_id",
+ "experiment_id",
+ "run_id",
+ "actor_email",
+ "resource",
+ "quantity",
+ "unit",
+ "unit_credits",
+ "provider_ref",
+ "started_at",
+ "ended_at",
]
@@ -2943,7 +2973,6 @@ class InferenceMetricsSerializer(serializers.Serializer):
dedicated_usage = DedicatedUsageSerializer()
last_request_at = serializers.DateTimeField(allow_null=True)
- cost_recorded_request_count = serializers.IntegerField()
failed_request_count = serializers.IntegerField()
cold_request_count = serializers.IntegerField()
end_to_end_p50_ms = serializers.FloatField(allow_null=True)
diff --git a/overbae/api/training_experiments.py b/overbae/api/training_experiments.py
index 561cecbc..88a092fc 100644
--- a/overbae/api/training_experiments.py
+++ b/overbae/api/training_experiments.py
@@ -145,7 +145,7 @@ class TrainingExperimentViewSet(
)
@action(detail=True, methods=["post"])
def launch(self, request, pk=None):
- require_credits(request.user)
+ require_credits(self.get_object().project_id)
body = ExperimentLaunchSerializer(data=request.data)
body.is_valid(raise_exception=True)
try:
@@ -164,8 +164,10 @@ class TrainingExperimentViewSet(
@extend_schema(request=None, responses=TrainingExperimentSerializer)
@action(detail=True, methods=["post"])
def prepare(self, request, pk=None):
+ found = self.get_object()
+ require_credits(found.project_id)
try:
- experiment = training_experiments.request_preparation(self.get_object())
+ experiment = training_experiments.request_preparation(found)
except InputValidationError as exc:
raise ValidationError(exc.detail) from None
except ValueError:
diff --git a/overbae/api/training_preparation.py b/overbae/api/training_preparation.py
index 4ddb0418..e656c66a 100644
--- a/overbae/api/training_preparation.py
+++ b/overbae/api/training_preparation.py
@@ -7,6 +7,7 @@ from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
+from overbae.api.credit_gate import require_credits
from overbae.api.scoping import project_ids_for
from overbae.core.errors import InputValidationError
from overbae.models import Dataset, DecisionJob, TrainingPreparation
@@ -74,8 +75,10 @@ class TrainingPreparationViewSet(mixins.RetrieveModelMixin, viewsets.GenericView
@extend_schema(request=None, responses={202: TrainingPreparationSerializer})
@action(detail=True, methods=["post"])
def retry(self, request, pk=None):
+ found = self.get_object()
+ require_credits(found.cell.dataset.project_id)
try:
- preparation = retry_preparation(self.get_object())
+ preparation = retry_preparation(found)
except InputValidationError as exc:
raise ValidationError(exc.detail) from exc
except (ValueError, RuntimeError, OSError) as exc:
@@ -115,6 +118,7 @@ class TrainingPreparationViewSet(mixins.RetrieveModelMixin, viewsets.GenericView
raise ValidationError("Validation dataset has no completed version.")
if cell is None:
raise ValidationError("Training dataset has no completed version.")
+ require_credits(dataset.project_id)
try:
preparation = begin_preparation(
cell,
diff --git a/overbae/api/views.py b/overbae/api/views.py
index b80a2092..5076f3b4 100644
--- a/overbae/api/views.py
+++ b/overbae/api/views.py
@@ -5,6 +5,7 @@ from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import (
Avg,
+ CharField,
Count,
Exists,
FloatField,
@@ -15,6 +16,7 @@ from django.db.models import (
Q,
Subquery,
Sum,
+ Value,
)
from django.db.models.expressions import RawSQL
from django.db.models.fields.json import KeyTextTransform
@@ -109,6 +111,7 @@ from overbae.api.training_monitoring import (
from overbae.core.errors import InputValidationError
from overbae.models import (
APIToken,
+ BillingTelemetry,
Cell,
ConnectorCredential,
Conversation,
@@ -714,8 +717,8 @@ class FinetuningJobViewSet(viewsets.ModelViewSet):
def native_evaluation(self, request, id=None):
from overbae.api.credit_gate import require_credits
- require_credits(request.user)
job = self.get_object()
+ require_credits(job.project_id)
body = NativeEvaluationRequestSerializer(data=request.data)
body.is_valid(raise_exception=True)
cells = Cell.objects.select_related("dataset").filter(dataset__project_id=job.project_id)
@@ -781,7 +784,7 @@ class FinetuningJobViewSet(viewsets.ModelViewSet):
from overbae.tasks.finetuning import run_finetuning
def admit_new_training():
- require_credits(self.request.user)
+ require_credits(serializer.validated_data["project"])
serializer.context["admit_new_training"] = admit_new_training
job = serializer.save(triggered_by=self.request.user)
@@ -1019,7 +1022,7 @@ class FinetuningJobViewSet(viewsets.ModelViewSet):
inspect_preparation.delay(str(prep.pk))
job.refresh_from_db()
return Response(FinetuningJobSerializer(job).data)
- require_credits(request.user)
+ require_credits(job.project_id)
try:
retry_training_preparation(job)
reset_before_evals_for_retry(job)
@@ -1980,6 +1983,27 @@ class ConnectorCredentialViewSet(viewsets.ModelViewSet):
return Response({"projects": [{"id": p.id, "name": p.name} for p in projects]})
+def _serving_cost(**window):
+ """The ledger's charges for a deployed model's serving containers, shared and dedicated,
+ in USD."""
+ dedicated = DedicatedDeployment.objects.filter(deployed_model=OuterRef(OuterRef("pk"))).values(
+ id_text=Cast("pk", CharField())
+ )
+ charged = (
+ BillingTelemetry.objects.filter(
+ Q(cause_kind="deployed_model", cause_id=Cast(OuterRef("pk"), CharField()))
+ | Q(cause_kind="dedicated_deployment", cause_id__in=Subquery(dedicated)),
+ **window,
+ )
+ .order_by()
+ .annotate(model=Value(1))
+ .values("model")
+ .annotate(total=-Sum("amount"))
+ .values("total")
+ )
+ return Subquery(charged)
+
+
@extend_schema_view(
list=extend_schema(summary="List deployed models for the current project"),
retrieve=extend_schema(summary="Get a deployed model by ID"),
@@ -2048,11 +2072,8 @@ class DeployedModelViewSet(
"inference_calls__latency_ms",
filter=Q(inference_calls__is_cold=False, inference_calls__outcome="succeeded"),
),
- cost_total=Sum("inference_calls__cost"),
- cost_this_month=Sum(
- "inference_calls__cost",
- filter=Q(inference_calls__created_at__gte=month_start),
- ),
+ cost_total=_serving_cost(),
+ cost_this_month=_serving_cost(timestamp__gte=month_start),
)
.order_by("-created_at")
)
@@ -2079,7 +2100,7 @@ class DeployedModelViewSet(
{"detail": "No associated finetuning job."},
status=status.HTTP_400_BAD_REQUEST,
)
- require_credits(request.user)
+ require_credits(instance.project_id)
try:
if instance.status in ("failed", "deleted"):
retry_deployment(instance.pk)
@@ -2129,7 +2150,7 @@ class DeployedModelViewSet(
{"detail": "Training job has no usable checkpoint — retry the training job first."},
status=status.HTTP_400_BAD_REQUEST,
)
- require_credits(request.user)
+ require_credits(instance.project_id)
try:
retry_deployment(instance.pk)
except InputValidationError as exc:
diff --git a/overbae/core/decisions.py b/overbae/core/decisions.py
index 4756f34d..29a44636 100644
--- a/overbae/core/decisions.py
+++ b/overbae/core/decisions.py
@@ -18,6 +18,7 @@ from django.core.cache import cache
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
from overbae.core.model_registry import PROVIDERS, decision_model, decision_models
+from overbae.services import model_meter
logger = logging.getLogger(__name__)
@@ -210,12 +211,26 @@ def response_usage(payload: dict, elapsed: float) -> dict[str, Any]:
def post_request(body, *, remaining):
provider = PROVIDERS["openrouter"]
- return httpx.post(
+ response = httpx.post(
f"{provider.base_url}/systemone",
headers={"Authorization": f"Bearer {provider.key()}", **provider.headers},
json=body,
timeout=httpx.Timeout(min(remaining, _TIMEOUT), connect=min(remaining, 5)),
)
+ if response.is_success:
+ # Every answered attempt is billed, retried or not.
+ with suppress(ValueError):
+ payload = response.json()
+ if isinstance(payload, dict):
+ usage = response_usage(payload, 0)
+ model_meter.settle(
+ usage["request_id"],
+ usage["response_cost"],
+ model=usage["served_model"] or str(body.get("model", "")),
+ prompt_tokens=usage["prompt_tokens"],
+ completion_tokens=usage["completion_tokens"],
+ )
+ return response
def request_once(body):
diff --git a/overbae/core/llms.py b/overbae/core/llms.py
index 9b5fd063..9977f689 100644
--- a/overbae/core/llms.py
+++ b/overbae/core/llms.py
@@ -8,6 +8,7 @@ from collections.abc import Callable
from contextlib import suppress
from dataclasses import dataclass, field
from functools import lru_cache
+from types import SimpleNamespace
from typing import Any
from urllib.parse import parse_qsl, urlsplit, urlunsplit
@@ -26,10 +27,12 @@ from tenacity import (
wait_exponential_jitter,
)
+from modal_shared import container_meter
from modal_shared.context_budget import INCOMPLETE_FINISH_REASONS
from modal_shared.modelfam import serve_image_key
from modal_shared.shared import routing_headers as _modal_routing_headers
from overbae.core.model_registry import (
+ OPENROUTER_BASE_URL,
PROVIDERS,
Provider,
TaskType,
@@ -40,6 +43,7 @@ from overbae.core.model_registry import (
resolve_model,
)
from overbae.models import DeployedModel
+from overbae.services import model_meter
logger = logging.getLogger(__name__)
@@ -184,11 +188,13 @@ def _model_spec_client_and_name(spec: ModelSpec) -> tuple[AsyncOpenAI, str, str]
if not api_key:
raise RuntimeError(f"{spec.api_key_env} is required for custom model '{spec.model_id}'")
base, query_items = _split_base_url(spec.base_url)
- header_items = (
- _inference_routing_header_items(spec.model_id)
- if spec.api_key_env == "INFERENCE_API_KEY"
- else ()
- )
+ header_items = ()
+ if spec.api_key_env == "INFERENCE_API_KEY":
+ header_items = _inference_routing_header_items(spec.model_id)
+ # The serving container charges this call's seconds to the caller's cause.
+ found = model_meter.current()
+ if found is not None:
+ header_items = (*header_items, (container_meter.REF_HEADER, found.ref))
return (
_openai_compatible_client(base, api_key, query_items, header_items),
spec.model_id,
@@ -269,12 +275,29 @@ class CompletionDeadlineExceededError(TimeoutError):
"""The total completion budget expired, even if the server kept sending bytes."""
+def _is_openrouter(client: AsyncOpenAI | OpenAI) -> bool:
+ return urlsplit(str(client.base_url)).hostname == urlsplit(OPENROUTER_BASE_URL).hostname
+
+
+def _settle(response: Any, fallback_model: str) -> None:
+ """Charge an answered OpenRouter request to the caller's billing cause."""
+ usage = getattr(response, "usage", None)
+ model_meter.settle(
+ getattr(response, "id", None),
+ _usage_value(usage, "cost", None),
+ model=getattr(response, "model", None) or fallback_model,
+ prompt_tokens=_usage_value(usage, "prompt_tokens", None),
+ completion_tokens=_usage_value(usage, "completion_tokens", None),
+ )
+
+
async def _create_completion(
client: AsyncOpenAI,
completion_kwargs: dict,
request_kwargs: dict,
retry_deadline: float = RETRY_DEADLINE_BACKGROUND,
max_attempts: int | None = None,
+ answered: list | None = None,
):
async def _once():
started = time.monotonic()
@@ -284,6 +307,8 @@ async def _create_completion(
if isinstance(exc.__cause__, SoftTimeLimitExceeded):
raise exc.__cause__ from None
raise
+ if answered is not None:
+ answered.append(response)
response_ms = (time.monotonic() - started) * 1000
with suppress(AttributeError, TypeError):
object.__setattr__(response, "_response_ms", response_ms)
@@ -311,19 +336,32 @@ def _do_openai_completion(
# Each chat owns its client and loop. Cached asynchronous clients cannot be
# reused across worker threads or across the loops of successive calls.
budget = retry_deadline if retry_deadline > 0 else _REQUEST_TIMEOUT
+ # Every answer the provider sent is billed, also one a later step rejects. A request
+ # that timed out after it was sent has no generation id to charge: that cost is ours.
+ answered: list = []
async def complete():
try:
async with client, asyncio.timeout(budget):
return await _create_completion(
- client, completion_kwargs, request_kwargs, retry_deadline, max_attempts
+ client,
+ completion_kwargs,
+ request_kwargs,
+ retry_deadline,
+ max_attempts,
+ answered,
)
except TimeoutError as exc:
raise CompletionDeadlineExceededError(
f"Completion deadline exceeded after {budget:g}s"
) from exc
- return asyncio.run(complete())
+ try:
+ return asyncio.run(complete())
+ finally:
+ if _is_openrouter(client):
+ for response in answered:
+ _settle(response, str(completion_kwargs.get("model", "")))
class EmbeddingUnavailableError(RuntimeError):
@@ -564,6 +602,7 @@ def call_llm(
preferences = _provider_preferences(completion_kwargs)
if preferences:
extra_body["provider"] = preferences
+ if _is_openrouter(client):
completion_kwargs["extra_body"] = extra_body
response = _do_openai_completion(
@@ -735,12 +774,11 @@ def stream_llm_tools(
model: str | None = None,
fallback_models: list[str] | None = None,
on_progress: Callable[[str, list[dict]], None] | None = None,
- on_generation: Callable[[str], None] | None = None,
) -> tuple[str, list[dict[str, Any]], dict]:
""":func:`call_llm_tools`, streamed. ``on_progress`` receives the text so far and the
tool calls as far as they are written; an exception it raises ends the stream and
- propagates. ``on_generation`` receives the provider's generation id once the stream
- starts: the provider bills a stream that started, also one cut off later.
+ propagates. The provider bills a stream that started, also one cut off later: it is
+ charged once its generation is priced.
Never retried: a stream that started may already be billed.
"""
@@ -765,8 +803,6 @@ def stream_llm_tools(
usage, served = chunk.usage or usage, chunk.model or served
if generation is None and chunk.id:
generation = chunk.id
- if on_generation is not None:
- on_generation(generation)
for choice in chunk.choices:
finish = choice.finish_reason or finish
text += choice.delta.content or ""
@@ -808,6 +844,9 @@ def stream_llm_tools(
timer.cancel()
except openai.OpenAIError as exc:
raise RuntimeError(f"Error calling LLM: {exc}") from exc
+ finally:
+ if generation is not None:
+ _settle(SimpleNamespace(id=generation, usage=usage, model=served), selected)
text, tool_calls = text.strip(), [calls[index] for index in sorted(calls)]
stats = _tool_call_stats(
usage, served, selected, (time.monotonic() - started) * 1000, generation
diff --git a/overbae/innermind/context.py b/overbae/innermind/context.py
index a4794700..593b63fb 100644
--- a/overbae/innermind/context.py
+++ b/overbae/innermind/context.py
@@ -45,7 +45,8 @@ def token_cost(entry: dict, input_tokens: int, output_tokens: int) -> float | No
not isinstance(rate, (int, float)) or not math.isfinite(rate) or rate < 0 for rate in rates
):
return None
- return round((input_tokens * rates[0] + output_tokens * rates[1]) / 1_000_000, 6)
+ # Credits, 100 to the dollar, at the provider's published token rates.
+ return round((input_tokens * rates[0] + output_tokens * rates[1]) / 10_000, 4)
def judge_model_options(checks: list[dict]) -> list[dict]:
@@ -54,7 +55,7 @@ def judge_model_options(checks: list[dict]) -> list[dict]:
return []
catalog, available = fetch_model_catalog()
entries = {entry["id"]: entry for entry in catalog}
- current_costs = [check.get("estimated_cost_usd") for check in judges]
+ current_costs = [check.get("estimated_credits") for check in judges]
current_cost = sum(current_costs) if all(cost is not None for cost in current_costs) else None
options = []
for name in judge_picker_models():
@@ -95,8 +96,8 @@ def judge_model_options(checks: list[dict]) -> list[dict]:
"context_window": context,
"max_output_tokens": limit,
"reserved_output_tokens": output,
- "estimated_cost_usd": cost,
- "cost_delta_usd": round(cost - current_cost, 6)
+ "estimated_credits": cost,
+ "credits_delta": round(cost - current_cost, 6)
if cost is not None and current_cost is not None
else None,
}
@@ -113,9 +114,9 @@ def suggest_models(
variant_models: list[str] | None = None,
) -> dict:
result = {
- "estimated_cost_usd": None,
+ "estimated_credits": None,
"cost_basis": (
- "USD at published token rates, using all checked rows and the full reserved output "
+ "An estimate in credits (100 = $1) at published token rates, using all checked rows and the full reserved output "
"for one dataset pass per model or judge. Excludes retries, extra tool turns, "
"caching, hosting and training. Actual usage and provider rates may differ."
),
@@ -125,7 +126,7 @@ def suggest_models(
catalog, available = fetch_model_catalog()
entries = {entry["id"]: entry for entry in catalog}
current = entries.get(pricing_slug(check["model"]), {}) if not custom else {}
- result["estimated_cost_usd"] = budget_cost(current, inputs, check["reserved_output_tokens"])
+ result["estimated_credits"] = budget_cost(current, inputs, check["reserved_output_tokens"])
if check["status"] == "fits":
return result
if not inputs or not available or not openrouter_configured():
@@ -164,7 +165,7 @@ def suggest_models(
):
continue
cost = budget_cost(entry, inputs, output)
- current_cost = result["estimated_cost_usd"]
+ current_cost = result["estimated_credits"]
result["suggestions"].append(
{
"model": name,
@@ -172,8 +173,8 @@ def suggest_models(
"context_window": context,
"max_output_tokens": output_limit,
"reserved_output_tokens": output,
- "estimated_cost_usd": cost,
- "cost_delta_usd": round(cost - current_cost, 6)
+ "estimated_credits": cost,
+ "credits_delta": round(cost - current_cost, 6)
if cost is not None and current_cost is not None
else None,
}
diff --git a/overbae/innermind/dataset.py b/overbae/innermind/dataset.py
index b7616e9c..73342b9c 100644
--- a/overbae/innermind/dataset.py
+++ b/overbae/innermind/dataset.py
@@ -14,6 +14,7 @@ from overbae.core.decisions import DecisionError
from overbae.innermind import generation
from overbae.innermind.span_processor import SpanProcessor
from overbae.models import EvalMatrix, EvalRun, EvalRunRow, EvalScore, Span
+from overbae.services import model_meter
from overbae.services.datasets import rows as row_store
MAX_CONCURRENT_ROWS = 64
@@ -144,5 +145,6 @@ async def score_rows(run: EvalRun, task_id: str) -> int:
await sync_to_async(_save)(saved, run_row, task_id)
return saved
- results = await asyncio.gather(*(score(row, run_row) for row, run_row in pairs))
+ with model_meter.billed(await sync_to_async(generation.run_cause)(run)):
+ results = await asyncio.gather(*(score(row, run_row) for row, run_row in pairs))
return sum(score is not None for score in results)
diff --git a/overbae/innermind/generation.py b/overbae/innermind/generation.py
index 1bfc05f4..56ed8350 100644
--- a/overbae/innermind/generation.py
+++ b/overbae/innermind/generation.py
@@ -18,7 +18,8 @@ from django.utils import timezone
from overbae.core.llms import ModelSpec, call_llm
from overbae.innermind import replay
-from overbae.models import EvalGenerationScheduler, EvalRun, EvalRunRow, Span
+from overbae.models import BillingService, EvalGenerationScheduler, EvalRun, EvalRunRow, Span
+from overbae.services import billing_ledger, model_meter
from overbae.services.datasets import heartbeat
from overbae.services.datasets import rows as row_store
from overbae.services.datasets.examples import matches_reference
@@ -220,6 +221,16 @@ def model_of(run: EvalRun) -> tuple[str | None, ModelSpec | None]:
)
+def run_cause(run: EvalRun) -> billing_ledger.Cause:
+ return billing_ledger.cause(
+ run.project_id,
+ BillingService.EVALUATION,
+ "eval_run",
+ run.pk,
+ actor=run.triggered_by_id,
+ )
+
+
def warm(run: EvalRun) -> None:
"""A freshly deployed fine-tuned model cold-starts for minutes on its first request;
paying that on the untimed run task keeps it off every row's clock."""
@@ -227,7 +238,8 @@ def warm(run: EvalRun) -> None:
if spec is None:
return
try:
- call_llm("ping", model=model_name, model_spec=spec, max_tokens=1)
+ with model_meter.billed(run_cause(run)):
+ call_llm("ping", model=model_name, model_spec=spec, max_tokens=1)
except Exception as exc: # noqa: BLE001 — warmup is best-effort
logger.warning("model warmup failed for %s: %s", spec.model_id, exc)
@@ -479,20 +491,21 @@ def generate(run_row: EvalRunRow) -> None:
"project_id": str(run.project_id),
}
strategy = params.get("generation_strategy") or "replay"
- if strategy == "single_completion":
- result = replay.generate_decision(
- tool_provider=replay.ReplayToolProvider(tool_defs=seed.tool_defs), **common
- )
- else:
- result = replay.run_capability(
- tool_provider=seed.provider,
- max_steps=replay.resolve_max_steps(
- recorded_tool_calls=len(seed.provider.recorded_calls),
- override=params.get("max_steps"),
- ),
- check_active=lambda: ensure_run_active(run.pk),
- **common,
- )
+ with model_meter.billed(run_cause(run)):
+ if strategy == "single_completion":
+ result = replay.generate_decision(
+ tool_provider=replay.ReplayToolProvider(tool_defs=seed.tool_defs), **common
+ )
+ else:
+ result = replay.run_capability(
+ tool_provider=seed.provider,
+ max_steps=replay.resolve_max_steps(
+ recorded_tool_calls=len(seed.provider.recorded_calls),
+ override=params.get("max_steps"),
+ ),
+ check_active=lambda: ensure_run_active(run.pk),
+ **common,
+ )
if result.error and not result.output_messages:
raise RuntimeError(f"generation failed: {result.error}")
diff --git a/overbae/innermind/signals.py b/overbae/innermind/signals.py
index 5772602a..e1f197a2 100644
--- a/overbae/innermind/signals.py
+++ b/overbae/innermind/signals.py
@@ -12,6 +12,7 @@ from datetime import UTC, datetime, timedelta
from statistics import mean, median
from typing import ClassVar
+from asgiref.sync import sync_to_async
from django.db.models import Func, IntegerField, Sum, TextField, Window
from django.db.models.functions import Cast, Coalesce
from django.utils import timezone
@@ -29,7 +30,8 @@ from overbae.innermind.metrics import (
scores_of,
)
from overbae.innermind.span_processor import MAX_ATTEMPTS
-from overbae.models import SignalEvent, SignalSubscription, Span
+from overbae.models import BillingService, SignalEvent, SignalSubscription, Span
+from overbae.services import billing_ledger, model_meter
logger = logging.getLogger(__name__)
@@ -712,6 +714,16 @@ class SignalRunner:
)
async def run(self) -> int:
+ """A project out of credits waits: its signals run again after a top-up."""
+ if not await sync_to_async(billing_ledger.can_spend)(self.project_id):
+ return 0
+ found = await sync_to_async(billing_ledger.cause)(
+ self.project_id, BillingService.SCORING, "signals", self.project_id
+ )
+ with model_meter.billed(found):
+ return await self._run()
+
+ async def _run(self) -> int:
configured = [
s async for s in SignalSubscription.objects.filter(project_id=self.project_id)
]
diff --git a/overbae/innermind/span_processor.py b/overbae/innermind/span_processor.py
index a93017bf..b1202846 100644
--- a/overbae/innermind/span_processor.py
+++ b/overbae/innermind/span_processor.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import logging
from collections import defaultdict
+from dataclasses import replace
from datetime import timedelta
from asgiref.sync import sync_to_async
@@ -13,7 +14,8 @@ from django.utils import timezone
from overbae.innermind import evidence
from overbae.innermind.evals import evaluator_factory, expectation_rows, matches
from overbae.innermind.metrics import Metric, answers_for_capability, mean_of
-from overbae.models import EvalMatrix, EvalScore, Span
+from overbae.models import BillingService, EvalMatrix, EvalScore, Span
+from overbae.services import billing_ledger, model_meter
logger = logging.getLogger(__name__)
@@ -289,7 +291,10 @@ def persist(span: Span) -> bool:
async def score_project_spans(project_id, spans: list[Span]) -> list[Span]:
"""Scores and stores each span as it finishes; returns the spans that gained a final
- score."""
+ score. A project out of credits waits: its spans stay unscored until a top-up."""
+ if not await sync_to_async(billing_ledger.can_spend)(project_id):
+ return []
+ base = await sync_to_async(billing_ledger.cause)(project_id, BillingService.SCORING, "span", "")
matrix = await enabled_matrix(project_id)
traces = await load_traces(
project_id,
@@ -314,14 +319,15 @@ async def score_project_spans(project_id, spans: list[Span]) -> list[Span]:
if not await record_attempt(span):
return None
try:
- await processor.evaluate(
- span,
- matrix,
- trace,
- fallback_intent=fallback,
- judge=not spent,
- last_attempt=attempts >= MAX_ATTEMPTS,
- )
+ with model_meter.billed(replace(base, id=span.span_id)):
+ await processor.evaluate(
+ span,
+ matrix,
+ trace,
+ fallback_intent=fallback,
+ judge=not spent,
+ last_attempt=attempts >= MAX_ATTEMPTS,
+ )
except Exception as exc: # noqa: BLE001 — still no "score", so the sweep retries it
logger.warning("Scoring span %s failed: %s", span.span_id, exc)
span.eval_attributes = {
diff --git a/overbae/innermind/trajectory.py b/overbae/innermind/trajectory.py
index 708655d1..33b1b18f 100644
--- a/overbae/innermind/trajectory.py
+++ b/overbae/innermind/trajectory.py
@@ -7,6 +7,7 @@ from collections import Counter
from dataclasses import asdict, replace
from datetime import timedelta
+from asgiref.sync import sync_to_async
from django.utils import timezone
from overbae.innermind import evidence
@@ -23,7 +24,8 @@ from overbae.innermind.metrics import (
score_of,
)
from overbae.innermind.span_processor import MAX_ATTEMPTS
-from overbae.models import EvalScore, Span
+from overbae.models import BillingService, EvalScore, Span
+from overbae.services import billing_ledger, model_meter
logger = logging.getLogger(__name__)
@@ -307,10 +309,17 @@ async def score_trace(project_id, trace_id: str) -> bool:
async def score_traces(project_id, trace_ids: list[str]) -> int:
+ """A project out of credits waits: its trajectories stay unscored until a top-up."""
+ if not await sync_to_async(billing_ledger.can_spend)(project_id):
+ return 0
+ base = await sync_to_async(billing_ledger.cause)(
+ project_id, BillingService.SCORING, "trace", ""
+ )
scored = 0
for trace_id in trace_ids:
try:
- scored += await score_trace(project_id, trace_id)
+ with model_meter.billed(replace(base, id=trace_id)):
+ scored += await score_trace(project_id, trace_id)
except Exception as exc: # noqa: BLE001 — the sweep retries an unscored trajectory
logger.warning("Scoring trajectory %s failed: %s", trace_id, exc)
return scored
diff --git a/overbae/migrations/0078_ledger_cause.py b/overbae/migrations/0078_ledger_cause.py
new file mode 100644
index 00000000..36632e14
--- /dev/null
+++ b/overbae/migrations/0078_ledger_cause.py
@@ -0,0 +1,194 @@
+# Generated by Django 6.0.8 on 2026-12-02 13:36
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+# Existing usage rows keep their payer and amount; what their keys and metadata already
+# name becomes their cause, resource and quantity. Nothing unrecorded is filled in.
+_KEYED = {
+ "dedicated": "dedicated_deployment",
+ "modal-sandbox": "workspace_sandbox",
+ "inference-ft": "inference_call",
+ "decision-evaluation": "decision_provider_request",
+ "decision-performance": "decision_performance_request",
+ "assistant": "assistant_thread",
+}
+_FIELDS = [
+ "actor",
+ "cause_kind",
+ "cause_id",
+ "provider_ref",
+ "resource",
+ "quantity",
+ "unit",
+ "unit_usd",
+]
+
+
+def describe(row):
+ key = row.idempotency_key or ""
+ prefix, _, rest = key.partition(":")
+ ident = rest.split(":", 1)[0]
+ metadata = row.metadata or {}
+ # The owner paid for these; who started the work was not recorded.
+ row.actor_id = None if row.service in ("assistant", "workspace") else row.user_id
+ if row.service == "finetuning-job" and metadata.get("job_id"):
+ row.cause_kind, row.cause_id = "finetune_job", str(metadata["job_id"])
+ elif prefix in _KEYED and ident:
+ row.cause_kind, row.cause_id = _KEYED[prefix], ident[:64]
+ if prefix == "modal-sandbox":
+ row.provider_ref, row.resource = ident, "modal sandbox"
+ elif prefix == "openrouter":
+ row.provider_ref = rest
+ usage = metadata.get("llm_usage") or metadata.get("usage") or {}
+ model = metadata.get("model_id") or (
+ usage.get("served_model") if isinstance(usage, dict) else ""
+ )
+ if model and row.service in ("assistant", "inference", "evaluation"):
+ row.resource = f"openrouter {model}"[:128]
+ row.quantity, row.unit, row.unit_usd = 1, "call", -row.amount
+ if prefix == "dedicated" and metadata.get("minutes"):
+ row.resource = f"modal {metadata.get('gpu_type', '')} x{metadata.get('replicas', 1)}"[:128]
+ row.quantity, row.unit = metadata["minutes"], "minute"
+ row.unit_usd = -row.amount / row.quantity
+
+
+def label_usage(apps, schema_editor):
+ ledger = apps.get_model("overbae", "BillingTelemetry")
+ batch = []
+ for row in ledger.objects.filter(amount__lt=0).iterator(chunk_size=1000):
+ describe(row)
+ batch.append(row)
+ if len(batch) == 1000:
+ ledger.objects.bulk_update(batch, _FIELDS)
+ batch = []
+ ledger.objects.bulk_update(batch, _FIELDS)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("overbae", "0077_deployed_model_cancelled"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="billingtelemetry",
+ name="actor",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ migrations.AddField(
+ model_name="billingtelemetry",
+ name="cause_id",
+ field=models.CharField(blank=True, default="", max_length=64),
+ ),
+ migrations.AddField(
+ model_name="billingtelemetry",
+ name="cause_kind",
+ field=models.CharField(blank=True, default="", max_length=32),
+ ),
+ migrations.AddField(
+ model_name="billingtelemetry",
+ name="ended_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="billingtelemetry",
+ name="experiment",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="overbae.experiment",
+ ),
+ ),
+ migrations.AddField(
+ model_name="billingtelemetry",
+ name="provider_ref",
+ field=models.CharField(blank=True, default="", max_length=255),
+ ),
+ migrations.AddField(
+ model_name="billingtelemetry",
+ name="quantity",
+ field=models.DecimalField(blank=True, decimal_places=6, max_digits=20, null=True),
+ ),
+ migrations.AddField(
+ model_name="billingtelemetry",
+ name="resource",
+ field=models.CharField(blank=True, default="", max_length=128),
+ ),
+ migrations.AddField(
+ model_name="billingtelemetry",
+ name="run",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="overbae.experimentrun",
+ ),
+ ),
+ migrations.AddField(
+ model_name="billingtelemetry",
+ name="started_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="billingtelemetry",
+ name="unit",
+ field=models.CharField(blank=True, default="", max_length=16),
+ ),
+ migrations.AddField(
+ model_name="billingtelemetry",
+ name="unit_usd",
+ field=models.DecimalField(blank=True, decimal_places=12, max_digits=20, null=True),
+ ),
+ migrations.AlterField(
+ model_name="billingtelemetry",
+ name="project",
+ field=models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.DO_NOTHING,
+ related_name="billing_telemetry",
+ to="overbae.project",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="billingtelemetry",
+ name="service",
+ field=models.CharField(
+ choices=[
+ ("grant", "Grant"),
+ ("purchase", "Purchase"),
+ ("finetuning-job", "Training"),
+ ("inference", "Inference"),
+ ("inference-ft-model", "Fine-tuned inference"),
+ ("dedicated-inference", "Dedicated inference"),
+ ("data-workshop", "Data workshop"),
+ ("evaluation", "Evaluation"),
+ ("scoring", "Scoring"),
+ ("assistant", "Assistant"),
+ ("workspace", "Assistant workspace"),
+ ],
+ max_length=32,
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="billingtelemetry",
+ index=models.Index(fields=["project", "timestamp"], name="billing_tel_project_ts_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="billingtelemetry",
+ index=models.Index(fields=["cause_kind", "cause_id"], name="billing_tel_cause_idx"),
+ ),
+ migrations.RunPython(label_usage, migrations.RunPython.noop),
+ ]
diff --git a/overbae/migrations/0079_metered_container.py b/overbae/migrations/0079_metered_container.py
new file mode 100644
index 00000000..760264f5
--- /dev/null
+++ b/overbae/migrations/0079_metered_container.py
@@ -0,0 +1,25 @@
+# Generated by Django 6.0.8 on 2026-12-02 13:54
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('overbae', '0078_ledger_cause'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='MeteredContainer',
+ fields=[
+ ('container_id', models.CharField(max_length=64, primary_key=True, serialize=False)),
+ ('function', models.CharField(blank=True, default='', max_length=128)),
+ ('started_at', models.DateTimeField()),
+ ('charged_until', models.DateTimeField()),
+ ('charged', models.JSONField(default=dict)),
+ ('last_ref', models.CharField(blank=True, default='', max_length=255)),
+ ('finished', models.BooleanField(db_index=True, default=False)),
+ ],
+ ),
+ ]
diff --git a/overbae/migrations/0080_trigger_cap_credits.py b/overbae/migrations/0080_trigger_cap_credits.py
new file mode 100644
index 00000000..0e6dc42f
--- /dev/null
+++ b/overbae/migrations/0080_trigger_cap_credits.py
@@ -0,0 +1,36 @@
+from django.db import migrations, models
+from django.db.models import F
+
+
+def to_credits(apps, schema_editor):
+ trigger = apps.get_model("overbae", "ExperimentTrigger")
+ trigger.objects.exclude(max_spend_credits=None).update(
+ max_spend_credits=F("max_spend_credits") * 100
+ )
+
+
+def to_usd(apps, schema_editor):
+ trigger = apps.get_model("overbae", "ExperimentTrigger")
+ trigger.objects.exclude(max_spend_credits=None).update(
+ max_spend_credits=F("max_spend_credits") / 100
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("overbae", "0079_metered_container"),
+ ]
+
+ operations = [
+ migrations.RenameField(
+ model_name="experimenttrigger",
+ old_name="max_spend_usd",
+ new_name="max_spend_credits",
+ ),
+ migrations.AlterField(
+ model_name="experimenttrigger",
+ name="max_spend_credits",
+ field=models.DecimalField(blank=True, decimal_places=2, max_digits=12, null=True),
+ ),
+ migrations.RunPython(to_credits, to_usd),
+ ]
diff --git a/overbae/modal/modal_decision_evaluation.py b/overbae/modal/modal_decision_evaluation.py
index cdf75029..7a3443c8 100644
--- a/overbae/modal/modal_decision_evaluation.py
+++ b/overbae/modal/modal_decision_evaluation.py
@@ -11,6 +11,7 @@ from pathlib import Path
import modal
+from modal_shared import container_meter
from modal_shared.compute_usage import ComputeMeter
from modal_shared.decision_artifact import read_artifact
from modal_shared.images.train import TRAIN_IMAGES
@@ -54,6 +55,9 @@ def paths(evaluation_id, model_run):
timeout=23 * 3600,
volumes={"/data": volume, "/weights": weights},
)
+@container_meter.metered(
+ lambda evaluation_id, **_: f"native_evaluation:{evaluation_id[:36]}", cpu=8, memory_gib=8
+)
def prepare(evaluation_id, model_run, input_sha256, *, foundation=None, inference=None):
meter = ComputeMeter(cpu=8, memory_gib=8)
volume.reload()
@@ -204,6 +208,7 @@ def publish_progress(directory, label, work, report, cursor):
timeout=24 * 3600,
volumes={"/data": volume, "/weights": weights},
)
+@container_meter.metered(lambda evaluation_id, **_: f"native_evaluation:{evaluation_id[:36]}")
def predict(evaluation_id, model_run, *, base_only=False, inference=None):
meter = ComputeMeter(gpu_type="H100", gpu_count=1)
volume.reload()
@@ -284,6 +289,9 @@ class DecisionPerformanceEndpoint:
@modal.enter()
def load(self):
+ container_meter.METER.configure(
+ "DecisionPerformanceEndpoint", ref=f"decision_performance:{self.measurement_id}"
+ )
self.meter = ComputeMeter(gpu_type="H100", gpu_count=1)
volume.reload()
weights.reload()
diff --git a/overbae/modal/modal_decision_serving.py b/overbae/modal/modal_decision_serving.py
index ded8483d..5eb83992 100644
--- a/overbae/modal/modal_decision_serving.py
+++ b/overbae/modal/modal_decision_serving.py
@@ -11,6 +11,7 @@ from pathlib import Path
import modal
+from modal_shared import container_meter
from modal_shared.decision_artifact import read_artifact
from modal_shared.decisions import decision_request
from modal_shared.images.serve import dedicated_sglang_kev_image, dedicated_vllm_image
@@ -110,6 +111,10 @@ def _decision_worker(cls_name, *, engine="vllm"):
@modal.enter()
def load(self):
+ # One container serves one artifact for its whole life.
+ container_meter.METER.configure(
+ cls_name, ref=f"decision_weights:{self.weights_path or self.base_repo}"
+ )
self.work = Path(tempfile.mkdtemp(prefix="decision-serving-"))
log_path = self.work / "worker.log"
self.log = log_path.open("w")
diff --git a/overbae/modal/modal_sft_worker.py b/overbae/modal/modal_sft_worker.py
index 23953a05..fde90408 100644
--- a/overbae/modal/modal_sft_worker.py
+++ b/overbae/modal/modal_sft_worker.py
@@ -36,6 +36,7 @@ from pathlib import Path
import modal
+from modal_shared import container_meter
from modal_shared.chat_checkpoint import read_checkpoint, seal_checkpoint
from modal_shared.compute_usage import ComputeMeter
from modal_shared.decision_artifact import read_artifact, seal_artifact
@@ -255,13 +256,22 @@ def _register_train(fn_name: str, image: modal.Image) -> None:
gpu_type: str = "H100",
gpu_count: int = 1,
) -> dict:
- return _run_training(run_id, env, gpu_type=gpu_type, gpu_count=gpu_count)
+ with container_meter.serving(env.get(container_meter.REF_ENV), function=fn_name):
+ return _run_training(run_id, env, gpu_type=gpu_type, gpu_count=gpu_count)
_sft.__name__ = fn_name
_sft.__qualname__ = fn_name
globals()[fn_name] = app.function(image=image, name=fn_name, **_TRAIN_FN_KWARGS)(_sft)
+ name = "prepare_" + fn_name
+
def prepare(preparation_id: str, request: dict) -> dict:
+ with container_meter.serving(
+ f"training_preparation:{preparation_id}", function=name, cpu=8, memory_gib=8
+ ):
+ return _prepare(preparation_id, request)
+
+ def _prepare(preparation_id: str, request: dict) -> dict:
meter = ComputeMeter(cpu=8, memory_gib=8)
sft_vol.reload()
destination = Path(DATA_MOUNT) / "preparations" / preparation_id
@@ -278,7 +288,6 @@ def _register_train(fn_name: str, image: modal.Image) -> None:
finally:
sft_vol.commit()
- name = "prepare_" + fn_name
prepare.__name__ = name
prepare.__qualname__ = name
globals()[name] = app.function(
diff --git a/overbae/modal/modal_vllm_worker.py b/overbae/modal/modal_vllm_worker.py
index 679a564e..07df6f53 100644
--- a/overbae/modal/modal_vllm_worker.py
+++ b/overbae/modal/modal_vllm_worker.py
@@ -14,6 +14,8 @@ Deploy:
import asyncio
import contextlib
+import functools
+import inspect
import json
import os
import shutil
@@ -27,6 +29,7 @@ from pathlib import Path
import modal
+from modal_shared import container_meter
from modal_shared.context_budget import (
CONTEXT_BUDGET_MESSAGE,
completion_body,
@@ -300,6 +303,44 @@ def _make_worker(
), cls_name
+def _billing_ref(worker, kwargs) -> str:
+ """The deployment a request serves: its adapter's served name on a shared base, else the
+ container's own model. A ref the API sends overrides it, as for an evaluation's calls."""
+ headers = {key.lower(): value for key, value in (kwargs.get("headers") or {}).items()}
+ adapter = kwargs.get("adapter")
+ served = adapter[0] if adapter else getattr(worker, "model_name", "")
+ return headers.get(container_meter.REF_HEADER) or f"served_model:{served}"
+
+
+def _meter(worker, kwargs):
+ return container_meter.serving(
+ _billing_ref(worker, kwargs),
+ function=type(worker).__name__,
+ cpu=getattr(worker, "meter_cpu", None),
+ memory_gib=getattr(worker, "meter_memory_gib", None),
+ )
+
+
+def _metered(method):
+ """Count a request's seconds toward the deployment it serves (modal_shared/container_meter)."""
+ if inspect.isasyncgenfunction(method):
+
+ @functools.wraps(method)
+ async def stream(self, **kwargs):
+ with _meter(self, kwargs):
+ async for item in method(self, **kwargs):
+ yield item
+
+ return stream
+
+ @functools.wraps(method)
+ async def call(self, **kwargs):
+ with _meter(self, kwargs):
+ return await method(self, **kwargs)
+
+ return call
+
+
class _BaseVLLMWorker:
"""Shared vLLM lifecycle for GPU workers.
@@ -629,6 +670,13 @@ class _BaseVLLMWorker:
# A parametrized web endpoint 303s and drops POST. A port forward does not.
self._tunnel_cm = modal.forward(VLLM_PORT)
self._tunnel = self._tunnel_cm.__enter__()
+ # Its whole life serves the one deployment it was started for.
+ container_meter.METER.configure(
+ type(self).__name__,
+ cpu=getattr(self, "meter_cpu", None),
+ memory_gib=getattr(self, "meter_memory_gib", None),
+ ref=f"served_model:{self.model_name}",
+ )
@modal.method()
def direct_url(self) -> str:
@@ -703,6 +751,7 @@ class _BaseVLLMWorker:
)
@modal.method()
+ @_metered
async def infer(
self,
*,
@@ -776,6 +825,7 @@ class _BaseVLLMWorker:
}
@modal.method()
+ @_metered
async def infer_stream(
self,
*,
@@ -1166,6 +1216,9 @@ def _register_worker(
"enable_lora": modal.parameter(default=runtime_lora or lora),
"max_lora_rank": modal.parameter(default=16),
"gpu_type": gpu_type,
+ # What Modal bills at least, read by the container meter.
+ "meter_cpu": cpu_count if lora or pin_resources else None,
+ "meter_memory_gib": memory_mib / 1024 if lora or pin_resources else None,
}
if runtime_lora:
parameters["__annotations__"]["base_identity"] = str
@@ -1272,6 +1325,8 @@ def _register_kev_dedicated(cls_name: str, gpu_type: str, target_app, owner) ->
self.engine = "sglang_kev"
self.direct_vllm = True
self.gpu_type = gpu_type
+ self.meter_cpu = 2
+ self.meter_memory_gib = {"L4": 32, "L40S": 64}.get(gpu_type, 64)
for name in (
"_startup_inner",
"_open_direct",
@@ -1352,7 +1407,7 @@ def _register_kev_dedicated(cls_name: str, gpu_type: str, target_app, owner) ->
"snapshot_engine": modal.parameter(default=False),
"gpu_type": gpu_type,
"startup": modal.enter()(startup),
- "infer": modal.method()(infer),
+ "infer": modal.method()(_metered(infer)),
"direct_url": modal.method()(direct_url),
"shutdown": modal.exit()(shutdown),
},
diff --git a/overbae/modal/register_model.py b/overbae/modal/register_model.py
index 9ae179a3..ce6c4af5 100644
--- a/overbae/modal/register_model.py
+++ b/overbae/modal/register_model.py
@@ -47,6 +47,7 @@ from pathlib import Path
import modal
+from modal_shared import container_meter
from modal_shared.kev_bases import BASES
from modal_shared.serving.artifacts import BASE_MANIFEST, seal_base
@@ -561,6 +562,7 @@ class RegisterAPIServer:
)
return fn.remote(
job_id=cache_key,
+ billing_ref=f"finetune_job:{job_id}" if job_id else f"served_model:{model_id}",
model_id=model_id,
is_lora=is_lora,
base_model_path=base_model_path,
@@ -614,6 +616,7 @@ class RegisterAPIServer:
print(f"[RegisterAPI] Dispatching base {model_id} to {tier} worker")
return fn.remote(
job_id=model_id,
+ billing_ref=f"served_model:{model_id}",
model_id=model_id,
is_lora=False,
base_model_path=None,
@@ -697,6 +700,7 @@ def _s3_checkpoint_exists(user_id: str, job_id: str) -> bool:
secrets=[inference_secret, aws_secret],
)
@modal.concurrent(max_inputs=1)
+@container_meter.metered(lambda job_id, **_: f"finetune_job:{job_id}")
def sync_modal_checkpoint_to_s3(
*, remote_id: str, user_id: str, job_id: str, job_result: dict | None = None
) -> dict:
@@ -800,6 +804,7 @@ def _ensure_draft(base_model: str) -> None:
max_containers=1, # global mutex: never let two callers write one base dir
)
@modal.concurrent(max_inputs=1)
+@container_meter.metered(lambda base_model, **_: f"base_model:{base_model}", cpu=8.0)
def fetch_base_model(*, base_model: str) -> dict:
"""The single choke point for base downloads: ``max_containers=1`` plus ``max_inputs=1`` make
it a global mutex, so concurrent callers cannot corrupt a shared
@@ -859,6 +864,7 @@ def fetch_base_model(*, base_model: str) -> dict:
secrets=[inference_secret],
)
@modal.concurrent(max_inputs=1)
+@container_meter.metered(lambda remote_id, **_: f"training_run:{remote_id.split(':', 1)[0]}")
def stage_modal_checkpoint(
*,
remote_id: str,
@@ -954,6 +960,11 @@ def _restore_adapter_from_s3(
secrets=[inference_secret],
)
@modal.concurrent(max_inputs=1)
+@container_meter.metered(
+ lambda remote_id, job_id="", **_: (
+ f"finetune_job:{job_id}" if job_id else f"training_run:{remote_id.split(':', 1)[0]}"
+ )
+)
def publish_adapter(
*, remote_id: str, cache_key: str, base_model: str, user_id: str = "", job_id: str = ""
) -> dict:
@@ -1025,6 +1036,7 @@ def publish_adapter(
secrets=[inference_secret, aws_secret],
)
@modal.concurrent(max_inputs=1)
+@container_meter.metered(lambda job_id, **_: f"finetune_job:{job_id}")
def download_checkpoint_from_s3(
*,
user_id: str,
@@ -1094,6 +1106,7 @@ def prune_spent_staging(*, max_age_s: float = _STAGING_ORPHAN_S) -> dict:
secrets=[inference_secret],
)
@modal.concurrent(max_inputs=1)
+@container_meter.metered(lambda model_id, **_: f"served_model:{model_id}")
def download_nebius_checkpoint(*, nebius_job_id: str, model_id: str) -> dict:
"""Download the final Nebius checkpoint into /weights/.staging/{job_id}/."""
from openai import OpenAI, PermissionDeniedError # noqa: PLC0415
@@ -1287,6 +1300,7 @@ _FP8_WORKER_KWARGS = {
@app.function(gpu="L40S", cpu=8.0, memory=65536, **_FP8_WORKER_KWARGS)
@modal.concurrent(max_inputs=1)
+@container_meter.metered(lambda billing_ref="", **_: billing_ref, cpu=8.0, memory_gib=64)
def prepare_fp8(
*,
job_id: str,
@@ -1296,6 +1310,7 @@ def prepare_fp8(
base_model: str = "",
quantize: bool = True,
source_dir: str = "",
+ billing_ref: str = "",
) -> dict:
"""Merge+FP8 for models up to ~34B."""
return _prepare_fp8_body(
@@ -1311,6 +1326,7 @@ def prepare_fp8(
@app.function(gpu="H200", cpu=16.0, memory=196608, **_FP8_WORKER_KWARGS)
@modal.concurrent(max_inputs=1)
+@container_meter.metered(lambda billing_ref="", **_: billing_ref, cpu=16.0, memory_gib=192)
def prepare_fp8_large(
*,
job_id: str,
@@ -1320,6 +1336,7 @@ def prepare_fp8_large(
base_model: str = "",
quantize: bool = True,
source_dir: str = "",
+ billing_ref: str = "",
) -> dict:
"""Merge+FP8 for >34B models — 141 GB VRAM keeps llmcompressor off the CPU."""
return _prepare_fp8_body(
diff --git a/overbae/models/__init__.py b/overbae/models/__init__.py
index 9339546a..8a353378 100644
--- a/overbae/models/__init__.py
+++ b/overbae/models/__init__.py
@@ -4,7 +4,7 @@ from .assistant import (
AssistantInput,
AssistantThread,
)
-from .billing import BillingService, BillingTelemetry, WorkspaceSandbox
+from .billing import BillingService, BillingTelemetry, MeteredContainer, WorkspaceSandbox
from .capabilities import Capability, IdentityAlias, Prompt
from .connectors import ConnectorCredential, ConnectorSyncConfig, ConnectorSyncRun
from .dataset_admission import DatasetLandingWork
@@ -126,6 +126,7 @@ __all__ = [
"IdentityAlias",
"BillingService",
"BillingTelemetry",
+ "MeteredContainer",
"WorkspaceSandbox",
"ConnectorCredential",
"ConnectorSyncConfig",
diff --git a/overbae/models/billing.py b/overbae/models/billing.py
index 4bc4e4f1..e0946914 100644
--- a/overbae/models/billing.py
+++ b/overbae/models/billing.py
@@ -9,19 +9,26 @@ from django.db import models
class BillingService(models.TextChoices):
GRANT = "grant", "Grant"
PURCHASE = "purchase", "Purchase"
- FINETUNING_JOB = "finetuning-job", "Finetuning job"
+ FINETUNING_JOB = "finetuning-job", "Training"
INFERENCE = "inference", "Inference"
INFERENCE_FT_MODEL = "inference-ft-model", "Fine-tuned inference"
DEDICATED_INFERENCE = "dedicated-inference", "Dedicated inference"
# Rows written before the assistant charged as its own service.
DATA_WORKSHOP = "data-workshop", "Data workshop"
EVALUATION = "evaluation", "Evaluation"
+ SCORING = "scoring", "Scoring"
ASSISTANT = "assistant", "Assistant"
WORKSPACE = "workspace", "Assistant workspace"
+# Money in; every other row is one measured provider cost of a project's work.
+CREDIT_SERVICES = (BillingService.GRANT, BillingService.PURCHASE)
+
+
class BillingTelemetry(models.Model):
- """Append-only credits ledger. Balance = SUM(amount) per user."""
+ """Credits ledger. Balance = SUM(amount) per user. A usage row is one provider cost at
+ the provider's price: ``quantity`` ``unit`` at ``unit_usd`` each. A container row grows
+ while the container runs; every other row is written once."""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(
@@ -29,9 +36,19 @@ class BillingTelemetry(models.Model):
on_delete=models.CASCADE,
related_name="billing_telemetry",
)
+ # Who started the work; the user above pays, the project's owner.
+ actor = models.ForeignKey(
+ settings.AUTH_USER_MODEL,
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ )
+ # No database constraint: a deleted project's charges keep naming it.
project = models.ForeignKey(
"overbae.Project",
- on_delete=models.SET_NULL,
+ on_delete=models.DO_NOTHING,
+ db_constraint=False,
null=True,
blank=True,
related_name="billing_telemetry",
@@ -39,6 +56,32 @@ class BillingTelemetry(models.Model):
amount = models.DecimalField(max_digits=12, decimal_places=7)
timestamp = models.DateTimeField(auto_now_add=True, db_index=True)
service = models.CharField(max_length=32, choices=BillingService.choices)
+ # What caused the cost, such as ``eval_run`` and its id.
+ cause_kind = models.CharField(max_length=32, blank=True, default="")
+ cause_id = models.CharField(max_length=64, blank=True, default="")
+ experiment = models.ForeignKey(
+ "overbae.Experiment",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ )
+ run = models.ForeignKey(
+ "overbae.ExperimentRun",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ )
+ # What the provider billed: a model, or a container's GPU, CPU and memory.
+ resource = models.CharField(max_length=128, blank=True, default="")
+ quantity = models.DecimalField(max_digits=20, decimal_places=6, null=True, blank=True)
+ unit = models.CharField(max_length=16, blank=True, default="")
+ unit_usd = models.DecimalField(max_digits=20, decimal_places=12, null=True, blank=True)
+ # The provider's own id for what it billed: a generation, a container.
+ provider_ref = models.CharField(max_length=255, blank=True, default="")
+ started_at = models.DateTimeField(null=True, blank=True)
+ ended_at = models.DateTimeField(null=True, blank=True)
idempotency_key = models.CharField(max_length=255, null=True, blank=True, unique=True)
metadata = models.JSONField(default=dict, blank=True)
@@ -46,6 +89,8 @@ class BillingTelemetry(models.Model):
ordering = ["-timestamp"]
indexes = [
models.Index(fields=["user", "timestamp"], name="billing_tel_user_ts_idx"),
+ models.Index(fields=["project", "timestamp"], name="billing_tel_project_ts_idx"),
+ models.Index(fields=["cause_kind", "cause_id"], name="billing_tel_cause_idx"),
]
def __str__(self) -> str:
@@ -73,3 +118,19 @@ class WorkspaceSandbox(models.Model):
started_at = models.DateTimeField(auto_now_add=True)
billed_until = models.DateTimeField()
finished = models.BooleanField(default=False, db_index=True)
+
+
+class MeteredContainer(models.Model):
+ """A Modal container's report, as far as it is charged: the totals it had reported then,
+ and the ref its idle time goes to (modal_shared/container_meter.py)."""
+
+ container_id = models.CharField(max_length=64, primary_key=True)
+ function = models.CharField(max_length=128, blank=True, default="")
+ started_at = models.DateTimeField()
+ # The report time up to which the container is charged.
+ charged_until = models.DateTimeField()
+ # Cumulative report values already charged: wall, GPU, CPU and memory seconds, and seconds
+ # per ref.
+ charged = models.JSONField(default=dict)
+ last_ref = models.CharField(max_length=255, blank=True, default="")
+ finished = models.BooleanField(default=False, db_index=True)
diff --git a/overbae/models/experiments.py b/overbae/models/experiments.py
index 0d533fcd..f72af7d9 100644
--- a/overbae/models/experiments.py
+++ b/overbae/models/experiments.py
@@ -191,9 +191,9 @@ class ExperimentTrigger(models.Model):
)
threshold = models.PositiveIntegerField(null=True, blank=True)
max_sends = models.PositiveSmallIntegerField()
- # Unattended work stops once the experiment's measured spend since the trigger was made
- # reaches this; unmeasured parts are not counted.
- max_spend_usd = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
+ # Unattended work stops once the credits the ledger charged to the experiment since the
+ # trigger was made reach this.
+ max_spend_credits = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)
sends = models.PositiveSmallIntegerField(default=0)
next_at = models.DateTimeField(null=True, blank=True)
last_sent_at = models.DateTimeField(null=True, blank=True)
diff --git a/overbae/services/assistant/turn.py b/overbae/services/assistant/turn.py
index 57a768a0..d05c93db 100644
--- a/overbae/services/assistant/turn.py
+++ b/overbae/services/assistant/turn.py
@@ -28,17 +28,12 @@ from overbae.models import (
AssistantEvent,
AssistantInput,
AssistantThread,
+ BillingService,
Project,
)
from overbae.models.assistant import STALE
-from overbae.services import workspaces
+from overbae.services import billing_ledger, model_meter, workspaces
from overbae.services.assistant import log, presentation, prompt, threads, tools
-from overbae.services.billing_ledger import (
- InsufficientCredits,
- charge_assistant_call,
- charge_generation_later,
- ensure_credits,
-)
from overbae.services.datasets import heartbeat
logger = logging.getLogger(__name__)
@@ -331,17 +326,19 @@ def _answer(thread, deadline: float) -> None:
if payer is None:
_status(thread, "failed", "The project has no owner to charge.")
return
- try:
- ensure_credits(payer)
- except InsufficientCredits:
- _status(thread, "failed", "Credits are needed to continue.")
+ if not billing_ledger.can_spend(thread.project_id):
+ _status(thread, "failed", "Paused: credits needed. Add credits to continue.")
return
if not warmed:
# Ready by the time the model asks for a cell.
workspaces.provider().warm(str(thread.project_id))
warmed = True
- _compact(thread, payer)
- reply = _model_call(thread, payer)
+ found = billing_ledger.cause(
+ thread.project_id, BillingService.ASSISTANT, "assistant_thread", thread.pk, actor=user
+ )
+ with model_meter.billed(found):
+ _compact(thread)
+ reply = _model_call(thread)
if reply is None or not reply.payload["calls"]:
return
asked = False
@@ -424,34 +421,11 @@ def _window(thread) -> list[AssistantEvent]:
return list(thread.events.filter(sequence__gt=covered or 0).defer("presentation"))
-def _charge(thread, payer, stats, sequence) -> None:
- generation = stats.get("provider_request_id")
- charge_assistant_call(
- payer,
- thread.project_id,
- stats,
- idempotency_key=f"openrouter:{generation}"
- if generation
- else f"assistant:{thread.pk}:{sequence}",
- )
+def _record(thread, kind, payload) -> AssistantEvent:
+ return log.append(thread, kind, payload, turn=thread.turn)
-def _record(thread, payer, kind, payload) -> AssistantEvent:
- """Save what a model call produced and charge it, both or neither. A reply that cannot
- be saved, as when a newer turn took the thread, is still charged: the provider billed it."""
- try:
- with transaction.atomic():
- event = log.append(thread, kind, payload, turn=thread.turn)
- _charge(thread, payer, payload["usage"], event.sequence)
- except BaseException:
- generation = payload["usage"].get("provider_request_id")
- if generation:
- charge_generation_later(payer, thread.project_id, generation)
- raise
- return event
-
-
-def _compact(thread, payer) -> None:
+def _compact(thread) -> None:
"""Summarize the older conversation once the last reply's prompt grew too large. The
cut falls before a user message or a reply, so no tool call loses its result."""
window = _window(thread)
@@ -484,9 +458,7 @@ def _compact(thread, payer) -> None:
except (RuntimeError, TimeoutError) as exc:
logger.warning("assistant summary failed for thread %s: %s", thread.pk, exc)
return
- _record(
- thread, payer, Kind.SUMMARY, {"text": text, "through": older[-1].sequence, "usage": stats}
- )
+ _record(thread, Kind.SUMMARY, {"text": text, "through": older[-1].sequence, "usage": stats})
def _continue(thread) -> None:
@@ -601,14 +573,9 @@ def messages(thread, events) -> list[dict]:
return out
-def _model_call(thread, payer) -> AssistantEvent | None:
+def _model_call(thread) -> AssistantEvent | None:
published = time.monotonic()
shown = None
- generation = None
-
- def started(value):
- nonlocal generation
- generation = value
def progress(text, calls):
nonlocal published, shown
@@ -629,31 +596,11 @@ def _model_call(thread, payer) -> AssistantEvent | None:
model=chain[0],
fallback_models=chain[1:],
on_progress=progress,
- on_generation=started,
)
- except IncompleteCompletionError as exc:
- # The provider charged for the reply it cut off.
- try:
- with transaction.atomic():
- event = log.append(
- thread,
- Kind.STATUS,
- {
- "state": "failed",
- "detail": "The model reached its output limit before it finished.",
- },
- turn=thread.turn,
- )
- _charge(thread, payer, exc.stats, event.sequence)
- except BaseException:
- if generation is not None:
- charge_generation_later(payer, thread.project_id, generation)
- raise
+ except IncompleteCompletionError:
+ _status(thread, "failed", "The model reached its output limit before it finished.")
return None
except BaseException as exc:
- # The provider bills a stream that started, also one cut off by a stop or a failure.
- if generation is not None:
- charge_generation_later(payer, thread.project_id, generation)
if not isinstance(exc, RuntimeError | TimeoutError):
raise
logger.warning("assistant model call failed for thread %s: %s", thread.pk, exc)
@@ -661,7 +608,6 @@ def _model_call(thread, payer) -> AssistantEvent | None:
return None
return _record(
thread,
- payer,
Kind.ASSISTANT,
{
"text": text,
diff --git a/overbae/services/billing_ledger.py b/overbae/services/billing_ledger.py
index 0e38edad..c9c63dd0 100644
--- a/overbae/services/billing_ledger.py
+++ b/overbae/services/billing_ledger.py
@@ -1,23 +1,31 @@
-"""Append-only credits ledger. Balance = SUM(BillingTelemetry.amount) per user."""
+"""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
-import httpx
-from django.conf import settings
from django.db import IntegrityError, transaction
-from django.db.models import Case, CharField, Count, Q, Sum, Value, When
-from django.db.models.fields.json import KeyTextTransform
+from django.db.models import Count, Q, Sum
from django.utils import timezone
-from overbae.core.model_registry import OPENROUTER_BASE_URL
-from overbae.models import BillingService, BillingTelemetry, FinetuningJob, User
-from overbae.services import model_catalog
+from overbae.models import (
+ AssistantThread,
+ BillingService,
+ BillingTelemetry,
+ ExperimentStep,
+ FinetuningJob,
+ Project,
+ User,
+)
from overbae.services.billing_provider import get_billing
logger = logging.getLogger(__name__)
@@ -53,8 +61,10 @@ def credit_report(
for row in rows
if row["used"]
]
+ balance = sum((row["balance"] for row in rows), Decimal("0"))
return {
- "balance_credits": sum((row["balance"] for row in rows), Decimal("0")) * CREDITS_PER_USD,
+ "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": {
@@ -64,15 +74,227 @@ def credit_report(
}
-class InsufficientCredits(Exception): # noqa: N818
- """Raised when the user has no credits left for paid work."""
+# 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) -> Decimal:
+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")
@@ -138,197 +360,76 @@ def grant_credit_purchase(user: User, amount: Decimal, session_id: str) -> Billi
def account_payload(user: User) -> dict[str, Any]:
+ enabled = get_billing().enabled
+ balance, spent = balance_usd(user), spent_usd(user)
return {
- "billing_enabled": get_billing().enabled,
- "credits_usd": balance_usd(user),
+ "billing_enabled": enabled,
+ "credits_usd": balance,
"credits_granted_usd": granted_usd(user),
- "credits_spent_usd": spent_usd(user),
+ "credits_spent_usd": spent,
+ "balance_credits": to_credits(balance),
+ "spent_credits": to_credits(spent),
+ "background_paused": enabled and balance <= 0,
}
-def charge_credits(
- 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:
- """Record usage as a negative ledger row."""
- if amount <= 0:
- return None
- return append_entry(
- user=user,
- amount=-amount,
- service=service,
- project_id=project_id,
- idempotency_key=idempotency_key,
- metadata=metadata,
- )
-
-
-def ensure_credits(user: User) -> None:
- get_billing().ensure_credits(user)
-
-
-def _attempt_cost(stats: dict[str, Any]) -> tuple[float, bool]:
- if stats.get("cached"):
- return 0.0, False
- cost = stats.get("response_cost")
- if cost is not None:
- return float(cost), False
- attempts = stats.get("attempts")
- if attempts:
- priced = [_attempt_cost(attempt) for attempt in attempts]
- return sum(value for value, _ in priced), any(unknown for _, unknown in priced)
- estimate = model_catalog.estimate_cost(
- str(stats.get("served_model") or ""),
- int(stats.get("prompt_tokens") or 0),
- int(stats.get("completion_tokens") or 0),
- cached_tokens=int(stats.get("cached_tokens") or 0),
- )
- return (estimate, False) if estimate is not None else (0.0, True)
-
-
-def charge_llm_usage(
- user: User,
- stats: dict[str, Any] | None,
- *,
- service: str,
- project_id: UUID | str | None = None,
- idempotency_key: str,
- metadata: dict[str, Any] | None = None,
-) -> BillingTelemetry | None:
- if user is None or not stats:
- return None
- if stats.get("cached"):
- return None
- cost, incomplete = _attempt_cost(stats)
- metadata = {**(metadata or {}), "cost_incomplete": incomplete}
- if not cost:
- return None
- try:
- return charge_credits(
- user,
- Decimal(str(cost)),
- service,
- project_id=project_id,
- idempotency_key=idempotency_key,
- metadata={"llm_usage": stats, **(metadata or {})},
- )
- except Exception:
- logger.exception(
- "Failed to charge llm usage key=%s user_id=%s",
- idempotency_key,
- getattr(user, "pk", None),
- )
- return None
-
-
-def charge_assistant_call(
- user: User, project_id: UUID | str, stats: dict[str, Any], *, idempotency_key: str
-) -> BillingTelemetry | None:
- """Charge one model call of the assistant at what the provider billed. A failure
- raises: the call's event and its charge are kept together or not at all. A call whose
- usage carried no cost is charged once the provider prices its generation."""
- cost = stats.get("response_cost")
- if cost is None:
- generation = stats.get("provider_request_id")
- if generation:
- charge_generation_later(user, project_id, generation)
- else:
- logger.warning("assistant call has no cost and no generation id: %s", idempotency_key)
- return None
- return charge_credits(
- user,
- Decimal(str(cost)),
- BillingService.ASSISTANT,
- project_id=project_id,
- idempotency_key=idempotency_key,
- metadata={"llm_usage": stats},
- )
-
-
-def charge_generation_later(user: User, project_id: UUID | str, generation: str) -> None:
- # Lazy: tasks import services.
- from overbae.tasks.assistant import charge_generation
-
- transaction.on_commit(
- lambda: charge_generation.delay(str(user.pk), str(project_id), generation)
- )
-
-
-def generation_cost(generation: str) -> Decimal | None:
- """What OpenRouter billed for a generation; None while it has not priced it yet."""
- response = httpx.get(
- f"{OPENROUTER_BASE_URL}/generation",
- params={"id": generation},
- headers={"Authorization": f"Bearer {settings.OPENROUTER_API_KEY}"},
- timeout=30,
- )
- if response.status_code == 404:
- return None
- response.raise_for_status()
- cost = response.json()["data"].get("total_cost")
- return None if cost is None else Decimal(str(cost))
-
-
def project_credit_report(
- user,
project,
*,
since=None,
before=None,
- training_job=None,
- training_experiment=None,
+ experiment=None,
+ run=None,
+ service=None,
+ cause_kind=None,
+ cause_id=None,
offset=0,
limit=20,
):
- """Account-owned posted charges; missing attribution stays in the null group."""
+ """The project's charges, grouped by what caused them."""
observed_at = timezone.now()
query = BillingTelemetry.objects.filter(
- user=user, project=project, amount__lt=0, timestamp__lte=observed_at
- )
- if since:
- query = query.filter(timestamp__gte=since)
- if before:
- query = query.filter(timestamp__lt=before)
- query = query.annotate(
- training_job_id=Case(
- When(
- service=BillingService.FINETUNING_JOB, then=KeyTextTransform("job_id", "metadata")
- ),
- default=Value(None),
- output_field=CharField(),
- )
+ project=project, amount__lt=0, timestamp__lte=observed_at
)
- if training_job:
- query = query.filter(training_job_id=str(training_job))
- if training_experiment:
- jobs = FinetuningJob.objects.filter(
- project=project, group_id=training_experiment
- ).values_list("id", flat=True)
- query = query.filter(training_job_id__in=[str(pk) for pk in jobs])
+ 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", "training_job_id")
+ 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", "training_job_id")
+ .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": list(grouped[offset : offset + limit]),
+ "groups": groups,
"total_groups": total,
"next_offset": offset + limit if offset + limit < total else None,
"limitations": [
- "Posted charges owned by this connection's account only; not all project members' spending.",
- "Unposted charges and provider estimates are excluded; no hard spending cap.",
- "Only recorded training job attribution is resolved. Other services and historical missing job metadata remain unattributed; experiment filtering includes only linked training charges, not a complete experiment bill.",
+ "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.",
],
}
diff --git a/overbae/services/billing_provider.py b/overbae/services/billing_provider.py
index 9d29bde9..1055e377 100644
--- a/overbae/services/billing_provider.py
+++ b/overbae/services/billing_provider.py
@@ -24,16 +24,12 @@ def commercial_billing_enabled() -> bool:
class Billing(Protocol):
enabled: bool
- def ensure_credits(self, user: User) -> None: ...
def grant_signup_credits(self, user: User) -> BillingTelemetry | None: ...
class UncappedBilling:
enabled = False
- def ensure_credits(self, user: User) -> None:
- return
-
def grant_signup_credits(self, user: User) -> BillingTelemetry | None:
return None
@@ -41,13 +37,6 @@ class UncappedBilling:
class StripeBilling:
enabled = True
- def ensure_credits(self, user: User) -> None:
- # Lazy import: billing_ledger imports this module.
- from overbae.services.billing_ledger import InsufficientCredits, balance_usd
-
- if balance_usd(user) <= 0:
- raise InsufficientCredits("Insufficient credits.")
-
def grant_signup_credits(self, user: User) -> BillingTelemetry | None:
# Lazy import: billing_ledger imports this module.
from overbae.models import BillingService
diff --git a/overbae/services/codebase/task_type.py b/overbae/services/codebase/task_type.py
index 589990ba..a0ef0ad7 100644
--- a/overbae/services/codebase/task_type.py
+++ b/overbae/services/codebase/task_type.py
@@ -12,6 +12,8 @@ from pydantic import BaseModel
from overbae.core.llms import RETRY_DEADLINE_INTERACTIVE, call_llm
from overbae.core.model_registry import TaskType as ModelTask
from overbae.core.model_registry import model_chain, resolve_model
+from overbae.models import BillingService
+from overbae.services import billing_ledger, model_meter
from overbae.services.benchmarks.taxonomy import TaskType
from overbae.services.codebase.flow import build_capability_flow
from overbae.services.judging import decisions
@@ -122,24 +124,29 @@ def classify_capability_task(capability) -> str:
)
metadata = {}
+ # Inside a cause, such as an assistant turn that asked, the call is that cause's.
+ found = model_meter.current() or billing_ledger.cause(
+ capability.project_id, BillingService.FINETUNING_JOB, "capability", capability.id
+ )
try:
- outcome = decisions.invoke(
- context,
- {
- "task_type": decisions.decision_question(
- _SYSTEM,
- {
- **dict(TaskType.choices),
- "unknown": "The primary objective is not established.",
- },
- )
- },
- convert=lambda answers: _Classification(task_type=answers["task_type"].choice),
- fallback=fallback,
- project_id=str(capability.project_id),
- workload="capability_task_classification",
- contract="capability_task@1",
- )
+ with model_meter.billed(found):
+ outcome = decisions.invoke(
+ context,
+ {
+ "task_type": decisions.decision_question(
+ _SYSTEM,
+ {
+ **dict(TaskType.choices),
+ "unknown": "The primary objective is not established.",
+ },
+ )
+ },
+ convert=lambda answers: _Classification(task_type=answers["task_type"].choice),
+ fallback=fallback,
+ project_id=str(capability.project_id),
+ workload="capability_task_classification",
+ contract="capability_task@1",
+ )
task_type = str(outcome.parsed.task_type)
metadata = outcome.stats.get("decision", {})
except Exception: # noqa: BLE001 — missing context or provider leaves models ungraded
diff --git a/overbae/services/compute_costs.py b/overbae/services/compute_costs.py
index d1fac6b1..5b035155 100644
--- a/overbae/services/compute_costs.py
+++ b/overbae/services/compute_costs.py
@@ -1,12 +1,6 @@
import math
-from decimal import Decimal
-from django.db import transaction
-from django.utils import timezone
-
-from overbae.models import BillingService, FinetuningJob
from overbae.services import provider_pricing
-from overbae.services.billing_ledger import charge_credits
def nonnegative(value):
@@ -85,104 +79,25 @@ def estimate_usage(usages, *, recorded_gpu=False):
}
-def gpu_charge(usages):
- unique, missing = unique_usage(usages)
- if missing:
- return None
- card = provider_pricing.current_rates()
- measurements = []
- for usage in unique.values():
- count = usage.get("gpu_count")
- if type(count) is not int or count < 0:
- return None
- if count == 0:
- continue
- rate = provider_pricing.gpu_rate(card, usage.get("gpu_type"))
- if not nonnegative(rate):
- return None
- measurements.append(
- {
- "usage_id": usage["usage_id"],
- "gpu_type": usage["gpu_type"],
- "gpu_count": count,
- "seconds": usage["elapsed_seconds"],
- "usd_per_second": rate,
- "usd": usage["elapsed_seconds"] * count * rate,
- }
- )
- if not measurements:
- return None
- return {
- "basis": "recorded_worker_gpu_seconds",
- "measurements": measurements,
- "cost_usd": round(sum(item["usd"] for item in measurements), 4),
- "rate_source": card["source"],
- "rates_fetched_at": card["fetched_at"],
- "exclusions": [
- "unreported_worker_time",
- "image_boot",
- "idle",
- "cpu",
- "memory",
- "storage",
- "network",
- ],
- }
-
-
-def record_training_charge(job):
- if job.provider != "modal" or job.cost_synced_at is not None:
- return
- receipt = gpu_charge((job.progress or {}).get("compute_usage", []))
- if receipt is None or receipt["cost_usd"] <= 0:
- return
- cost = Decimal(str(receipt["cost_usd"]))
- with transaction.atomic():
- current = (
- FinetuningJob.objects.select_related("triggered_by")
- .select_for_update(of=("self",))
- .get(pk=job.pk)
- )
- if current.cost_synced_at is not None:
- return
- if current.triggered_by_id:
- charge_credits(
- current.triggered_by,
- cost,
- BillingService.FINETUNING_JOB,
- project_id=current.project_id,
- idempotency_key=f"finetuning-job:{current.pk}",
- metadata={"job_id": str(current.pk), "provider": "modal", **receipt},
- )
- current.cost_usd, current.cost_synced_at = cost, timezone.now()
- current.result = {**(current.result or {}), "compute_charge": receipt}
- current.save(update_fields=["cost_usd", "cost_synced_at", "result", "updated_at"])
- job.refresh_from_db()
-
-
def training_cost(job):
+ """What the job's containers were charged, from the ledger, beside the forecast inputs
+ its workers measured. Charges are in ``recorded_training_usd``; nothing here is billed."""
progress = job.progress or {}
recorded = float(job.cost_usd) if job.cost_usd is not None else None
training = estimate_usage(progress.get("compute_usage", []), recorded_gpu=recorded is not None)
preparation = estimate_usage(
[(progress.get("preparation", {}).get("report") or {}).get("compute_usage", {})]
)
- estimates = [training["estimated_usd"], preparation["estimated_usd"]]
return {
"recorded_training_usd": recorded,
"recorded_at": job.cost_synced_at.isoformat() if job.cost_synced_at else None,
- "recorded_basis": (job.result or {}).get("compute_charge") or None,
- "coverage": "training_gpu" if job.provider == "modal" else "provider_training",
+ "coverage": "modal_containers" if job.provider == "modal" else "provider_training",
"training_compute": training,
"preparation_compute": preparation,
- "recorded_plus_estimated_usd": recorded + sum(estimates)
- if recorded is not None and all(value is not None for value in estimates)
- else None,
"unreported_components": [
"evaluation_and_inference_reported_separately",
- "storage",
+ "storage_included",
"network",
- "local_orchestration",
"provider_billing_adjustments",
],
"all_in_actual_usd": None,
diff --git a/overbae/services/container_meter.py b/overbae/services/container_meter.py
new file mode 100644
index 00000000..1d9323d5
--- /dev/null
+++ b/overbae/services/container_meter.py
@@ -0,0 +1,243 @@
+"""Charges Modal containers from their reports (modal_shared/container_meter.py).
+
+Each report's new GPU, CPU and memory seconds are priced at Modal's live rates and split
+across the refs the container served by their request seconds. Time with no request goes to
+the ref the container served last, or was started for. One ledger row per container and ref
+grows while the container runs. A report that names no ref, or a ref no record matches, is
+our cost: it is logged, never charged to anyone.
+"""
+
+from __future__ import annotations
+
+import logging
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+
+import modal
+from django.core.cache import cache
+from django.db import transaction
+from django.utils import timezone
+
+from modal_shared import container_meter
+from overbae.models import (
+ BillingService,
+ DecisionPerformanceRun,
+ DedicatedDeployment,
+ DeployedModel,
+ EvalRun,
+ FinetuningJob,
+ MeteredContainer,
+ NativeEvaluationPlan,
+ TrainingPreparation,
+)
+from overbae.services import billing_ledger, provider_pricing
+
+logger = logging.getLogger(__name__)
+
+# A container that reported nothing for this long has stopped; its last report is final.
+STALE = timedelta(minutes=5)
+BASE_FETCH_KEY = "container-meter:base-fetch:{}"
+
+
+def note_base_fetch(base_model: str, ref: str) -> None:
+ """A base download is shared; the work that asked for it first pays for it."""
+ cache.add(BASE_FETCH_KEY.format(base_model), ref, timeout=6 * 3600)
+
+
+def _when(seconds: float) -> datetime:
+ return datetime.fromtimestamp(seconds, UTC)
+
+
+def resolve(ref: str, function: str = "") -> billing_ledger.Cause | None:
+ """The cause a billing ref names: the project and work a container served."""
+ kind, _, ident = ref.partition(":")
+ service = BillingService
+ try:
+ if kind == "finetune_job":
+ job = FinetuningJob.objects.filter(pk=ident).first()
+ return job and billing_ledger.cause(
+ job.project_id, service.FINETUNING_JOB, kind, job.pk, actor=job.triggered_by_id
+ )
+ if kind == "training_run":
+ job = FinetuningJob.objects.filter(remote_job_id__startswith=f"{ident}:").first()
+ return job and resolve(f"finetune_job:{job.pk}")
+ if kind == "training_preparation":
+ job = FinetuningJob.objects.filter(preparation_id=ident).order_by("created_at").first()
+ if job is not None:
+ return resolve(f"finetune_job:{job.pk}")
+ preparation = (
+ TrainingPreparation.objects.filter(pk=ident).select_related("cell__dataset").first()
+ )
+ return preparation and billing_ledger.cause(
+ preparation.cell.dataset.project_id, service.FINETUNING_JOB, kind, preparation.pk
+ )
+ if kind == "base_model":
+ asked = cache.get(BASE_FETCH_KEY.format(ident))
+ return asked and resolve(asked)
+ if kind in ("served_model", "decision_weights"):
+ if ident.startswith("dedicated/"):
+ dedicated = DedicatedDeployment.objects.filter(pk=ident.split("/", 1)[1]).first()
+ return dedicated and billing_ledger.cause(
+ dedicated.project_id,
+ service.DEDICATED_INFERENCE,
+ "dedicated_deployment",
+ dedicated.pk,
+ actor=dedicated.started_by_id,
+ )
+ field = "model_id" if kind == "served_model" else "weights_path"
+ deployed = (
+ DeployedModel.objects.filter(**{field: ident}).order_by("-created_at").first()
+ )
+ if deployed is None:
+ return None
+ if function.startswith("decision_dedicated"):
+ dedicated = deployed.dedicated_deployments.order_by("-created_at").first()
+ if dedicated is not None:
+ return resolve(f"served_model:{dedicated.served_model_id}")
+ return billing_ledger.cause(
+ deployed.project_id, service.INFERENCE_FT_MODEL, "deployed_model", deployed.pk
+ )
+ if kind == "native_evaluation":
+ plan = NativeEvaluationPlan.objects.filter(pk=ident).first()
+ return plan and billing_ledger.cause(
+ plan.project_id, service.EVALUATION, kind, plan.pk, actor=plan.triggered_by_id
+ )
+ if kind == "decision_performance":
+ run = (
+ DecisionPerformanceRun.objects.filter(pk=ident).select_related("evaluation").first()
+ )
+ return run and billing_ledger.cause(
+ run.project_id,
+ service.EVALUATION,
+ kind,
+ run.pk,
+ actor=run.evaluation.triggered_by_id,
+ )
+ if kind == "eval_run":
+ run = EvalRun.objects.filter(pk=ident).first()
+ return run and billing_ledger.cause(run.project_id, service.EVALUATION, kind, run.pk)
+ except (ValueError, TypeError):
+ # A malformed id names nothing.
+ return None
+ return None
+
+
+def _rates(card, report):
+ """USD per second of each resource; None while Modal's rates are not known."""
+ rates = card["rates"]
+ cpu, memory = rates.get("cpu_hour_cost"), rates.get("mem_gib_hour_cost")
+ gpu = 0.0
+ if report.get("gpu_count"):
+ gpu = provider_pricing.gpu_rate(card, report.get("gpu"))
+ if cpu is None or memory is None or gpu is None:
+ return None
+ return {
+ "gpu": Decimal(str(gpu)),
+ "cpu": Decimal(str(cpu / 3600)),
+ "memory": Decimal(str(memory / 3600)),
+ }
+
+
+def _resource(report) -> str:
+ gpu = f"{report['gpu']} x{report['gpu_count']}, " if report.get("gpu_count") else ""
+ return f"modal {gpu}{report.get('cpu')} CPU, {report.get('memory_gib')} GiB"
+
+
+def charge_report(report: dict, card: dict) -> bool:
+ """Charge what a container reported since its last charge. False when it waits: for
+ Modal's rates, or for the first ref of a container that is still starting."""
+ rates = _rates(card, report)
+ if rates is None:
+ return False
+ seen = _when(report["seen_at"])
+ with transaction.atomic():
+ state, _ = MeteredContainer.objects.select_for_update().get_or_create(
+ container_id=report["container"],
+ defaults={
+ "function": report.get("function", "")[:128],
+ "started_at": _when(report["started_at"]),
+ "charged_until": _when(report["started_at"]),
+ },
+ )
+ done = state.charged
+ wall = Decimal(str(report["wall_seconds"])) - Decimal(str(done.get("wall", 0)))
+ if wall <= 0:
+ return True
+ cpu = Decimal(str(report["cpu_core_seconds"])) - Decimal(str(done.get("cpu", 0)))
+ memory = Decimal(str(report["memory_gib_seconds"])) - Decimal(str(done.get("memory", 0)))
+ gpu = wall * int(report.get("gpu_count") or 0)
+ usd = gpu * rates["gpu"] + cpu * rates["cpu"] + memory * rates["memory"]
+ served = {
+ ref: Decimal(str(seconds)) - Decimal(str(done.get("refs", {}).get(ref, 0)))
+ for ref, seconds in (report.get("refs") or {}).items()
+ }
+ served = {ref: seconds for ref, seconds in served.items() if seconds > 0}
+ idle = report.get("last_ref") or state.last_ref or report.get("default_ref")
+ if not served and not idle and not report.get("stopped"):
+ return False
+ total = sum(served.values())
+ shares = (
+ {ref: seconds / total for ref, seconds in served.items()}
+ if total
+ else ({idle: Decimal(1)} if idle else {})
+ )
+ if not shares:
+ logger.error("Container time with no billing ref is absorbed: %s", report["container"])
+ charged_jobs = set()
+ for ref, share in shares.items():
+ found = resolve(ref, report.get("function", ""))
+ if found is None:
+ logger.error("Container time for an unknown billing ref is absorbed: %s", ref)
+ continue
+ if found.kind == "finetune_job":
+ charged_jobs.add(found.id)
+ billing_ledger.accrue(
+ found,
+ usd * share,
+ key=f"modal:{report['container']}:{found.ref}"[:255],
+ resource=_resource(report),
+ seconds=wall * share,
+ provider_ref=report["container"],
+ started_at=state.charged_until,
+ ended_at=seen,
+ components={
+ "gpu_seconds": float(gpu * share),
+ "cpu_core_seconds": float(cpu * share),
+ "memory_gib_seconds": float(memory * share),
+ },
+ )
+ for job in charged_jobs:
+ billing_ledger.mirror_job_spend(job)
+ state.charged = {
+ "wall": report["wall_seconds"],
+ "cpu": report["cpu_core_seconds"],
+ "memory": report["memory_gib_seconds"],
+ "refs": report.get("refs") or {},
+ }
+ state.last_ref = (report.get("last_ref") or idle or "")[:255]
+ state.charged_until = seen
+ state.finished = bool(report.get("stopped"))
+ state.save()
+ return True
+
+
+def collect() -> int:
+ """Charge every container's latest report; forget a container once it has stopped."""
+ card = provider_pricing.current_rates()
+ store = modal.Dict.from_name(container_meter.STORE, create_if_missing=True)
+ now = timezone.now()
+ charged = 0
+ for key, report in list(store.items()):
+ if now - _when(report["seen_at"]) > STALE:
+ # It stopped without a last report: up to its last report is all that is known.
+ report = {**report, "stopped": True}
+ try:
+ done = charge_report(report, card)
+ except Exception:
+ logger.exception("Container report was not charged: %s", key)
+ continue
+ charged += done
+ if done and report.get("stopped"):
+ MeteredContainer.objects.filter(pk=report["container"]).update(finished=True)
+ store.pop(key)
+ return charged
diff --git a/overbae/services/decision_performance.py b/overbae/services/decision_performance.py
index 18d8abb6..b327575f 100644
--- a/overbae/services/decision_performance.py
+++ b/overbae/services/decision_performance.py
@@ -19,8 +19,7 @@ from overbae.models import (
FinetuningJob,
Project,
)
-from overbae.services import native_evaluation
-from overbae.services.billing_ledger import charge_llm_usage
+from overbae.services import billing_ledger, model_meter, native_evaluation
from overbae.services.compute_costs import estimate_usage
from overbae.services.datasets import heartbeat
from overbae.services.decision_benchmark_scoring import records
@@ -289,6 +288,13 @@ def advance(run_id):
totals = dict(run.results.get("active_seconds", {}))
try:
prepare_workload(run)
+ found = billing_ledger.cause(
+ run.project_id,
+ BillingService.EVALUATION,
+ "decision_performance",
+ run.pk,
+ actor=run.evaluation.triggered_by_id,
+ )
inputs = run.workload["inputs"] * settings["repetitions"]
for original in native_evaluation.participants(run.evaluation):
participant = dict(original)
@@ -342,14 +348,6 @@ def advance(run_id):
except (ValueError, KeyError, TypeError) as exc:
request.state, request.error = "failed", type(exc).__name__
request.save()
- charge_llm_usage(
- run.evaluation.triggered_by,
- request.usage,
- service=BillingService.EVALUATION,
- project_id=run.project_id,
- idempotency_key=f"decision-performance:{request.pk}",
- metadata={"performance_run": str(run.pk)},
- )
if request.state == "submitting" and not request.call_id:
request.state, request.error = (
"submission_unknown",
@@ -375,7 +373,9 @@ def advance(run_id):
future = executor.submit(native_result, call, clock)
else:
future = executor.submit(
- external_request, participant, inputs[position]
+ model_meter.carried(external_request, found),
+ participant,
+ inputs[position],
)
futures[future] = request
launched += 1
@@ -416,14 +416,6 @@ def advance(run_id):
if isinstance(exc, decisions.DecisionError):
request.usage = exc.stats
request.save()
- charge_llm_usage(
- run.evaluation.triggered_by,
- request.usage,
- service=BillingService.EVALUATION,
- project_id=run.project_id,
- idempotency_key=f"decision-performance:{request.pk}",
- metadata={"performance_run": str(run.pk)},
- )
if launched:
totals[participant["key"]] = (
totals.get(participant["key"], 0) + time.perf_counter() - started_window
diff --git a/overbae/services/decision_providers.py b/overbae/services/decision_providers.py
index e0bafbfc..c5320f8d 100644
--- a/overbae/services/decision_providers.py
+++ b/overbae/services/decision_providers.py
@@ -21,8 +21,7 @@ from overbae.modal.model_registry import (
get_unsloth_image,
)
from overbae.models import BillingService, DecisionProviderRequest, FinetuningJob
-from overbae.services import evaluation_inputs
-from overbae.services.billing_ledger import charge_llm_usage
+from overbae.services import billing_ledger, evaluation_inputs, model_meter
MAX_INSTRUCTIONS = 8000
@@ -289,18 +288,6 @@ def complete_response(record, request, participant):
record.save()
-def meter_attempts(record):
- for index, attempt in enumerate(record.attempts):
- charge_llm_usage(
- record.plan.triggered_by,
- attempt.get("usage"),
- service=BillingService.EVALUATION,
- project_id=record.plan.project_id,
- idempotency_key=f"decision-evaluation:{record.pk}:{index}",
- metadata={"plan": str(record.plan_id), "participant": record.participant},
- )
-
-
def usage(plan, participant, role):
entries = DecisionProviderRequest.objects.filter(plan=plan, participant=participant, role=role)
counts = dict(entries.values("state").annotate(count=Count("id")).values_list("state", "count"))
@@ -366,7 +353,6 @@ def external_step(plan, role, participant):
record.save()
continue
if record.state == "received":
- meter_attempts(record)
complete_response(record, row["decision"], participant)
elif record.state not in {"completed", "failed", "incompatible"}:
try:
@@ -376,6 +362,13 @@ def external_step(plan, role, participant):
record.save()
continue
pending[record.pk] = (record, row["decision"])
+ found = billing_ledger.cause(
+ plan.project_id,
+ BillingService.EVALUATION,
+ "native_evaluation",
+ plan.pk,
+ actor=plan.triggered_by_id,
+ )
with ThreadPoolExecutor(max_workers=plan.config["inference"]["concurrency"]) as executor:
futures = {}
for record, request in pending.values():
@@ -395,7 +388,10 @@ def external_step(plan, role, participant):
"state": request["state"],
"questions": {"decision": question(request, participant.get("instructions", ""))},
}
- futures[executor.submit(decisions.request_once, body)] = (record, request)
+ futures[executor.submit(model_meter.carried(decisions.request_once, found), body)] = (
+ record,
+ request,
+ )
errors = []
for future in as_completed(futures):
record, request = futures[future]
@@ -409,7 +405,6 @@ def external_step(plan, role, participant):
outcome="received",
)
record.save()
- meter_attempts(record)
complete_response(record, request, participant)
except decisions.DecisionError as exc:
code = exc.stats.get("status_code")
@@ -445,7 +440,6 @@ def external_step(plan, role, participant):
)
record.error = exc.reason
record.save()
- meter_attempts(record)
if record.state == "retryable":
errors.append(RetryableEvaluationError(exc.reason))
except Exception as exc:
diff --git a/overbae/services/dedicated.py b/overbae/services/dedicated.py
index 20989700..7e6d10cf 100644
--- a/overbae/services/dedicated.py
+++ b/overbae/services/dedicated.py
@@ -9,14 +9,14 @@ from datetime import UTC, timedelta
from decimal import Decimal
from django.db import IntegrityError, transaction
-from django.db.models import Q
+from django.db.models import Q, Sum
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from overbae.core.errors import InputValidationError
-from overbae.models import BillingService, DedicatedDeployment, DeployedModel
+from overbae.models import BillingTelemetry, DedicatedDeployment, DeployedModel
from overbae.services import dedicated_progress, dedicated_runtime
-from overbae.services.billing_ledger import balance_usd, charge_credits
+from overbae.services.billing_ledger import balance_usd
from overbae.services.billing_provider import commercial_billing_enabled
from overbae.services.dedicated_offer import credits_per_hour, hourly_usd, offers, serving_shape
from overbae.services.dedicated_offer import gpu_names_for as offered_gpus
@@ -130,10 +130,13 @@ def _quote(gpu_type: str):
return price, credits, parsed
-def _require_floor(user, price: Decimal, minimum: int) -> None:
- if not commercial_billing_enabled() or minimum < 1 or user is None:
+def _require_floor(project, price: Decimal, minimum: int) -> None:
+ """The project's owner pays: their balance must cover a first minute."""
+ if not commercial_billing_enabled() or minimum < 1:
return
- if balance_usd(user) < dedicated_runtime.minute_usd(price, minimum):
+ if project.owner_id is None or balance_usd(project.owner_id) < dedicated_runtime.minute_usd(
+ price, minimum
+ ):
raise InputValidationError(BALANCE_TOO_LOW)
@@ -155,7 +158,7 @@ def start(
min_replicas, max_replicas, scale_to_zero, idle_shutdown_seconds
)
price, credits, fetched = _quote(gpu_type)
- _require_floor(user, price, minimum)
+ _require_floor(deployed.project, price, minimum)
try:
return DedicatedDeployment.objects.create(
project_id=deployed.project_id,
@@ -205,7 +208,7 @@ def update(
if gpu != row.gpu_type:
dedicated_runtime.release(row, row.gpu_type)
price, credits, fetched = _quote(gpu)
- _require_floor(row.started_by, price, minimum)
+ _require_floor(row.project, price, minimum)
DedicatedDeployment.objects.filter(pk=row.pk).update(
gpu_type=gpu,
min_replicas=minimum,
@@ -243,31 +246,20 @@ def due():
def _meter(row: DedicatedDeployment, now) -> None:
- if row.last_billed_at is None or row.started_by_id is None:
- return
- minutes = int((now - row.last_billed_at).total_seconds() // 60)
- if minutes <= 0:
- return
- replicas = row.running_replicas
- if replicas:
- usd = dedicated_runtime.minute_usd(row.rate_usd_per_gpu_hour, replicas) * minutes
- charged = charge_credits(
- row.started_by,
- usd,
- BillingService.DEDICATED_INFERENCE,
- project_id=row.project_id,
- idempotency_key=f"dedicated:{row.id}:{row.last_billed_at.isoformat()}",
- metadata={"replicas": replicas, "minutes": minutes, "gpu_type": row.gpu_type},
- )
- if charged is not None:
- row.accrued_credits += (usd * 100).quantize(Decimal("0.01"))
- row.last_billed_at = row.last_billed_at + timedelta(minutes=minutes)
+ """What the deployment's containers were charged so far, from the ledger
+ (services/container_meter.py charges them)."""
+ spent = BillingTelemetry.objects.filter(
+ cause_kind="dedicated_deployment", cause_id=str(row.pk)
+ ).aggregate(total=Sum("amount"))["total"]
+ row.accrued_credits = (-(spent or Decimal(0)) * 100).quantize(Decimal("0.01"))
+ row.last_billed_at = now
def _broke(row: DedicatedDeployment) -> bool:
- if not commercial_billing_enabled() or row.running_replicas < 1 or row.started_by_id is None:
+ if not commercial_billing_enabled() or row.running_replicas < 1:
return False
- return balance_usd(row.started_by) < dedicated_runtime.minute_usd(
+ owner = row.project.owner_id
+ return owner is None or balance_usd(owner) < dedicated_runtime.minute_usd(
row.rate_usd_per_gpu_hour, row.running_replicas
)
@@ -283,7 +275,7 @@ def advance(deployment_id: str) -> None:
with transaction.atomic():
row = (
DedicatedDeployment.objects.select_for_update(of=("self",))
- .select_related("deployed_model", "started_by")
+ .select_related("deployed_model", "started_by", "project")
.filter(pk=deployment_id)
.first()
)
diff --git a/overbae/services/deployed_chat.py b/overbae/services/deployed_chat.py
index fccfb39f..e1b8602a 100644
--- a/overbae/services/deployed_chat.py
+++ b/overbae/services/deployed_chat.py
@@ -5,15 +5,12 @@ from __future__ import annotations
import logging
import uuid
from datetime import datetime
-from decimal import Decimal
from typing import Any
from django.db.models import Q
from django.utils import timezone
-from overbae.models import BillingService, Capability, DeployedModel, InferenceCall, User
-from overbae.services.billing_ledger import charge_credits
-from overbae.services.inference_pricing import estimate_call_cost
+from overbae.models import Capability, DeployedModel, InferenceCall
logger = logging.getLogger(__name__)
@@ -60,7 +57,6 @@ def record_inference_call(
usage: dict | None,
latency_ms: float | None,
is_cold: bool = False,
- user: User | None = None,
metrics: dict | None = None,
*,
request_id: uuid.UUID | None = None,
@@ -69,15 +65,15 @@ def record_inference_call(
source: str = "internal",
requested_model: str = "",
started_at: datetime | None = None,
- bill: bool = True,
) -> None:
- """Persist one InferenceCall. Never raises.
+ """Persist one InferenceCall. Never raises. Its GPU time is charged by the container
+ meter (services/container_meter.py), which divides a container among its requests.
``metrics`` is vLLM's per-request timing block and wins when present: warm
``latency_ms`` becomes ``time_to_first_token_ms + generation_time_ms``, which
excludes queue wait, network and container boot. COLD calls keep the gateway
- wall-clock so the boot overhead still feeds ``cold_start_ms``; wall-clock also
- drives the cost/GPU-time proxy and is the fallback when vLLM sends no metrics
+ wall-clock so the boot overhead still feeds ``cold_start_ms``; wall-clock is
+ the fallback when vLLM sends no metrics
(``n > 1``/multi-prompt, or an older worker).
"""
usage = usage or {}
@@ -98,17 +94,11 @@ def record_inference_call(
stored_latency_ms = latency_ms
try:
- cost = (
- estimate_call_cost(deployed.gpu_type, latency_ms)
- if bill and (outcome == "succeeded" or usage)
- else None
- )
call = InferenceCall.objects.create(
deployed_model=deployed,
project_id=deployed.project_id,
prompt_tokens=int(usage.get("prompt_tokens") or 0),
completion_tokens=completion_tokens,
- cost=cost,
tokens_per_second=tps,
latency_ms=stored_latency_ms,
is_cold=is_cold,
@@ -138,14 +128,5 @@ def record_inference_call(
first_application_request_at=call.created_at
)
active.update(last_application_request_at=call.created_at)
- if user is not None and cost:
- charge_credits(
- user,
- Decimal(str(cost)),
- BillingService.INFERENCE_FT_MODEL,
- project_id=deployed.project_id,
- idempotency_key=f"inference-ft:{call.id}",
- metadata={"inference_call_id": str(call.id), "model_id": deployed.model_id},
- )
except Exception:
logger.exception("Failed to record InferenceCall for %s", deployed.model_id)
diff --git a/overbae/services/deployment.py b/overbae/services/deployment.py
index ecbb5f37..a980ec97 100644
--- a/overbae/services/deployment.py
+++ b/overbae/services/deployment.py
@@ -28,7 +28,7 @@ from overbae.models import (
FinetuningJobEval,
OperationalEvent,
)
-from overbae.services import operational_progress, provider_progress
+from overbae.services import container_meter, operational_progress, provider_progress
from overbae.services.decision_serving import current_runtime
from overbae.services.finetuning_runner import MAX_ACTIVITY_LINES
from overbae.services.model_catalog import resolve_training_openrouter_slug
@@ -428,6 +428,8 @@ def _remote_operation(deployed: DeployedModel):
cfg = get_model_config_any_backend(deployed.base_model_id) or {}
stage = deployed.deployment_stage
if stage == "base":
+ if job is not None:
+ container_meter.note_base_fetch(base, f"finetune_job:{job.pk}")
return modal.Function.from_name(
"overmind-register", "fetch_base_model", environment_name=env
), {"base_model": base}
diff --git a/overbae/services/experiments/describe.py b/overbae/services/experiments/describe.py
index df4b022d..96dd8772 100644
--- a/overbae/services/experiments/describe.py
+++ b/overbae/services/experiments/describe.py
@@ -3,17 +3,17 @@
import json
from decimal import Decimal
-from django.db.models import Count, Prefetch
+from django.db.models import Count, Prefetch, Sum
from overbae.models import (
+ BillingTelemetry,
Cell,
- EvalRunRow,
Experiment,
ExperimentRun,
ExperimentStep,
- FinetuningJob,
)
from overbae.services.assistant import threads
+from overbae.services.billing_ledger import CREDITS_PER_USD
from overbae.services.datasets import partition_plans
from overbae.services.experiments import document as flow
from overbae.services.experiments import records
@@ -180,43 +180,21 @@ def _pinned(project, document) -> list[dict]:
def spend(found: Experiment, since=None) -> dict:
- """What the experiment's work cost as measured, in USD, and the parts no record prices:
- an unmeasured part is named, never estimated."""
- unknown, total = set(), Decimal(0)
+ """What the ledger charged to the experiment, in credits, and the costs of its work that
+ are charged to the project rather than to one experiment."""
+ rows = BillingTelemetry.objects.filter(experiment=found, amount__lt=0)
+ if since is not None:
+ rows = rows.filter(timestamp__gte=since)
+ total = rows.aggregate(total=Sum("amount"))["total"] or Decimal(0)
events = found.assistant_thread.events.all()
- roots = found.runs.filter(parent=None).values_list("pk", flat=True)
- steps = ExperimentStep.objects.filter(run__in=records.run_tree(roots))
if since is not None:
- events, steps = events.filter(created_at__gte=since), steps.filter(started_at__gte=since)
- if events.filter(kind="tool_result", payload__name="run_python").exists():
- unknown.add("workspace time")
- for cost in events.filter(kind__in=["assistant", "summary"]).values_list(
- "payload__usage__response_cost", flat=True
- ):
- if isinstance(cost, int | float):
- total += Decimal(str(cost))
- else:
- unknown.add("agent calls priced later")
- receipts = [
- r for found_receipts in steps.values_list("receipts", flat=True) for r in found_receipts
- ]
- jobs = [r["id"] for r in receipts if r.get("kind") == "finetune_job"]
- for cost in FinetuningJob.objects.filter(pk__in=jobs).values_list("cost_usd", flat=True):
- if cost is None:
- unknown.add("training not priced yet")
- else:
- total += cost
- runs = [r["id"] for r in receipts if r.get("kind") == "eval_run"]
- if runs:
- unknown.add("evaluation judging")
- for cost in EvalRunRow.objects.filter(run__in=runs).values_list(
- "metadata__cost", flat=True
- ):
- if isinstance(cost, int | float):
- total += Decimal(str(cost))
- named = {"native_evaluation": "decision evaluation", "deployment": "serving"}
- unknown |= {named[r["kind"]] for r in receipts if r.get("kind") in named}
- return {"measured_usd": float(round(total, 4)), "unknown": sorted(unknown)}
+ events = events.filter(created_at__gte=since)
+ # The workspace is the project's, shared by its experiments.
+ shared = events.filter(kind="tool_result", payload__name="run_python").exists()
+ return {
+ "spent_credits": float(round(-total * CREDITS_PER_USD, 2)),
+ "not_attributed": ["workspace time"] if shared else [],
+ }
def triggers(found: Experiment) -> list[dict]:
@@ -230,7 +208,7 @@ def triggers(found: Experiment) -> list[dict]:
"threshold": trigger.threshold,
"sends": trigger.sends,
"max_sends": trigger.max_sends,
- "max_spend_usd": trigger.max_spend_usd,
+ "max_spend_credits": trigger.max_spend_credits,
"next_at": trigger.next_at,
"last_sent_at": trigger.last_sent_at,
}
diff --git a/overbae/services/experiments/runs.py b/overbae/services/experiments/runs.py
index 2ae08b99..54a5a562 100644
--- a/overbae/services/experiments/runs.py
+++ b/overbae/services/experiments/runs.py
@@ -190,12 +190,12 @@ def _agent_budget(experiment: Experiment) -> None:
)
if asked is not None and asked.origin == AssistantInput.Origin.USER:
return
- for trigger in experiment.triggers.filter(deleted_at=None, max_spend_usd__isnull=False):
- spent = Decimal(str(describe.spend(experiment, since=trigger.created_at)["measured_usd"]))
- if spent >= trigger.max_spend_usd:
+ for trigger in experiment.triggers.filter(deleted_at=None, max_spend_credits__isnull=False):
+ spent = Decimal(str(describe.spend(experiment, since=trigger.created_at)["spent_credits"]))
+ if spent >= trigger.max_spend_credits:
raise InputValidationError(
- f"The trigger's spend cap of ${trigger.max_spend_usd} is reached "
- f"(${spent:.2f} measured). Ask the user before starting another run."
+ f"The trigger's spend cap of {trigger.max_spend_credits} credits is reached "
+ f"({spent:.2f} charged). Ask the user before starting another run."
)
diff --git a/overbae/services/experiments/triggers.py b/overbae/services/experiments/triggers.py
index e4dd3f12..b2ade1f5 100644
--- a/overbae/services/experiments/triggers.py
+++ b/overbae/services/experiments/triggers.py
@@ -11,6 +11,7 @@ from django.utils import timezone
from overbae.core.errors import InputValidationError
from overbae.innermind import health
from overbae.models import AssistantInput, Capability, ExperimentTrigger
+from overbae.services import billing_ledger
from overbae.services.experiments import describe, operator, records
Kind = ExperimentTrigger.Kind
@@ -30,7 +31,7 @@ def create(
max_sends,
capability=None,
threshold=None,
- max_spend_usd=None,
+ max_spend_credits=None,
) -> ExperimentTrigger:
if kind not in Kind.values:
raise InputValidationError("A trigger runs on a schedule or on failing traces.")
@@ -53,7 +54,7 @@ def create(
capability=found,
threshold=threshold if found else None,
max_sends=max_sends,
- max_spend_usd=max_spend_usd,
+ max_spend_credits=max_spend_credits,
next_at=now + timedelta(hours=hours) if kind == Kind.SCHEDULE else now,
created_by=user,
)
@@ -86,10 +87,12 @@ def fire_due() -> int:
deleted_at=None,
experiment__deleted_at=None,
)
- cap = trigger.max_spend_usd
+ cap = trigger.max_spend_credits
spent = describe.spend(trigger.experiment, trigger.created_at) if cap else None
- if cap is not None and Decimal(str(spent["measured_usd"])) >= cap:
- # Past its spend cap a trigger sends nothing: a send starts paid agent turns.
+ capped = cap is not None and Decimal(str(spent["spent_credits"])) >= cap
+ if capped or not billing_ledger.can_spend(trigger.experiment.project_id):
+ # Past its spend cap, or with no credits left, a trigger sends nothing: a send
+ # starts paid agent turns. It sends again after a top-up.
observed.update(next_at=now + window)
continue
if trigger.kind == Kind.FAILING_TRACES:
diff --git a/overbae/services/finetuning_runner.py b/overbae/services/finetuning_runner.py
index 57fb44c3..ed286cf8 100644
--- a/overbae/services/finetuning_runner.py
+++ b/overbae/services/finetuning_runner.py
@@ -19,7 +19,9 @@ from typing import Any, ClassVar
from django.conf import settings
+from modal_shared.container_meter import REF_ENV
from modal_shared.decisions import DECISION_OBJECTIVES
+from overbae.services import container_meter
from overbae.services.finetuning_policy import (
TrainingPlan,
derive_training_plan,
@@ -902,6 +904,7 @@ class ModalRunner(BaseFinetuningRunner):
"preparing_base_model",
"Checking base model weights and downloading missing files",
)
+ container_meter.note_base_fetch(env["MODEL_ID"], f"finetune_job:{job.pk}")
base = self._await_base_model(env["MODEL_ID"])
if training_kind == "lora":
from overbae.services.deployment import start_serving_snapshot # noqa: PLC0415
@@ -926,7 +929,10 @@ class ModalRunner(BaseFinetuningRunner):
options.update(profile_options(hp))
training_submission.dispatching(job, run_id)
call = train_fn.with_options(**options).spawn(
- run_id=run_id, env=env, gpu_type=gpu_type, gpu_count=gpu_count
+ run_id=run_id,
+ env={**env, REF_ENV: f"finetune_job:{job.pk}"},
+ gpu_type=gpu_type,
+ gpu_count=gpu_count,
)
remote_id = f"{run_id}:{call.object_id}"
diff --git a/overbae/services/inference_metrics.py b/overbae/services/inference_metrics.py
index 8e3dcae8..43273516 100644
--- a/overbae/services/inference_metrics.py
+++ b/overbae/services/inference_metrics.py
@@ -6,11 +6,12 @@ from datetime import timedelta
from itertools import pairwise
from django.db.models import Aggregate, Avg, Count, F, FloatField, Max, Q, Sum
-from django.db.models.functions import Cast, NullIf, Substr, Trunc
+from django.db.models.functions import Cast, NullIf, Trunc
from django.utils import timezone
from overbae.core.errors import InputValidationError
from overbae.models import BillingTelemetry, DeployedModel
+from overbae.services import billing_ledger
from overbae.services.model_catalog import estimate_cost
# Cap the per-model sample pulled into Python for percentile math. Bounds memory
@@ -106,12 +107,9 @@ def model_metrics(deployed: DeployedModel, *, period="all", source="all") -> dic
cold = Q(is_cold=True, outcome="succeeded")
agg = calls.aggregate(
last_request_at=Max("created_at"),
- cost_recorded_request_count=Count("cost"),
request_count=Count("id"),
prompt_tokens=Sum("prompt_tokens"),
completion_tokens=Sum("completion_tokens"),
- cost_total=Sum("cost"),
- cost_this_month=Sum("cost", filter=Q(created_at__gte=month_start)),
cold_start_ms=Avg("latency_ms", filter=cold),
cold_request_count=Count("id", filter=cold),
failed_request_count=Count("id", filter=Q(outcome="failed")),
@@ -124,7 +122,24 @@ def model_metrics(deployed: DeployedModel, *, period="all", source="all") -> dic
(p50_tps,) = _warm_percentiles(calls, "tokens_per_second", (0.5,))
prompt = agg["prompt_tokens"] or 0
completion = agg["completion_tokens"] or 0
- our_cost = agg["cost_total"]
+ # The serving containers' charges, shared and dedicated: a shared container's time is
+ # divided among its requests, so no single call, and no traffic source, has a cost of its
+ # own.
+ dedicated = [str(pk) for pk in deployed.dedicated_deployments.values_list("pk", flat=True)]
+ charges = BillingTelemetry.objects.filter(
+ Q(cause_kind="deployed_model", cause_id=str(deployed.pk))
+ | Q(cause_kind="dedicated_deployment", cause_id__in=dedicated)
+ )
+ duration = MONITORING_PERIODS[period]
+ if source != "all":
+ our_cost = None
+ elif duration:
+ our_cost = billing_ledger.window_spend(charges, timezone.now() - duration)
+ else:
+ spent = charges.aggregate(total=Sum("amount"))["total"]
+ our_cost = -spent if spent is not None else None
+ our_cost = float(our_cost) if our_cost is not None else None
+ month_cost = billing_ledger.window_spend(charges, month_start) if source == "all" else None
# Savings vs the capability's original (frontier) model — price the same
# tokens at that model's OpenRouter rate and subtract our GPU-time cost.
job = deployed.finetuning_job if deployed.finetuning_job_id else None
@@ -148,7 +163,6 @@ def model_metrics(deployed: DeployedModel, *, period="all", source="all") -> dic
return {
"dedicated_usage": dedicated_usage(deployed, period),
"last_request_at": agg["last_request_at"],
- "cost_recorded_request_count": agg["cost_recorded_request_count"],
"failed_request_count": agg["failed_request_count"],
"cold_request_count": agg["cold_request_count"],
"end_to_end_p50_ms": percentile(end_to_end, 0.5),
@@ -159,8 +173,8 @@ def model_metrics(deployed: DeployedModel, *, period="all", source="all") -> dic
"completion_tokens": completion,
"total_tokens": prompt + completion,
"cost": our_cost,
- "cost_this_month": agg["cost_this_month"],
- "cost_is_estimate": our_cost is not None,
+ "cost_this_month": float(month_cost) if month_cost is not None else None,
+ "cost_is_estimate": False,
"avg_tokens_per_second": p50_tps,
"avg_latency_ms": p50_latency,
"latency_p95_ms": p95_latency,
@@ -266,20 +280,16 @@ def dedicated_usage(deployed, period):
end = timezone.now()
duration = MONITORING_PERIODS[period]
ids = [str(pk) for pk in deployed.dedicated_deployments.values_list("pk", flat=True)]
- entries = (
- BillingTelemetry.objects.filter(
- project_id=deployed.project_id,
- service="dedicated-inference",
- timestamp__lte=end,
- )
- .annotate(deployment_ref=Substr("idempotency_key", 11, 36))
- .filter(deployment_ref__in=ids)
+ entries = BillingTelemetry.objects.filter(
+ project_id=deployed.project_id,
+ cause_kind="dedicated_deployment",
+ cause_id__in=ids,
+ timestamp__lte=end,
)
if duration:
entries = entries.filter(timestamp__gte=end - duration)
entries = entries.annotate(
- gpu_minutes=Cast("metadata__minutes", FloatField())
- * Cast("metadata__replicas", FloatField()),
+ gpu_minutes=Cast("metadata__gpu_seconds", FloatField()) / 60,
)
totals = entries.aggregate(
amount=Sum("amount"),
@@ -295,7 +305,7 @@ def dedicated_usage(deployed, period):
.order_by("bucket")
)
breakdown = list(
- entries.values(gpu_type=F("metadata__gpu_type"))
+ entries.values(gpu_type=F("resource"))
.annotate(credits=-Sum("amount") * 100)
.order_by("gpu_type")
)
diff --git a/overbae/services/inference_pricing.py b/overbae/services/inference_pricing.py
deleted file mode 100644
index 33503e0d..00000000
--- a/overbae/services/inference_pricing.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from __future__ import annotations
-
-from overbae.services import provider_pricing
-
-
-def gpu_usd_per_second(gpu_type: str) -> float | None:
- return provider_pricing.gpu_rate(provider_pricing.current_rates(), gpu_type)
-
-
-def estimate_call_cost(gpu_type: str, generation_time_ms: float | None) -> float | None:
- rate = gpu_usd_per_second(gpu_type)
- if rate is None or not generation_time_ms:
- return None
- return round((generation_time_ms / 1000.0) * rate, 6)
diff --git a/overbae/services/inference_requests.py b/overbae/services/inference_requests.py
index 889711f5..90e4916b 100644
--- a/overbae/services/inference_requests.py
+++ b/overbae/services/inference_requests.py
@@ -307,13 +307,11 @@ def finalize(request_id):
or ((request.completed_at or timezone.now()) - request.created_at).total_seconds()
* 1000,
request.is_cold,
- user=request.user,
request_id=request.pk,
outcome=request.state,
error_code=request.error_code,
source=request.payload.get("source", "mcp"),
requested_model=request.payload.get("model_id") or "",
- bill=not request.payload.get("dedicated_id"),
)
diff --git a/overbae/services/mcp/__init__.py b/overbae/services/mcp/__init__.py
index 045ffdd7..e43e725c 100644
--- a/overbae/services/mcp/__init__.py
+++ b/overbae/services/mcp/__init__.py
@@ -1,3 +1,3 @@
"""MCP protocol and catalog services."""
-CONTRACT_VERSION = "12.6.0"
+CONTRACT_VERSION = "13.0.0"
diff --git a/overbae/services/mcp/contracts/evaluations.py b/overbae/services/mcp/contracts/evaluations.py
index 9b3f6fa0..6f05b9b2 100644
--- a/overbae/services/mcp/contracts/evaluations.py
+++ b/overbae/services/mcp/contracts/evaluations.py
@@ -219,8 +219,8 @@ class EvaluationContextSuggestionContract(MCPModel):
context_window: int
max_output_tokens: int
reserved_output_tokens: int
- estimated_cost_usd: float | None
- cost_delta_usd: float | None
+ estimated_credits: float | None
+ credits_delta: float | None
class EvaluationContextCheckContract(MCPModel):
@@ -240,7 +240,7 @@ class EvaluationContextCheckContract(MCPModel):
estimated: bool
status: Literal["fits", "warning", "unknown"]
message: str
- estimated_cost_usd: float | None = None
+ estimated_credits: float | None = None
cost_basis: str = ""
suggestions: list[EvaluationContextSuggestionContract] = Field(
default_factory=list, max_length=3
@@ -255,8 +255,8 @@ class EvaluationJudgeOptionContract(MCPModel):
context_window: int | None
max_output_tokens: int | None
reserved_output_tokens: int
- estimated_cost_usd: float | None
- cost_delta_usd: float | None
+ estimated_credits: float | None
+ credits_delta: float | None
class CreditReadinessContract(MCPModel):
diff --git a/overbae/services/mcp/contracts/experiments.py b/overbae/services/mcp/contracts/experiments.py
index f2ee4388..00b52572 100644
--- a/overbae/services/mcp/contracts/experiments.py
+++ b/overbae/services/mcp/contracts/experiments.py
@@ -60,7 +60,10 @@ class InspectExperimentOutput(MCPModel):
run: dict[str, Any] | None = None
triggers: list[dict[str, Any]]
notes: str
- spend: dict[str, Any] = Field(description="Measured spend and the parts not measured.")
+ spend: dict[str, Any] = Field(
+ description="Credits the ledger charged to this experiment, and the costs charged to "
+ "its project but not to one experiment."
+ )
proposals: list[dict[str, Any]] = Field(description="Changes awaiting a person.")
catalog: list[dict[str, Any]] | None = None
resource_links: list[ResourceLinkContract]
@@ -154,8 +157,12 @@ class ConfigureExperimentTriggerInput(MCPModel):
instruction: str = Field(default="", max_length=8000)
hours: int = Field(default=24, ge=1, le=720)
max_sends: int = Field(default=5, ge=1, le=100)
- max_spend_usd: Decimal | None = Field(
- default=None, gt=0, max_digits=10, decimal_places=2, description="Stops unattended runs."
+ max_spend_credits: Decimal | None = Field(
+ default=None,
+ ge=1,
+ max_digits=12,
+ decimal_places=2,
+ description="Credits; stops unattended runs.",
)
capability: str | None = Field(default=None, max_length=255)
threshold: int | None = Field(default=None, ge=1)
diff --git a/overbae/services/mcp/contracts/projects.py b/overbae/services/mcp/contracts/projects.py
index 733b47e9..d97b7409 100644
--- a/overbae/services/mcp/contracts/projects.py
+++ b/overbae/services/mcp/contracts/projects.py
@@ -62,20 +62,29 @@ class GetCreditBalanceOutput(MCPModel):
observed_at: datetime
since: datetime | None
usage: CreditUsage
+ background_paused: bool = Field(
+ description="Scoring, signals and scheduled work wait until the balance is above zero."
+ )
class CreditAttributionInput(MCPModel):
since: AwareDatetime | None = None
before: AwareDatetime | None = None
- training_job: UUID | None = None
- training_experiment: UUID | None = None
+ experiment: UUID | None = None
+ run: UUID | None = None
+ service: str | None = Field(default=None, max_length=32)
+ cause_kind: str | None = Field(default=None, max_length=32)
+ cause_id: str | None = Field(default=None, max_length=64)
offset: int = Field(default=0, ge=0)
limit: int = Field(default=20, ge=1, le=100)
class CreditAttributionRow(MCPModel):
service: str
- training_job_id: str | None
+ cause_kind: str
+ cause_id: str
+ experiment_id: str | None
+ run_id: str | None
spent_credits: Decimal
entries: int
@@ -90,7 +99,5 @@ class CreditAttributionOutput(MCPModel):
total_groups: int
next_offset: int | None
credits_per_usd: Literal[100] = 100
- scope: Literal["connection_account_posted_project_charges"] = (
- "connection_account_posted_project_charges"
- )
+ scope: Literal["project_charges"] = "project_charges"
limitations: list[str]
diff --git a/overbae/services/mcp/resources.py b/overbae/services/mcp/resources.py
index fdde39df..f5048603 100644
--- a/overbae/services/mcp/resources.py
+++ b/overbae/services/mcp/resources.py
@@ -1310,13 +1310,15 @@ def interface_resource():
"credit_reporting": {
"tool": "get_credit_balance",
"units": "100 credits = 1 USD; decimal values are exact JSON strings.",
- "scope": "Account and project credentials expose the connection owner's account balance, lifetime grants/spending and account-wide usage by service. No project_id is required; since filters usage, not lifetime totals.",
- "task_budget": "Save observed_at before work, reuse it as since, and compare usage.spent_credits with the agreed budget before further paid work. Concurrent spending in the reported scope is included; unposted charges and external coding-agent costs are excluded. No reservation or hard spending cap is created. A zero recorded total does not prove pending work is free. With billing_enabled=false, metering is uncapped.",
+ "scope": "Account and project credentials expose the connection owner's account balance, lifetime grants/spending and account-wide usage by service. No project_id is required; since filters usage, not lifetime totals. get_credit_usage pages one project's charges by service, cause, experiment and run.",
+ "payer": "A project's owner pays for all its work at the provider's price, with no markup; each charge names its cause and who started it. Storage and compute on Overmind's own servers are included.",
+ "task_budget": "For work in a project, read get_credit_usage without since before the work and again before further paid work, and compare the growth of spent_credits with the agreed budget: the project's owner pays, so the connection's own account usage can miss it, and a running container's charge grows on its existing row, which since (a filter on when a row was created) does not count. Compare get_credit_balance spent_credits the same way only for a budget of the connection owner's account. A running container's charge grows each minute, and a model call the provider prices later posts then. No reservation or hard spending cap is created. With billing_enabled=false, metering is uncapped.",
+ "gate": "Paid work a person or agent starts needs the owner's balance above zero; the balance can go negative while work runs. With billing enabled, at zero background_paused is true: scoring, signals and scheduled work wait until a top-up. Without billing nothing pauses.",
},
"training_measurements": {
"planning": "save_training_plan retains immutable source/task, prepared versions, partition and attributed audit/baseline/sanity evidence. Full training requires no pilot; bind create_training_experiment with stage full directly. Stage pilot and measured pilot selection are optional. Primary metric is a JSON Pointer into check metrics; optional pilot selection requires finite task metrics and a verified checkpoint from matching data, and limits full recipes to declared budget-field changes. Hardware profiles are not quality pilots. New upstream identities require new matching evidence; old snapshots stay reproducible.",
"monitoring": "A frozen monitoring policy controls bounded development checks, generation scoring, checkpoint selection and optional early stopping. inspect_training_progress pages durable checks and exact evidence without invoking workers. cancel_finetune preserves completed evidence and records remote acknowledgement separately. Development metrics are not final benchmarks. Native target distributions and mean-only denominators remain distinct.",
- "billing": "New Modal training charges use deduplicated worker GPU-time receipts and recorded hardware, never local completion-observation delay. Missing usage remains unmeasured. recorded_basis identifies the retained charge calculation; historical charges without that receipt are not retrospectively relabelled.",
+ "billing": "Training, preparation and publication containers are charged by their reported container seconds at Modal's rates for GPU, CPU and memory, also when the job fails or is cancelled. Read them with get_credit_usage(cause_kind='finetune_job').",
"forecast": "Matching duration evidence comes from worker usage receipts, excluding collector delay; estimates and recorded charges are not all-in invoices or spend caps.",
"recovery": "The training collector renews a short lease while alive. Reconciliation closes missed terminal operational events from local receipts without another provider call; worker heartbeat timestamps are preserved.",
},
diff --git a/overbae/services/mcp/tools_evaluations.py b/overbae/services/mcp/tools_evaluations.py
index 9c5c325c..af5e5d27 100644
--- a/overbae/services/mcp/tools_evaluations.py
+++ b/overbae/services/mcp/tools_evaluations.py
@@ -195,9 +195,9 @@ def _scope_data(payload: EvaluationScopeInput, context: MCPContext, dataset: Dat
return data
-def _credits_available(user) -> bool:
+def _credits_available(project) -> bool:
try:
- require_credits(user)
+ require_credits(project)
except PaymentRequired:
return False
return True
@@ -326,7 +326,7 @@ def _readiness_sync(
if reason := evaluation_generation_error(cell.intent_report):
dataset_data.cell.fits = False
dataset_data.cell.reason = reason
- credits = CreditReadinessContract(required=True, available=_credits_available(context.user))
+ credits = CreditReadinessContract(required=True, available=_credits_available(context.project))
ready = bool(matrix and credits.available and dataset_data.cell and dataset_data.cell.fits)
links = [resource_link("datasets", str(dataset.id), dataset.name or "Dataset")]
if eval_set is not None:
@@ -360,7 +360,7 @@ def _run_sync(payload: RunEvaluationInput, context: MCPContext) -> RunEvaluation
"evaluation_not_ready", "The evaluation request is invalid.", error
) from None
try:
- require_credits(context.user)
+ require_credits(context.project)
except PaymentRequired as error:
raise MCPError(
"insufficient_credits", "Evaluation runs require available credits."
diff --git a/overbae/services/mcp/tools_experiments.py b/overbae/services/mcp/tools_experiments.py
index 06008077..09e6dc0a 100644
--- a/overbae/services/mcp/tools_experiments.py
+++ b/overbae/services/mcp/tools_experiments.py
@@ -8,7 +8,7 @@ from django.db import transaction
from overbae.core.errors import InputValidationError
from overbae.models import Experiment, ExperimentRun
-from overbae.services import workspaces
+from overbae.services import billing_ledger, workspaces
from overbae.services.assistant import threads, tools, turn
from overbae.services.datasets import partition_plans
from overbae.services.entity_resolution import resolve_capability
@@ -298,7 +298,7 @@ def _trigger_sync(
max_sends=payload.max_sends,
capability=capability.pk if capability else None,
threshold=payload.threshold,
- max_spend_usd=payload.max_spend_usd,
+ max_spend_credits=payload.max_spend_credits,
)
except InputValidationError as exc:
raise _refused(exc) from None
@@ -311,6 +311,8 @@ def _run_python_sync(payload: RunPythonInput, context: MCPContext) -> RunPythonO
"""A coding agent explores the project's data in place: its own kernel in the
experiment's workspace, offline, with the versions it names copied in read-only."""
found = _experiment(context, payload.experiment)
+ if not billing_ledger.can_spend(context.project.pk):
+ raise MCPError("insufficient_credits", "Running code requires available credits.")
versions = sorted({str(version) for version in payload.versions})
try:
run = tools.run_cell(
diff --git a/overbae/services/mcp/tools_finetuning.py b/overbae/services/mcp/tools_finetuning.py
index ade17e52..0f77533c 100644
--- a/overbae/services/mcp/tools_finetuning.py
+++ b/overbae/services/mcp/tools_finetuning.py
@@ -197,7 +197,7 @@ def _require_credits(context: MCPContext) -> None:
from overbae.api.credit_gate import PaymentRequired, require_credits
try:
- require_credits(context.user)
+ require_credits(context.project)
except PaymentRequired as error:
raise MCPError(
"insufficient_credits", "This operation requires available credits."
@@ -1013,6 +1013,7 @@ def _prepare_training_sync(payload, context):
)
if cell is None or (validation is not None and validation.active_cell is None):
raise MCPError("dataset_not_ready", "Select completed dataset versions.")
+ _require_credits(context)
try:
prep = begin_preparation(
cell,
diff --git a/overbae/services/mcp/tools_model_workflows.py b/overbae/services/mcp/tools_model_workflows.py
index 89085cd3..05561bab 100644
--- a/overbae/services/mcp/tools_model_workflows.py
+++ b/overbae/services/mcp/tools_model_workflows.py
@@ -138,7 +138,7 @@ def create_comparison(payload, context):
def launch_comparison(payload, context):
- require_credits(context.user)
+ require_credits(context.project)
plan = native_evaluation.launch(
workflow(context, "native_evaluation", payload.evaluation), user=context.user
)
@@ -146,6 +146,7 @@ def launch_comparison(payload, context):
def resume_comparison(payload, context):
+ require_credits(context.project)
plan = native_evaluation.resume(
workflow(context, "native_evaluation", payload.evaluation),
stage=payload.stage,
@@ -177,7 +178,7 @@ def save_training_plan(payload, context):
def launch_experiment(payload, context):
- require_credits(context.user)
+ require_credits(context.project)
experiment = training_experiments.launch(
workflow(context, "training_experiment", payload.experiment),
user=context.user,
@@ -187,6 +188,7 @@ def launch_experiment(payload, context):
def prepare_experiment(payload, context):
+ require_credits(context.project)
return output(
"training_experiment",
training_experiments.request_preparation(
@@ -205,6 +207,7 @@ def create_profile(payload, context):
def prepare_comparison(payload, context):
+ require_credits(context.project)
return output(
"native_evaluation",
native_evaluation.prepare(workflow(context, "native_evaluation", payload.evaluation)),
@@ -257,7 +260,7 @@ def list_workflows(payload, context):
def create_performance(payload, context):
- require_credits(context.user)
+ require_credits(context.project)
plan = workflow(context, "native_evaluation", payload.evaluation)
run = decision_performance.create(plan, **payload.model_dump(exclude={"evaluation"}))
if run.state == "queued":
@@ -266,6 +269,7 @@ def create_performance(payload, context):
def resume_performance(payload, context):
+ require_credits(context.project)
run = workflow(context, "decision_performance", payload.performance_run)
if run.state != "failed":
raise ValueError("Only stopped measurements can be resumed")
diff --git a/overbae/services/mcp/tools_projects.py b/overbae/services/mcp/tools_projects.py
index b88bf6a9..aa2200ce 100644
--- a/overbae/services/mcp/tools_projects.py
+++ b/overbae/services/mcp/tools_projects.py
@@ -140,7 +140,7 @@ def register_project_tools(catalog):
ToolDefinition(
name="get_credit_usage",
title="Get project credit usage",
- description="Page posted account-owned project charges by service and recorded training job. Pass the first page's observed_at as before on later pages. Null job attribution is unknown. Excludes unposted charges and estimates; does not enforce budgets.",
+ description="Page the project's charges in credits, grouped by service, cause (such as eval_run and its id), experiment and run; filter by any of them. The project's owner pays for every charge. Pass the first page's observed_at as before on later pages: that fixes which charges appear, not their amounts, since a running container's charge grows each minute on its row. since and before filter by when a row was created; for a budget, compare spent_credits read without since at two times. Charges post within minutes of the provider billing them; nothing here is an estimate.",
input_model=CreditAttributionInput,
output_model=CreditAttributionOutput,
read_only=True,
@@ -232,6 +232,4 @@ def register_project_tools(catalog):
def get_credit_usage(payload, context):
if payload.since and payload.before and payload.since >= payload.before:
raise MCPError("invalid_input", "since must precede before.")
- return CreditAttributionOutput(
- **project_credit_report(context.user, context.project, **payload.model_dump())
- )
+ return CreditAttributionOutput(**project_credit_report(context.project, **payload.model_dump()))
diff --git a/overbae/services/model_meter.py b/overbae/services/model_meter.py
new file mode 100644
index 00000000..12eb4999
--- /dev/null
+++ b/overbae/services/model_meter.py
@@ -0,0 +1,147 @@
+"""The one meter for OpenRouter. Every request the provider answered is charged at what it
+billed (`usage.cost`), keyed by its generation id, to the cause the caller set with
+`billed`. A generation whose cost did not arrive, as when a stream was cut, is priced later
+from `/generation`. A request with no cause is our cost: it is logged, never charged to
+anyone."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+from contextvars import ContextVar, copy_context
+from decimal import Decimal
+from typing import Any
+
+import httpx
+from django.conf import settings
+
+from overbae.core.model_registry import OPENROUTER_BASE_URL
+from overbae.services.billing_ledger import Cause, charge
+
+logger = logging.getLogger(__name__)
+
+_CAUSE: ContextVar[Cause | None] = ContextVar("billing_cause", default=None)
+
+
+@contextmanager
+def billed(found: Cause) -> Iterator[Cause]:
+ """Charge the model calls made inside the block, in this thread and the tasks and
+ threads it starts with its context, to ``found``."""
+ token = _CAUSE.set(found)
+ try:
+ yield found
+ finally:
+ _CAUSE.reset(token)
+
+
+def current() -> Cause | None:
+ return _CAUSE.get()
+
+
+def carried(fn: Callable[..., Any], found: Cause | None = None) -> Callable[..., Any]:
+ """``fn`` with this context's cause, or ``found``, for a thread pool, which starts its
+ threads without it."""
+ context = copy_context()
+
+ def run(*args, **kwargs):
+ if found is None:
+ return fn(*args, **kwargs)
+ with billed(found):
+ return fn(*args, **kwargs)
+
+ return lambda *args, **kwargs: context.run(run, *args, **kwargs)
+
+
+def _cost(value: Any) -> Decimal | None:
+ if isinstance(value, bool) or not isinstance(value, int | float | str | Decimal):
+ return None
+ try:
+ cost = Decimal(str(value))
+ except ArithmeticError:
+ return None
+ return cost if cost.is_finite() and cost >= 0 else None
+
+
+def settle(
+ generation: str | None,
+ cost: Any,
+ *,
+ model: str,
+ prompt_tokens: int | None = None,
+ completion_tokens: int | None = None,
+ found: Cause | None = None,
+) -> None:
+ """Charge one answered OpenRouter request. Never raises: the provider has billed it,
+ and the caller's work goes on."""
+ found = found or _CAUSE.get()
+ if not generation:
+ logger.warning("OpenRouter answer without a generation id for model %s", model)
+ return
+ if found is None:
+ logger.error("OpenRouter generation without a billing cause: %s", generation)
+ return
+ usage = {"prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens}
+ priced = _cost(cost)
+ try:
+ asyncio.get_running_loop()
+ on_loop = True
+ except RuntimeError:
+ on_loop = False
+ try:
+ if priced is None or on_loop:
+ # An unpriced generation waits for the provider; an event loop cannot write.
+ # Lazy: tasks import services.
+ from overbae.tasks.billing import price_generation
+
+ price_generation.delay(
+ found.as_dict(), generation, model, None if priced is None else str(priced), usage
+ )
+ return
+ charge_generation(found, generation, priced, model, usage)
+ except Exception:
+ logger.exception("Charging OpenRouter generation %s failed; it is retried", generation)
+ _retry(found, generation, model, priced, usage)
+
+
+def _retry(found: Cause, generation: str, model: str, priced: Decimal | None, usage) -> None:
+ # Lazy: tasks import services.
+ from overbae.tasks.billing import price_generation
+
+ try:
+ price_generation.delay(
+ found.as_dict(), generation, model, None if priced is None else str(priced), usage
+ )
+ except Exception:
+ logger.exception("OpenRouter generation charge is lost: %s", generation)
+
+
+def charge_generation(
+ found: Cause, generation: str, cost: Decimal, model: str, usage: dict[str, Any]
+) -> None:
+ charge(
+ found,
+ cost,
+ key=f"openrouter:{generation}",
+ resource=f"openrouter {model}",
+ quantity=Decimal(1),
+ unit="generation",
+ unit_usd=cost,
+ provider_ref=generation,
+ metadata={key: value for key, value in usage.items() if value is not None},
+ )
+
+
+def generation_cost(generation: str) -> Decimal | None:
+ """What OpenRouter billed for a generation; None while it has not priced it yet."""
+ response = httpx.get(
+ f"{OPENROUTER_BASE_URL}/generation",
+ params={"id": generation},
+ headers={"Authorization": f"Bearer {settings.OPENROUTER_API_KEY}"},
+ timeout=30,
+ )
+ if response.status_code == 404:
+ return None
+ response.raise_for_status()
+ return _cost(response.json()["data"].get("total_cost"))
diff --git a/overbae/services/provider_check.py b/overbae/services/provider_check.py
new file mode 100644
index 00000000..b1acf603
--- /dev/null
+++ b/overbae/services/provider_check.py
@@ -0,0 +1,108 @@
+"""The daily check that the ledger matches what the providers billed this environment.
+
+It reads Modal's billing report and the usage of this environment's OpenRouter key, compares
+each with the ledger's charges of the same provider and window, and logs an error when they
+differ by more than ``TOLERANCE``. It never changes the ledger. What the platform absorbs
+(gateways, internal checks, unattributed calls) shows up here as a difference.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+
+import httpx
+import modal
+from asgiref.sync import async_to_sync
+from django.conf import settings
+from django.db.models import Sum
+
+from overbae.core.model_registry import OPENROUTER_BASE_URL
+from overbae.models import BillingTelemetry
+
+logger = logging.getLogger(__name__)
+
+TOLERANCE = Decimal("0.02")
+MODAL_DAYS = 7
+
+
+def _ledger(prefix: str, **window) -> Decimal:
+ total = BillingTelemetry.objects.filter(resource__startswith=prefix, **window).aggregate(
+ total=Sum("amount")
+ )["total"]
+ return -(total or Decimal(0))
+
+
+def modal_billed(start: datetime, end: datetime) -> Decimal:
+ async def fetch():
+ report = modal.Workspace.from_context().billing.report
+ return await asyncio.wait_for(report.aio(start=start, end=end, resolution="d"), timeout=60)
+
+ items = async_to_sync(fetch)()
+ environment = settings.MODAL_ENVIRONMENT
+ return sum(
+ (
+ Decimal(str(item.cost))
+ for item in items
+ if not environment or getattr(item, "environment_name", "") == environment
+ ),
+ Decimal(0),
+ )
+
+
+def openrouter_billed() -> tuple[Decimal, datetime]:
+ """This key's usage this UTC month, and the month's start."""
+ response = httpx.get(
+ f"{OPENROUTER_BASE_URL}/key",
+ headers={"Authorization": f"Bearer {settings.OPENROUTER_API_KEY}"},
+ timeout=30,
+ )
+ response.raise_for_status()
+ now = datetime.now(UTC)
+ month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+ return Decimal(str(response.json()["data"]["usage_monthly"])), month
+
+
+def _compare(provider: str, billed: Decimal, charged: Decimal, window: str) -> dict:
+ difference = charged - billed
+ off = billed and abs(difference) / billed > TOLERANCE or not billed and charged > 0
+ result = {
+ "provider": provider,
+ "window": window,
+ "billed_usd": str(billed),
+ "charged_usd": str(charged),
+ "within_tolerance": not off,
+ }
+ if off:
+ logger.error(
+ "Ledger differs from the provider bill by more than 2%%: %s %s billed %s charged %s",
+ provider,
+ window,
+ billed,
+ charged,
+ )
+ return result
+
+
+def check() -> list[dict]:
+ results = []
+ end = datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0)
+ start = end - timedelta(days=MODAL_DAYS)
+ try:
+ billed = modal_billed(start, end)
+ # A container row is dated by when it stopped; one that spans the window's edge
+ # moves cost across it, which the seven days dilute.
+ charged = _ledger("modal", ended_at__gte=start, ended_at__lt=end)
+ results.append(_compare("modal", billed, charged, f"{start:%Y-%m-%d}..{end:%Y-%m-%d}"))
+ except Exception:
+ logger.exception("Modal billing report unavailable for the provider check")
+ if settings.OPENROUTER_API_KEY:
+ try:
+ billed, month = openrouter_billed()
+ charged = _ledger("openrouter", timestamp__gte=month)
+ results.append(_compare("openrouter", billed, charged, f"{month:%Y-%m} to date"))
+ except Exception:
+ logger.exception("OpenRouter key usage unavailable for the provider check")
+ return results
diff --git a/overbae/services/systemone.py b/overbae/services/systemone.py
index a09119fc..f7d5316c 100644
--- a/overbae/services/systemone.py
+++ b/overbae/services/systemone.py
@@ -8,7 +8,6 @@ import logging
import time
import uuid
from contextlib import suppress
-from decimal import Decimal
import requests
from django.conf import settings
@@ -17,7 +16,7 @@ from django.db.models import Q
from overbae.core.errors import InputValidationError
from overbae.core.model_registry import OPENROUTER_BASE_URL, decision_models, openrouter_configured
from overbae.models import APIToken, DeployedModel
-from overbae.services.billing_ledger import BillingService, charge_credits
+from overbae.services import model_meter
from overbae.services.decision_serving import worker
from overbae.services.deployed_chat import is_cold_start, record_inference_call
@@ -195,7 +194,6 @@ def call_deployment(
None,
(time.monotonic() - started) * 1000,
is_cold=cold,
- user=user,
outcome="failed",
error_code="provider_failed",
source=source,
@@ -209,7 +207,6 @@ def call_deployment(
None,
elapsed_ms,
is_cold=cold,
- user=user,
outcome="failed",
error_code=(result or {}).get("error_code") or "provider_failed",
source=source,
@@ -221,7 +218,6 @@ def call_deployment(
result.get("usage"),
elapsed_ms,
is_cold=cold,
- user=user,
source=source,
requested_model=deployment.model_id,
)
@@ -239,7 +235,7 @@ def call_deployment(
}
-def call_openrouter(user, body: dict) -> tuple[int, dict]:
+def call_openrouter(found, body: dict) -> tuple[int, dict]:
if not openrouter_configured():
return _error(503, "Frontier model inference is not configured.", "server_error")
try:
@@ -276,16 +272,12 @@ def call_openrouter(user, body: dict) -> tuple[int, dict]:
if not isinstance(payload, dict):
return _error(502, "The model provider returned an invalid response.", "server_error")
usage = payload.get("usage") if isinstance(payload.get("usage"), dict) else {}
- cost = usage.get("cost")
- if isinstance(cost, (int, float)) and not isinstance(cost, bool) and cost > 0:
- try:
- charge_credits(
- user,
- Decimal(str(cost)),
- BillingService.INFERENCE,
- idempotency_key=f"inference:{user.pk}:{uuid.uuid4()}",
- metadata={"model_id": body.get("model"), "usage": usage},
- )
- except Exception:
- logger.exception("Failed to charge systemone inference for user_id=%s", user.pk)
+ model_meter.settle(
+ payload.get("id"),
+ usage.get("cost"),
+ model=str(payload.get("model") or body.get("model") or ""),
+ prompt_tokens=usage.get("input_tokens"),
+ completion_tokens=usage.get("output_tokens"),
+ found=found,
+ )
return 200, payload
diff --git a/overbae/services/workspaces/modal_sandbox.py b/overbae/services/workspaces/modal_sandbox.py
index ab71eb0e..f4f0407d 100644
--- a/overbae/services/workspaces/modal_sandbox.py
+++ b/overbae/services/workspaces/modal_sandbox.py
@@ -22,6 +22,7 @@ import time
import tomllib
import uuid
from datetime import timedelta
+from decimal import Decimal
from functools import cache
from pathlib import Path
from typing import BinaryIO
@@ -34,7 +35,7 @@ from modal.exception import AlreadyExistsError, NotFoundError
from modal.volume import FileEntryType
from overbae.models import BillingService, Project, WorkspaceSandbox
-from overbae.services.billing_ledger import charge_credits
+from overbae.services.billing_ledger import Cause, charge
from overbae.services.workspaces import (
MAX_FILE_BYTES,
DataTooLargeError,
@@ -321,17 +322,28 @@ class ModalProvider:
# Another run charged this window since it was measured.
if row.billed_until != since:
continue
- if usage.cost and row.user_id is not None:
- charge_credits(
- row.user,
- usage.cost,
- BillingService.WORKSPACE,
- project_id=row.project_id,
- idempotency_key=f"modal-sandbox:{row.sandbox_id}:{row.billed_until.isoformat()}",
+ if usage.cost and row.project_id is not None:
+ seconds = Decimal(str((until - row.billed_until).total_seconds()))
+ cost = Decimal(str(usage.cost))
+ charge(
+ Cause(
+ project_id=str(row.project_id),
+ service=BillingService.WORKSPACE,
+ kind="workspace_sandbox",
+ id=row.sandbox_id,
+ payer_id=row.user_id,
+ resolved=True,
+ ),
+ cost,
+ key=f"modal-sandbox:{row.sandbox_id}:{row.billed_until.isoformat()}",
+ resource="modal sandbox",
+ quantity=seconds,
+ unit="second",
+ unit_usd=cost / seconds if seconds else None,
+ provider_ref=row.sandbox_id,
+ started_at=row.billed_until,
+ ended_at=until,
metadata={
- "sandbox": row.sandbox_id,
- "since": row.billed_until.isoformat(),
- "until": until.isoformat(),
"cpu_core_seconds": usage.billed_cpu_core_seconds,
"memory_gib_seconds": usage.billed_memory_gib_seconds,
"cost_by_resource": {
diff --git a/overbae/settings.py b/overbae/settings.py
index 4b09f301..5b6d5f99 100644
--- a/overbae/settings.py
+++ b/overbae/settings.py
@@ -450,8 +450,10 @@ CELERY_TASK_ROUTES = {
"overbae.tasks.assistant.stop_kernel": {"queue": "assistant"},
"overbae.tasks.assistant.forget_workspace_data": {"queue": "assistant"},
"overbae.tasks.assistant.remove_workspace": {"queue": "assistant"},
- "overbae.tasks.assistant.charge_generation": {"queue": "assistant"},
"overbae.tasks.assistant.bill_workspaces": {"queue": "assistant"},
+ "overbae.tasks.billing.price_generation": {"queue": "io"},
+ "overbae.tasks.billing.collect_container_meters": {"queue": "io"},
+ "overbae.tasks.billing.check_provider_bills": {"queue": "io"},
"overbae.tasks.assistant.sweep_idle_workspaces": {"queue": "assistant"},
# An advance calls platform tools and reads their records: short, network-bound work.
"overbae.tasks.experiments.advance_run": {"queue": "io"},
@@ -565,6 +567,17 @@ CELERY_BEAT_SCHEDULE = {
"task": "overbae.tasks.guest_cleanup.sweep_guest_workspaces",
"schedule": 86400.0,
},
+ # Modal containers report every minute; each collection charges what they reported.
+ "collect-container-meters": {
+ "task": "overbae.tasks.billing.collect_container_meters",
+ "schedule": 60.0,
+ "options": {"expires": 55.0},
+ },
+ # Read-only: alerts when the ledger and the providers' bills differ by more than 2%.
+ "check-provider-bills": {
+ "task": "overbae.tasks.billing.check_provider_bills",
+ "schedule": 86400.0,
+ },
"bill-workspaces": {
"task": "overbae.tasks.assistant.bill_workspaces",
"schedule": 900.0,
diff --git a/overbae/tasks/__init__.py b/overbae/tasks/__init__.py
index c25ec73b..16d6fbfb 100644
--- a/overbae/tasks/__init__.py
+++ b/overbae/tasks/__init__.py
@@ -4,6 +4,7 @@ from overbae.api.otlp import process_span
from . import ( # noqa: E402
assistant,
+ billing,
capability_rebind,
cleanup_modal,
cleanup_tmp,
@@ -27,6 +28,7 @@ from .dataset_context import refresh_dataset_context
__all__ = [
"assistant",
+ "billing",
"capability_rebind",
"cleanup_modal",
"cleanup_tmp",
diff --git a/overbae/tasks/assistant.py b/overbae/tasks/assistant.py
index 551c9c8b..9ec77694 100644
--- a/overbae/tasks/assistant.py
+++ b/overbae/tasks/assistant.py
@@ -2,9 +2,7 @@ import logging
from datetime import timedelta
from uuid import UUID
-import httpx
from celery import shared_task
-from django.db import transaction
from django.db.models import Max
from django.utils import timezone
@@ -15,10 +13,6 @@ logger = logging.getLogger(__name__)
IDLE_WORKSPACE = timedelta(days=7)
-class NotPricedError(Exception):
- """The provider has not priced the generation yet."""
-
-
@shared_task(name="overbae.tasks.assistant.run_turn")
def run_turn(thread_id):
# Lazy: the turn reaches the MCP catalog, which imports the serializers that import tasks.
@@ -71,37 +65,6 @@ def remove_workspace(project_id):
workspaces.provider().remove(project_id)
-@shared_task(
- name="overbae.tasks.assistant.charge_generation",
- autoretry_for=(NotPricedError, httpx.HTTPError),
- retry_backoff=30,
- max_retries=12,
-)
-def charge_generation(user_id, project_id, generation):
- """Charge a model call of the assistant whose usage carried no cost, at what the provider
- billed for its generation."""
- from overbae.models import BillingService, Project, User
- from overbae.services import billing_ledger
-
- cost = billing_ledger.generation_cost(generation)
- if cost is None:
- raise NotPricedError(generation)
- with transaction.atomic():
- # The project may be deleted by now; the charge stays its owner's. Its row is held
- # until the charge is written, so a delete waits for it.
- held = (
- Project.objects.select_for_update().filter(pk=project_id).values_list("pk", flat=True)
- )
- billing_ledger.charge_credits(
- User.objects.get(pk=user_id),
- cost,
- BillingService.ASSISTANT,
- project_id=project_id if list(held) else None,
- idempotency_key=f"openrouter:{generation}",
- metadata={"generation": generation},
- )
-
-
@shared_task(name="overbae.tasks.assistant.bill_workspaces")
def bill_workspaces():
"""Charge each project's owner for the workspace compute the provider has measured."""
diff --git a/overbae/tasks/billing.py b/overbae/tasks/billing.py
new file mode 100644
index 00000000..8df62fbe
--- /dev/null
+++ b/overbae/tasks/billing.py
@@ -0,0 +1,48 @@
+import logging
+from decimal import Decimal
+
+import httpx
+from celery import shared_task
+
+logger = logging.getLogger(__name__)
+
+
+class NotPricedError(Exception):
+ """The provider has not priced the generation yet."""
+
+
+@shared_task(bind=True, name="overbae.tasks.billing.price_generation", max_retries=12)
+def price_generation(self, cause, generation, model, cost, usage):
+ """Charge an OpenRouter generation at its cost, looked up once the provider priced it."""
+ # Lazy: services import tasks.
+ from overbae.services import model_meter
+ from overbae.services.billing_ledger import Cause
+
+ try:
+ priced = Decimal(cost) if cost is not None else model_meter.generation_cost(generation)
+ if priced is None:
+ raise NotPricedError(generation)
+ except (NotPricedError, httpx.HTTPError) as exc:
+ if self.request.retries >= self.max_retries:
+ logger.error("OpenRouter generation was never priced: %s", generation)
+ return
+ raise self.retry(exc=exc, countdown=min(30 * 2**self.request.retries, 600)) from exc
+ model_meter.charge_generation(Cause(**cause), generation, priced, model, usage)
+
+
+@shared_task(name="overbae.tasks.billing.collect_container_meters")
+def collect_container_meters():
+ """Charge the Modal containers that did customers' work since the last collection."""
+ # Lazy: services import tasks.
+ from overbae.services import container_meter
+
+ return {"charged": container_meter.collect()}
+
+
+@shared_task(name="overbae.tasks.billing.check_provider_bills")
+def check_provider_bills():
+ """Compare the ledger with what Modal and OpenRouter billed this environment; read-only."""
+ # Lazy: services import tasks.
+ from overbae.services import provider_check
+
+ return {"results": provider_check.check()}
diff --git a/overbae/tasks/finetuning.py b/overbae/tasks/finetuning.py
index 942d7745..5a506f3c 100644
--- a/overbae/tasks/finetuning.py
+++ b/overbae/tasks/finetuning.py
@@ -20,7 +20,6 @@ from modal_shared.decisions import DECISION_OBJECTIVES
from modal_shared.training_telemetry import STARTUP_LABELS
from overbae.models import FinetuningJob
from overbae.services import operational_progress, training_monitoring, training_submission
-from overbae.services.compute_costs import record_training_charge
from overbae.services.finetuning_runner import get_runner
from overbae.services.training_preparation import for_job, preparation_error
from overbae.tasks.training_preparation import inspect_preparation
@@ -180,13 +179,6 @@ def _record_event(job, event_type: str, message: str = "", data: dict | None = N
)
-def _charge_modal_finetuning(job) -> None:
- try:
- record_training_charge(job)
- except Exception: # noqa: BLE001 — billing must not change training outcome
- logger.exception("Failed to charge Modal finetuning job %s", job.pk)
-
-
def _transition(job, status: str, *, message: str = "", error: str = "") -> None:
from overbae.models import FinetuningJob
from overbae.services.finetuning_runner import sanitize_job_error
@@ -214,12 +206,6 @@ def _transition(job, status: str, *, message: str = "", error: str = "") -> None
message=message or f"→ {status}",
data={"status": status, **({"error": error} if error else {})},
)
- if status in {
- FinetuningJob.Status.SUCCEEDED,
- FinetuningJob.Status.FAILED,
- FinetuningJob.Status.CANCELLED,
- }:
- _charge_modal_finetuning(job)
def _remote_id(job) -> str:
@@ -428,7 +414,6 @@ def _finalize_success(job, runner, snap, remote: str) -> dict[str, Any]:
message="Fine-tuning completed — deploying model",
data={"status": FinetuningJob.Status.DEPLOYING},
)
- _charge_modal_finetuning(job)
try:
from overbae.services.finetuning_eval import tick_job_evals
diff --git a/overmind/CHANGELOG.md b/overmind/CHANGELOG.md
index c45a82c9..fb1246cb 100644
--- a/overmind/CHANGELOG.md
+++ b/overmind/CHANGELOG.md
@@ -8,6 +8,9 @@ entries here cover the SDK surface.
### Added
+- `overmind credits balance` prints the account's credit balance, which can be negative, and
+ the credits spent. `overmind credits usage` lists each charge with its cause, quantity times
+ unit price and credits, filtered by `--project-id`, `--experiment` and `--service`.
- `overmind experiment` drives experiments from scripts over the REST API: `list`, `show`,
`create --flow FILE`, `revise`, `plan`, `start`, `status`, `stop` and `message`, with
`--json` on every command. `start --watch` and `status --watch` wait for the run and exit 1 unless it
diff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.py
index 8c513e1d..dbc0c01e 100644
--- a/overmind/overmind/__init__.py
+++ b/overmind/overmind/__init__.py
@@ -9,7 +9,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any
-__version__ = "0.1.135"
+__version__ = "0.1.136"
from .client import Client, ModelDeleted, OvermindInferenceError
diff --git a/overmind/overmind/__main__.py b/overmind/overmind/__main__.py
index f85c41cb..a8d3f04b 100644
--- a/overmind/overmind/__main__.py
+++ b/overmind/overmind/__main__.py
@@ -28,6 +28,7 @@ try:
from overmind.chassis import chassis as chassis_cmd
from overmind.connection_cmd import connection_app
from overmind.connector_cmd import connector_app
+ from overmind.credits_cmd import credits_app
from overmind.dataset_cmd import dataset_app
from overmind.experiment_cmd import experiment_app
from overmind.finetune_cmd import finetune as finetune_cmd
@@ -89,6 +90,7 @@ def common(
app.add_typer(skills_app, name="skills")
app.add_typer(dataset_app, name="dataset")
app.add_typer(experiment_app, name="experiment")
+app.add_typer(credits_app, name="credits")
app.add_typer(connection_app, name="connection")
app.add_typer(connector_app, name="connector")
app.add_typer(model_app, name="model")
diff --git a/overmind/overmind/credits_cmd.py b/overmind/overmind/credits_cmd.py
new file mode 100644
index 00000000..ae2f6a48
--- /dev/null
+++ b/overmind/overmind/credits_cmd.py
@@ -0,0 +1,72 @@
+"""Credit balance and usage, as the Console's billing settings show them. 100 credits = $1."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Annotated
+
+import typer
+
+from overmind.config import DEFAULT_PATH
+from overmind.rest import Api, ApiKey, ApiUrl, AsJson, CommandError, emit, fail
+
+credits_app = typer.Typer(help="Read the account's credit balance and what each charge was for.")
+
+
+@credits_app.command("balance")
+def balance(
+ api_key: ApiKey = "",
+ api_url: ApiUrl = "",
+ path: Annotated[Path, typer.Option("--path")] = DEFAULT_PATH,
+ as_json: AsJson = False,
+) -> None:
+ """The balance, which can be negative, and the credits spent."""
+ try:
+ account = Api(api_key, api_url, path).call("GET", "/api/billing/account/")
+ except (CommandError, ValueError) as exc:
+ fail(exc, as_json)
+ text = f"{account['balance_credits']} credits; {account['spent_credits']} spent"
+ if account.get("background_paused"):
+ text += "\nPaused: credits needed. Scoring, signals and scheduled work resume after a top-up."
+ emit(account, text, as_json)
+
+
+@credits_app.command("usage")
+def usage(
+ project_id: Annotated[str, typer.Option("--project-id", help="Only this project")] = "",
+ experiment: Annotated[str, typer.Option("--experiment", help="Only this experiment")] = "",
+ service: Annotated[str, typer.Option("--service", help="Only this service, such as evaluation")] = "",
+ page: Annotated[int, typer.Option("--page", min=1)] = 1,
+ api_key: ApiKey = "",
+ api_url: ApiUrl = "",
+ path: Annotated[Path, typer.Option("--path")] = DEFAULT_PATH,
+ as_json: AsJson = False,
+) -> None:
+ """Each charge: when, what caused it, quantity times unit price, and credits."""
+ query = {"usage": "true", "page": page, "project": project_id, "experiment": experiment, "service": service}
+ try:
+ rows = Api(api_key, api_url, path).call(
+ "GET", "/api/billing/ledger/", params={key: value for key, value in query.items() if value}
+ )
+ except (CommandError, ValueError) as exc:
+ fail(exc, as_json)
+ lines = [
+ " ".join([
+ row["timestamp"][:19],
+ row["service"],
+ f"{row['cause_kind']} {row['cause_id']}".strip() or "-",
+ _priced(row),
+ f"{row['credits']} credits",
+ ])
+ for row in rows["results"]
+ ]
+ text = "\n".join(lines) or "No charges."
+ if rows.get("next"):
+ text += f"\nMore: run the same command with --page {page + 1}."
+ emit(rows, text, as_json)
+
+
+def _priced(row: dict) -> str:
+ if row.get("quantity") is None or row.get("unit_credits") is None:
+ return row.get("resource") or "-"
+ return f"{row['resource']}: {row['quantity']} {row['unit']} x {row['unit_credits']} credits"
diff --git a/overmind/pyproject.toml b/overmind/pyproject.toml
index 2ff105c6..d006e78c 100644
--- a/overmind/pyproject.toml
+++ b/overmind/pyproject.toml
@@ -46,7 +46,7 @@ license = { text = "MIT" }
name = "overmind"
readme = "README.md"
requires-python = ">=3.10,<4" # todo; remove the upper bound
-version = "0.1.135"
+version = "0.1.136"
[project.urls]
"Agent setup" = "https://console.overmindlab.ai/setup.md"
diff --git a/overmind/skills/overmind-evaluations/SKILL.md b/overmind/skills/overmind-evaluations/SKILL.md
index 36eba788..f0a1de5f 100644
--- a/overmind/skills/overmind-evaluations/SKILL.md
+++ b/overmind/skills/overmind-evaluations/SKILL.md
@@ -167,7 +167,7 @@ eval set (default: the capability's active set) and the proposed `targets`. Read
`ready`, the matrix summary, credit availability and advisory `context_checks` for
candidate models and the judge. Context warnings and unknown limits never change
`ready` or require approval; report them without blocking launch. Present
-`suggestions`, `estimated_cost_usd`, `cost_delta_usd` and `cost_basis` during setup:
+`suggestions`, `estimated_credits`, `credits_delta` and `cost_basis` during setup:
they are full-reserved-output budgets for one dataset pass, not total-run quotes or
quality predictions. Never switch models automatically.
diff --git a/overmind/skills/overmind-experiments/SKILL.md b/overmind/skills/overmind-experiments/SKILL.md
index afd13853..b49bdc64 100644
--- a/overmind/skills/overmind-experiments/SKILL.md
+++ b/overmind/skills/overmind-experiments/SKILL.md
@@ -77,7 +77,7 @@ results as Data Workshop pipelines; the kernel is scratch.
`inspect_experiment`, and write your own with `revise_experiment` and `notes`.
- `configure_experiment_trigger` sends an instruction to that agent every N hours, or when a
capability's failing traces within N hours reach a threshold, up to `max_sends` times, and
- no unattended run past `max_spend_usd` of measured spend; `enabled` false ends one.
+ no unattended run once the experiment's charges reach `max_spend_credits`; `enabled` false ends one.
## From scripts
diff --git a/overmind/skills/overmind-training/SKILL.md b/overmind/skills/overmind-training/SKILL.md
index b1e26cc5..390650bc 100644
--- a/overmind/skills/overmind-training/SKILL.md
+++ b/overmind/skills/overmind-training/SKILL.md
@@ -337,7 +337,7 @@ Pass the same explicit train/validation/evaluation cell IDs and evaluation choic
For a native decision checkpoint, use `schedule_native_evaluation` with separate frozen calibration and final decision cells. This authorizes paid paired unchanged-base/candidate evaluation after verified checkpoint completion. Poll `get_job(kind=native_evaluation)` and follow its links. References stay local; known incompatible inputs remain visible in coverage. Calibration is frozen before final results. Report raw and calibrated metrics, source slices, paired confidence intervals and regressions separately from training loss.
-An unknown native forecast is not a zero-dollar quote. GPU ledger spend excludes unreported preparation, CPU/memory, evaluation and storage. Compare measured work and forecast ranges without describing them as a spending cap. Native checkpoints are probability artifacts and do not enter chat deployment or activation.
+An unknown native forecast is not a zero-dollar quote. A job's charges cover its preparation, base download, training and publication containers (GPU, CPU and memory at Modal's rates), also for failed and cancelled jobs; read them with `get_credit_usage(cause_kind="finetune_job")`. Storage is not charged: Overmind absorbs it. Compare measured work and forecast ranges without describing them as a spending cap. Native checkpoints are probability artifacts and do not enter chat deployment or activation.
## Develop models from data
diff --git a/overmind/skills/overmind/SKILL.md b/overmind/skills/overmind/SKILL.md
index a8ebee2b..8c970a0f 100644
--- a/overmind/skills/overmind/SKILL.md
+++ b/overmind/skills/overmind/SKILL.md
@@ -188,7 +188,7 @@ group's owning skill carries its workflow.
- Recovery: `inspect_jobs`, `inspect_mutation`.
- Observability: `inspect_capability_health`, `query_failures`, `query_traces`, `get_job`.
- Signals: `list_signals`, `set_signal_subscription`.
-- Credits: `get_credit_usage` pages account-owned posted project charges by service and recorded training job; experiment filters cover linked training charges only. Null attribution and unposted charges remain unknown. `get_credit_balance` reports account balance and usage by service, with `since` for task budgets. Read the `credit_reporting` field of `overmind://interface/current` for scope and budget limits.
+- Credits: `get_credit_usage` pages the project's charges by service, cause (such as `eval_run` and its id), experiment and run; the project's owner pays for every charge, at the provider's price. `get_credit_balance` reports account balance, which can be negative, usage by service and `background_paused`, with `since` for task budgets. `overmind credits balance` and `overmind credits usage` read the same from a shell. Read the `credit_reporting` field of `overmind://interface/current` for scope and budget limits.
- Instrumentation: `get_instrumentation_plan`, `verify_instrumentation`.
- Datasets: `list_datasets`, `inspect_dataset`, `query_dataset`,
`start_dataset`, `create_dataset_from_traces`, `create_dataset_from_llm_calls`,
diff --git a/overmind/skills/overmind/references/compare-models.md b/overmind/skills/overmind/references/compare-models.md
index 511b7f8f..0c1a748c 100644
--- a/overmind/skills/overmind/references/compare-models.md
+++ b/overmind/skills/overmind/references/compare-models.md
@@ -23,7 +23,7 @@ agent.
1. **Check readiness and cost.** Call `check_evaluation_readiness` with the
dataset, its cell and these `targets`: one `recorded` target with
`is_baseline: true`, and one `generate` target per candidate with its
- `model_name` and a `label`. Show `ready`, `estimated_cost_usd` and the context
+ `model_name` and a `label`. Show `ready`, `estimated_credits` and the context
warnings. `suggestions` lists models with room for longer rows; offer them, do
not add them yourself. Wait for the user to approve the spend.
1. **Run.** Call `run_evaluation` with the same targets and a stable
diff --git a/overmind/tests/test_credits_cmd.py b/overmind/tests/test_credits_cmd.py
new file mode 100644
index 00000000..b665f96c
--- /dev/null
+++ b/overmind/tests/test_credits_cmd.py
@@ -0,0 +1,72 @@
+from __future__ import annotations
+
+import json
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import pytest
+from typer.testing import CliRunner
+
+from overmind.__main__ import app
+
+pytestmark = pytest.mark.covers("cli-contract")
+
+ROW = {
+ "timestamp": "2026-12-02T10:00:00Z",
+ "service": "evaluation",
+ "cause_kind": "eval_run",
+ "cause_id": "r1",
+ "resource": "openrouter m",
+ "quantity": "1.000000",
+ "unit": "generation",
+ "unit_credits": "0.2",
+ "credits": "-0.2",
+}
+
+
+def api():
+ received: list[str] = []
+ replies = {
+ "/api/billing/account/": {"balance_credits": "-120.00", "spent_credits": "5120.00", "background_paused": True},
+ "/api/billing/ledger/": {"count": 1, "results": [ROW]},
+ }
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ received.append(self.path)
+ data = json.dumps(replies[self.path.split("?")[0]]).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def log_message(self, *args):
+ pass
+
+ httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ threading.Thread(target=httpd.serve_forever, daemon=True).start()
+ yield f"http://127.0.0.1:{httpd.server_address[1]}", received
+ httpd.shutdown()
+
+
+def run(url, *args):
+ return CliRunner().invoke(app, ["credits", *args, "--api-url", url, "--api-key", "k"])
+
+
+def test_balance_shows_a_negative_balance_and_the_pause(api):
+ url, _ = api
+ result = run(url, "balance")
+ assert result.exit_code == 0, result.output
+ assert "-120.00 credits; 5120.00 spent" in result.output
+ assert "Paused: credits needed" in result.output
+
+
+def test_usage_lists_cause_and_unit_price_with_the_filters_sent(api):
+ url, received = api
+ result = run(url, "usage", "--experiment", "e1", "--service", "evaluation")
+ assert result.exit_code == 0, result.output
+ assert "eval_run r1 openrouter m: 1.000000 generation x 0.2 credits -0.2 credits" in result.output
+ (path,) = received
+ assert "experiment=e1" in path and "service=evaluation" in path and "usage=true" in path
diff --git a/overmind/uv.lock b/overmind/uv.lock
index 108a42c3..64a04b4d 100644
--- a/overmind/uv.lock
+++ b/overmind/uv.lock
@@ -923,7 +923,7 @@ wheels = [
[[package]]
name = "overmind"
-version = "0.1.135"
+version = "0.1.136"
source = { editable = "." }
dependencies = [
{ name = "packaging" },
diff --git a/tests/fakes/llm.py b/tests/fakes/llm.py
index 9dffd624..05a353b9 100644
--- a/tests/fakes/llm.py
+++ b/tests/fakes/llm.py
@@ -164,6 +164,8 @@ class FakeLLM:
catalog_reads: list[dict[str, str]] = field(default_factory=list)
# What OpenRouter billed for each generation id; one not listed is not priced yet.
generations: dict[str, float] = field(default_factory=dict)
+ # What OpenRouter billed this key this month (GET /key).
+ key_usage_monthly: float = 0.0
def catalog(self) -> list[dict[str, Any]]:
from overbae.core.model_registry import OPENROUTER_MODEL_SLUGS
@@ -361,6 +363,9 @@ class FakeLLM:
"usage": {"input_tokens": 10, "output_tokens": 1, "cost": self.decision_cost},
}
return 200, {"content-type": "application/json"}, json.dumps(payload).encode()
+ if method == "GET" and url.rstrip("/").endswith("/key"):
+ payload = {"data": {"usage_monthly": self.key_usage_monthly}}
+ return 200, {"content-type": "application/json"}, json.dumps(payload).encode()
if method == "GET" and "/generation?" in url:
generation = parse_qs(urlsplit(url).query).get("id", [""])[0]
if generation not in self.generations:
diff --git a/tests/fakes/modal.py b/tests/fakes/modal.py
index 1e48ba65..59043479 100644
--- a/tests/fakes/modal.py
+++ b/tests/fakes/modal.py
@@ -304,6 +304,8 @@ class FakeModal:
app_logs: list[Any] = field(default_factory=list)
worker_stats: dict[str, Any] | BaseException | None = None
sandboxes: dict[str, FakeSandbox] = field(default_factory=dict)
+ # Items of Workspace.billing.report: cost and environment_name each.
+ billing_items: list[Any] = field(default_factory=list)
# Files of each workspace Volume, by path in the Volume.
volumes: dict[str, dict[str, bytes]] = field(default_factory=dict)
full_regions: set[str] = field(default_factory=set)
@@ -380,13 +382,19 @@ class FakeModal:
@staticmethod
def from_name(name, *, environment_name="", **_):
values = cloud.dictionaries.setdefault((environment_name, name), {})
- return SimpleNamespace(get=_Method(values.get), put=_Method(values.__setitem__))
+ return SimpleNamespace(
+ get=_Method(values.get),
+ put=_Method(values.__setitem__),
+ items=_Method(lambda: list(values.items())),
+ pop=_Method(values.pop),
+ )
class Workspace:
@staticmethod
def from_context():
return SimpleNamespace(
billing=SimpleNamespace(
+ report=_Method(lambda **_: list(cloud.billing_items)),
rates=_Method(
lambda: {
"gpu_hour_cost_h100": 3.95,
@@ -394,7 +402,7 @@ class FakeModal:
"cpu_hour_cost": 0.0473,
"mem_gib_hour_cost": 0.008,
}
- )
+ ),
)
)
diff --git a/tests/test_api_error_disclosure.py b/tests/test_api_error_disclosure.py
index 840afda8..ced28731 100644
--- a/tests/test_api_error_disclosure.py
+++ b/tests/test_api_error_disclosure.py
@@ -24,7 +24,7 @@ PRIVATE_DIAGNOSTIC = "Traceback: /srv/private/worker.py provider_token=do-not-ex
@pytest.fixture
def request_context(db, monkeypatch):
user = User.objects.create_user(email="[email protected]", password="pw", clerk_user_id="errors")
- project = Project.objects.create(name="Errors", slug="errors")
+ project = Project.objects.create(name="Errors", slug="errors", owner=user)
ProjectMembership.objects.create(user=user, project=project)
dataset = Dataset.objects.create(project=project, name="Training", intent="train")
cell = Cell.objects.create(dataset=dataset, position=0, state="ok", fingerprint="fixture")
diff --git a/tests/test_assistant_turn.py b/tests/test_assistant_turn.py
index 240b2a8a..e05e6772 100644
--- a/tests/test_assistant_turn.py
+++ b/tests/test_assistant_turn.py
@@ -1,7 +1,6 @@
import json
import time
from datetime import timedelta
-from decimal import Decimal
import pytest
from conftest import frozen_dataset
@@ -122,37 +121,6 @@ def test_a_members_turn_is_charged_to_the_projects_owner(fake_llm, user, thread)
assert charge.user_id == user.pk == thread.project.owner_id
-def test_a_call_the_provider_did_not_price_is_charged_at_its_generation_cost(
- fake_llm, user, thread, monkeypatch, django_capture_on_commit_callbacks
-):
- later = []
- monkeypatch.setattr(assistant_tasks.charge_generation, "delay", lambda *a: later.append(a))
- fake_llm.stream_rounds([([], "Hello.")], cost=None)
- with django_capture_on_commit_callbacks(execute=True):
- say(thread, user, "Hi.")
- assert not BillingTelemetry.objects.filter(service=BillingService.ASSISTANT).exists()
- ((payer, project, generation),) = later
- with pytest.raises(assistant_tasks.NotPricedError):
- assistant_tasks.charge_generation(payer, project, generation)
- fake_llm.generations[generation] = 0.02
- assistant_tasks.charge_generation(payer, project, generation)
- assistant_tasks.charge_generation(payer, project, generation)
- (charge,) = BillingTelemetry.objects.filter(service=BillingService.ASSISTANT)
- assert charge.amount == Decimal("-0.02") and str(charge.user_id) == payer == str(user.pk)
-
-
-def test_a_generation_of_a_deleted_project_is_still_charged_to_its_owner(fake_llm, user):
- project = make_project(member=user)
- project_id = str(project.pk)
- project.delete()
- fake_llm.generations["gen-gone"] = 0.03
- assistant_tasks.charge_generation(str(user.pk), project_id, "gen-gone")
- (charge,) = BillingTelemetry.objects.filter(service=BillingService.ASSISTANT)
- assert charge.amount == Decimal("-0.03") and charge.project_id is None and charge.user == user
-
-
# The workspace starts in a thread of its own, on its own connection.
@pytest.mark.django_db(transaction=True)
@pytest.mark.covers("workspaces")
diff --git a/tests/test_billing_provider.py b/tests/test_billing_provider.py
index bd957f4b..3aa5106b 100644
--- a/tests/test_billing_provider.py
+++ b/tests/test_billing_provider.py
@@ -5,10 +5,11 @@ from decimal import Decimal
import pytest
from django.contrib.auth import get_user_model
from django.urls import reverse
-from factories import auth_client
+from factories import auth_client, make_project
from overbae.models import BillingService, BillingTelemetry
-from overbae.services.billing_ledger import charge_credits, grant_signup_credits
+from overbae.services import billing_ledger
+from overbae.services.billing_ledger import grant_signup_credits
from overbae.services.billing_provider import get_billing
pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]
@@ -16,6 +17,21 @@ pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]
User = get_user_model()
+def spend(user, usd, key):
+ """A provider cost of the user's own project, as the meters write it."""
+ project = make_project(member=user)
+ found = billing_ledger.cause(project.pk, BillingService.INFERENCE, "api_key", key)
+ return billing_ledger.charge(
+ found,
+ usd,
+ key=key,
+ resource="openrouter m",
+ quantity=Decimal(1),
+ unit="generation",
+ unit_usd=usd,
+ )
+
+
def _make_user(slug: str) -> User:
return User.objects.create_user(
email=f"{slug}@example.com",
@@ -39,12 +55,7 @@ def test_uncapped_skips_signup_grant(uncapped):
def test_uncapped_me_and_spend_routes(uncapped):
user = _make_user("uncapped-api")
- charge_credits(
- user,
- Decimal("2"),
- BillingService.INFERENCE,
- idempotency_key="inf-api",
- )
+ spend(user, Decimal("2"), "inf-api")
client = auth_client(user)
me = client.get(reverse("user-me"))
diff --git a/tests/test_completions_api.py b/tests/test_completions_api.py
index 4e4e1dab..328bab80 100644
--- a/tests/test_completions_api.py
+++ b/tests/test_completions_api.py
@@ -12,7 +12,7 @@ from rest_framework import status
from rest_framework.test import APIClient
from rest_framework_simplejwt.tokens import RefreshToken
-from overbae.models import InferenceCall, Project, ProjectMembership, User
+from overbae.models import BillingTelemetry, InferenceCall, Project, ProjectMembership, User
from overbae.models.inference import DeployedModel
from overbae.services.inference_client import InferenceClientError
@@ -39,6 +39,9 @@ def _project() -> Project:
def _membership(user: User, project: Project) -> None:
ProjectMembership.objects.create(user=user, project=project)
+ # Its first member created it, and pays for its work.
+ if project.owner_id is None:
+ Project.objects.filter(pk=project.pk).update(owner=user)
def _deployed_model(
@@ -469,37 +472,37 @@ class TestChatCompletionsEndpoint:
assert r.status_code == status.HTTP_200_OK
assert mock_post.call_args.kwargs["json"]["response_format"] == {"type": "json_object"}
- @pytest.mark.parametrize(
- ("usage", "estimated", "expected_amount"),
- [
- # OpenRouter's own cost wins, so the catalog estimate is never reached.
- ({"prompt_tokens": 10, "completion_tokens": 5, "cost": 1.23e-4}, None, "0.000123"),
- ({"prompt_tokens": 10, "completion_tokens": 5}, 0.0005, "0.0005"),
- # No known price is an honest absence, never a fabricated zero.
- ({"prompt_tokens": 10, "completion_tokens": 5}, None, None),
- ],
- )
- def test_charge_frontier_usage_pricing(self, usage, estimated, expected_amount):
- from overbae.api.completions import _charge_frontier_usage
- from overbae.models import BillingService
-
- captured: dict = {}
- with (
- patch("overbae.api.completions.estimate_cost", return_value=estimated),
- patch(
- "overbae.api.completions.charge_credits",
- lambda user, amount, service, **kwargs: captured.update(
- {"amount": amount, "service": service}
- ),
- ),
- ):
- _charge_frontier_usage(_user(), "mistralai/mistral-large", usage)
+ @override_settings(OPENROUTER_API_KEY="or-test", OPENROUTER_PROXY_ENABLED=True)
+ def test_a_frontier_call_is_charged_to_the_project_at_the_provider_cost(self, fake_llm):
+ u, p = _user(), _project()
+ _membership(u, p)
+ fake_llm.on(lambda r: True, {"content": "Hi", "usage": {"cost": 1.23e-4}})
+ r = _jwt_client(u).post(
+ self.URL,
+ {"model": "anthropic/claude-sonnet-5", "messages": self.MESSAGES},
+ format="json",
+ )
+ assert r.status_code == status.HTTP_200_OK
+ assert fake_llm.requests[-1].body["usage"] == {"include": True}
+ (row,) = BillingTelemetry.objects.filter(amount__lt=0)
+ assert (row.project_id, row.user_id, row.actor_id) == (p.pk, u.pk, u.pk)
+ assert (row.amount, row.idempotency_key) == (
+ Decimal("-0.000123"),
+ f"openrouter:{r.json()['id']}",
+ )
- if expected_amount is None:
- assert captured == {}
- else:
- assert captured["amount"] == Decimal(expected_amount)
- assert captured["service"] == BillingService.INFERENCE
+ @override_settings(OPENROUTER_API_KEY="or-test", OPENROUTER_PROXY_ENABLED=True)
+ def test_a_frontier_call_names_the_project_it_charges(self):
+ u = _user()
+ for project in (_project(), _project()):
+ _membership(u, project)
+ r = _jwt_client(u).post(
+ self.URL,
+ {"model": "anthropic/claude-sonnet-5", "messages": self.MESSAGES},
+ format="json",
+ )
+ assert r.status_code == status.HTTP_400_BAD_REQUEST
+ assert "X-Overmind-Project" in r.json()["error"]["message"]
def test_non_ready_model_returns_503(self):
u, p = _user(), _project()
diff --git a/tests/test_container_meter.py b/tests/test_container_meter.py
new file mode 100644
index 00000000..e940bc11
--- /dev/null
+++ b/tests/test_container_meter.py
@@ -0,0 +1,147 @@
+import time
+from decimal import Decimal
+
+import pytest
+from conftest import TRAIN_ROWS, frozen_dataset
+from factories import make_project, make_user
+
+from modal_shared.container_meter import STORE
+from overbae.models import BillingTelemetry, DeployedModel, FinetuningJob, MeteredContainer
+from overbae.services import container_meter
+
+pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]
+
+# FakeModal's rates: H100 3.95/h, CPU 0.0473 per core-hour, memory 0.008 per GiB-hour.
+H100, CPU, MEMORY = Decimal("3.95") / 3600, Decimal("0.0473") / 3600, Decimal("0.008") / 3600
+
+
+def report(container, wall, refs, *, gpu_count=1, stopped=False, last_ref=None, default_ref=None):
+ started = time.time() - wall
+ return {
+ "container": container,
+ "function": "H100_vllm_lora",
+ "gpu": "H100",
+ "gpu_count": gpu_count,
+ "cpu": 8,
+ "memory_gib": 64,
+ "started_at": started,
+ "seen_at": started + wall,
+ "wall_seconds": wall,
+ "cpu_core_seconds": 8 * wall,
+ "memory_gib_seconds": 64 * wall,
+ "usage_measured": True,
+ "refs": refs,
+ "last_ref": last_ref,
+ "default_ref": default_ref,
+ "stopped": stopped,
+ }
+
+
+def cost(wall, gpu_count=1):
+ return Decimal(wall) * (gpu_count * H100 + 8 * CPU + 64 * MEMORY)
+
+
+def reports(fake_modal):
+ return fake_modal.dictionaries.setdefault(("", STORE), {})
+
+
+def spent(project):
+ rows = BillingTelemetry.objects.filter(project=project)
+ return -sum((row.amount for row in rows), Decimal(0))
+
+
+def test_a_shared_container_divides_its_time_by_requests_and_idle_goes_to_the_last(fake_modal):
+ a, b = make_project(member=make_user()), make_project(member=make_user())
+ DeployedModel.objects.create(project=a, model_id="ft-a")
+ DeployedModel.objects.create(project=b, model_id="ft-b")
+ # B served more, A last: the idle minute after is A's.
+ refs, last = {"served_model:ft-a": 30, "served_model:ft-b": 90}, "served_model:ft-a"
+ reports(fake_modal)["ta-1"] = report("ta-1", 60, refs, last_ref=last)
+ container_meter.collect()
+ reports(fake_modal)["ta-1"] = report("ta-1", 120, refs, last_ref=last)
+ container_meter.collect()
+
+ assert spent(a) == pytest.approx(cost(60) / 4 + cost(60), abs=Decimal("1e-6"))
+ assert spent(b) == pytest.approx(cost(60) * 3 / 4, abs=Decimal("1e-6"))
+ row = BillingTelemetry.objects.get(project=a)
+ assert (row.user_id, row.cause_kind, row.unit, row.quantity) == (
+ a.owner_id,
+ "deployed_model",
+ "second",
+ Decimal(75),
+ )
+ assert row.provider_ref == "ta-1" and row.resource.startswith("modal H100 x1")
+
+
+def test_a_cancelled_training_container_is_charged_to_the_owner_for_what_ran(fake_modal):
+ owner, starter = make_user(), make_user()
+ project = make_project(member=owner)
+ job = FinetuningJob.objects.create(
+ project=project,
+ dataset=frozen_dataset(project, TRAIN_ROWS, name="chat", contract="train"),
+ base_model="Qwen/Qwen3-8B",
+ status=FinetuningJob.Status.CANCELLED,
+ triggered_by=starter,
+ )
+ ref = f"finetune_job:{job.pk}"
+ reports(fake_modal)["tr-1"] = report("tr-1", 300, {ref: 290}, gpu_count=2, stopped=True)
+ container_meter.collect()
+
+ (row,) = BillingTelemetry.objects.filter(project=project)
+ assert (row.user_id, row.actor_id, row.cause_id) == (owner.pk, starter.pk, str(job.pk))
+ assert -row.amount == pytest.approx(cost(300, gpu_count=2), abs=Decimal("1e-6"))
+ job.refresh_from_db()
+ assert job.cost_usd == pytest.approx(-row.amount, abs=Decimal("1e-4"))
+ assert MeteredContainer.objects.get(pk="tr-1").finished
+ assert "tr-1" not in reports(fake_modal)
+
+
+def test_container_time_no_record_explains_is_named_and_charged_to_no_one(fake_modal, caplog):
+ reports(fake_modal)["tu-1"] = report("tu-1", 60, {"served_model:gone": 60}, stopped=True)
+ container_meter.collect()
+ assert not BillingTelemetry.objects.exists()
+ assert "unknown billing ref is absorbed" in caplog.text
+ assert "tu-1" not in reports(fake_modal)
+
+
+def test_a_shared_preparation_is_charged_to_the_first_job_that_used_it(fake_modal):
+ from datetime import timedelta
+
+ from django.utils import timezone
+
+ from overbae.models import TrainingPreparation
+
+ owner = make_user()
+ project = make_project(member=owner)
+ cell = frozen_dataset(project, TRAIN_ROWS, name="chat", contract="train").active_cell
+ preparation = TrainingPreparation.objects.create(
+ cell=cell, signature="s" * 64, deadline=timezone.now() + timedelta(hours=1)
+ )
+ ref = f"training_preparation:{preparation.pk}"
+ reports(fake_modal)["tp-1"] = report("tp-1", 60, {ref: 60})
+ container_meter.collect()
+ (alone,) = BillingTelemetry.objects.filter(project=project)
+ assert (alone.cause_kind, alone.user_id) == ("training_preparation", owner.pk)
+
+ job = FinetuningJob.objects.create(
+ project=project, dataset=cell.dataset, base_model="Qwen/Qwen3-8B", preparation=preparation
+ )
+ reports(fake_modal)["tp-1"] = report("tp-1", 120, {ref: 120})
+ container_meter.collect()
+ used = BillingTelemetry.objects.get(project=project, cause_kind="finetune_job")
+ assert used.cause_id == str(job.pk)
+
+
+def test_a_container_that_reports_again_after_a_gap_is_charged_for_the_gap(fake_modal):
+ project = make_project(member=make_user())
+ DeployedModel.objects.create(project=project, model_id="ft-gap")
+ ref = "served_model:ft-gap"
+ silent = report("tg-1", 60, {ref: 60}, last_ref=ref)
+ silent["seen_at"] -= 600
+ reports(fake_modal)["tg-1"] = silent
+ container_meter.collect()
+ assert "tg-1" not in reports(fake_modal)
+
+ reports(fake_modal)["tg-1"] = report("tg-1", 720, {ref: 60}, last_ref=ref)
+ container_meter.collect()
+ assert spent(project) == pytest.approx(cost(720), abs=Decimal("1e-6"))
diff --git a/tests/test_credit_grants.py b/tests/test_credit_grants.py
index e14bcdd2..e7c0f6d1 100644
--- a/tests/test_credit_grants.py
+++ b/tests/test_credit_grants.py
@@ -8,12 +8,10 @@ from django.urls import reverse
from factories import auth_client, make_project, make_user
from overbae.models import BillingService, BillingTelemetry
+from overbae.services import billing_ledger
from overbae.services.billing_ledger import (
SIGNUP_CREDITS_USD,
- InsufficientCredits,
balance_usd,
- charge_credits,
- ensure_credits,
grant_signup_credits,
granted_usd,
)
@@ -23,6 +21,21 @@ pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]
User = get_user_model()
+def spend(user, usd, key):
+ """A provider cost of the user's own project, as the meters write it."""
+ project = make_project(member=user)
+ found = billing_ledger.cause(project.pk, BillingService.INFERENCE, "api_key", key)
+ return billing_ledger.charge(
+ found,
+ usd,
+ key=key,
+ resource="openrouter m",
+ quantity=Decimal(1),
+ unit="generation",
+ unit_usd=usd,
+ )
+
+
def test_signup_grants_exactly_50_credits_once():
user = User.objects.create_user(
@@ -39,7 +52,7 @@ def test_signup_grants_exactly_50_credits_once():
assert balance_usd(user) == SIGNUP_CREDITS_USD
-def test_charge_credits_reduces_balance_and_entry_gate():
+def test_charges_reduce_the_balance_below_zero_and_close_the_start_gate():
user = User.objects.create_user(
password="x",
@@ -47,32 +60,16 @@ def test_charge_credits_reduces_balance_and_entry_gate():
)
assert balance_usd(user) == SIGNUP_CREDITS_USD
- charge_credits(
- user,
- Decimal("3.5"),
- BillingService.INFERENCE,
- idempotency_key="inf-1",
- )
+ spend(user, Decimal("3.5"), "inf-1")
assert balance_usd(user) == Decimal("46.5")
- charge_credits(
- user,
- Decimal("46.5"),
- BillingService.INFERENCE,
- idempotency_key="inf-2",
- )
+ spend(user, Decimal("46.5"), "inf-2")
assert balance_usd(user) == Decimal("0")
- with pytest.raises(InsufficientCredits):
- ensure_credits(user)
+ assert not billing_ledger.can_spend(user.owned_projects.first().pk)
# Post-hoc debit still records full amount (ledger truth).
- charge_credits(
- user,
- Decimal("1"),
- BillingService.INFERENCE,
- idempotency_key="inf-3",
- )
+ spend(user, Decimal("1"), "inf-3")
assert balance_usd(user) == Decimal("-1")
# Usage never shrinks the granted total (progress-bar denominator).
assert granted_usd(user) == SIGNUP_CREDITS_USD
@@ -89,19 +86,9 @@ def test_ledger_lists_own_entries_newest_first():
password="x",
clerk_user_id="clerk_ledger_other",
)
- charge_credits(
- user,
- Decimal("1.25"),
- BillingService.INFERENCE,
- idempotency_key="ledger-inf-1",
- )
+ spend(user, Decimal("1.25"), "ledger-inf-1")
# Other user's row must not appear.
- charge_credits(
- other,
- Decimal("9"),
- BillingService.INFERENCE,
- idempotency_key="ledger-inf-other",
- )
+ spend(other, Decimal("9"), "ledger-inf-other")
r = auth_client(user).get(reverse("billing-ledger"))
assert r.status_code == 200
diff --git a/tests/test_data_first_workflow.py b/tests/test_data_first_workflow.py
index 57968441..ba2df0bc 100644
--- a/tests/test_data_first_workflow.py
+++ b/tests/test_data_first_workflow.py
@@ -26,8 +26,8 @@ pytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]
def workspace():
- project = Project.objects.create(name="Data-first", slug="data-first")
user = User.objects.create_user(email="[email protected]", password="fixture")
+ project = Project.objects.create(name="Data-first", slug="data-first", owner=user)
ProjectMembership.objects.create(project=project, user=user)
client = APIClient()
client.force_authenticate(user)
diff --git a/tests/test_dedicated_deployment.py b/tests/test_dedicated_deployment.py
index 0e773935..6012a09c 100644
--- a/tests/test_dedicated_deployment.py
+++ b/tests/test_dedicated_deployment.py
@@ -3,8 +3,9 @@
from __future__ import annotations
import json
+import time
import uuid
-from datetime import timedelta
+from decimal import Decimal
import pytest
from conftest import drain_stream
@@ -12,11 +13,12 @@ from django.utils import timezone
from rest_framework.test import APIClient
from rest_framework_simplejwt.tokens import RefreshToken
+from modal_shared.container_meter import STORE
from overbae.core.errors import InputValidationError
from overbae.models import BillingTelemetry, DedicatedDeployment, InferenceCall, Project, User
from overbae.models.billing import BillingService
from overbae.models.inference import DeployedModel
-from overbae.services import dedicated, inference_requests
+from overbae.services import container_meter, dedicated, inference_requests
from overbae.services.provider_pricing import refresh_rates
from tests.fakes.modal import open_chat_tunnel
@@ -59,7 +61,7 @@ def _ok(**_kwargs):
def test_missing_rate_refuses_start_and_a_second_start_conflicts(fake_modal):
refresh_rates()
user = _user()
- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
+ project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
deployed = _ready(project)
with pytest.raises(InputValidationError, match="price is unavailable"):
dedicated.start(deployed, user, gpu_type="L4")
@@ -73,7 +75,7 @@ def test_missing_rate_refuses_start_and_a_second_start_conflicts(fake_modal):
def test_stopped_deployment_can_restart_with_its_saved_configuration(fake_modal):
refresh_rates()
user = _user()
- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
+ project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
deployed = _ready(project)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
row = dedicated.start(
@@ -110,10 +112,10 @@ def test_stopped_deployment_can_restart_with_its_saved_configuration(fake_modal)
@pytest.mark.covers("ledger")
-def test_running_replicas_are_metered_and_idle_replicas_are_not(fake_modal):
+def test_the_containers_meter_dedicated_time_and_the_deployment_shows_it(fake_modal):
refresh_rates()
user = _user()
- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
+ project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
deployed = _ready(project)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
fake_modal.worker_stats = {"num_total_runners": 2, "backlog": 0, "num_running_inputs": 0}
@@ -122,32 +124,39 @@ def test_running_replicas_are_metered_and_idle_replicas_are_not(fake_modal):
dedicated.advance(str(row.id))
row.refresh_from_db()
assert row.status == DedicatedDeployment.Status.ONLINE
- DedicatedDeployment.objects.filter(pk=row.pk).update(
- last_billed_at=timezone.now() - timedelta(minutes=2)
- )
- dedicated.advance(str(row.id))
- charges = BillingTelemetry.objects.filter(service=BillingService.DEDICATED_INFERENCE)
- assert charges.count() == 1
- assert charges.get().amount < 0
- row.refresh_from_db()
- assert row.accrued_credits > 0
- assert row.running_replicas == 2
-
- fake_modal.worker_stats = {"num_total_runners": 0, "backlog": 0, "num_running_inputs": 0}
- DedicatedDeployment.objects.filter(pk=row.pk).update(
- last_billed_at=timezone.now() - timedelta(minutes=3),
- next_poll_at=timezone.now(),
- )
+ assert not BillingTelemetry.objects.filter(service=BillingService.DEDICATED_INFERENCE).exists()
+
+ now = time.time()
+ fake_modal.dictionaries.setdefault(("", STORE), {})["td-1"] = {
+ "container": "td-1",
+ "function": "H100_vllm_dedicated",
+ "gpu": "H100",
+ "gpu_count": 1,
+ "cpu": 8,
+ "memory_gib": 64,
+ "started_at": now - 120,
+ "seen_at": now,
+ "wall_seconds": 120,
+ "cpu_core_seconds": 960,
+ "memory_gib_seconds": 7680,
+ "refs": {},
+ "last_ref": f"served_model:{row.served_model_id}",
+ "default_ref": f"served_model:{row.served_model_id}",
+ "stopped": False,
+ }
+ container_meter.collect()
+ (charge,) = BillingTelemetry.objects.filter(service=BillingService.DEDICATED_INFERENCE)
+ assert (charge.user_id, charge.actor_id, charge.quantity) == (user.pk, user.pk, 120)
+ DedicatedDeployment.objects.filter(pk=row.pk).update(next_poll_at=timezone.now())
dedicated.advance(str(row.id))
- assert BillingTelemetry.objects.filter(service=BillingService.DEDICATED_INFERENCE).count() == 1
row.refresh_from_db()
- assert row.running_replicas == 0
+ assert row.accrued_credits == (-charge.amount * 100).quantize(Decimal("0.01"))
def test_gpu_change_scales_the_previous_gpu_to_zero(fake_modal):
refresh_rates()
user = _user()
- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
+ project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
deployed = _ready(project)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
row = dedicated.start(deployed, user, gpu_type="H100", min_replicas=1, max_replicas=1)
@@ -171,7 +180,7 @@ def test_gpu_change_scales_the_previous_gpu_to_zero(fake_modal):
def test_dedicated_chat_skips_per_request_billing_and_appears_in_the_model_list(fake_modal):
refresh_rates()
user = _user()
- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
+ project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
from overbae.models import ProjectMembership
ProjectMembership.objects.create(user=user, project=project)
@@ -212,7 +221,7 @@ def test_dedicated_chat_skips_per_request_billing_and_appears_in_the_model_list(
def test_dedicated_chat_streams_tokens_before_the_reply_finishes(fake_modal):
refresh_rates()
user = _user()
- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
+ project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
from overbae.models import ProjectMembership
ProjectMembership.objects.create(user=user, project=project)
@@ -276,7 +285,7 @@ def test_dedicated_list_returns_the_latest_row_for_each_model():
from overbae.models import ProjectMembership
user = _user()
- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
+ project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
ProjectMembership.objects.create(user=user, project=project)
other = Project.objects.create(name="Other", slug=f"p-{uuid.uuid4().hex[:8]}")
first = _ready(project)
@@ -314,7 +323,7 @@ def test_dedicated_list_returns_the_latest_row_for_each_model():
def test_failed_warmup_releases_the_remote_floor_before_becoming_terminal(fake_modal):
refresh_rates()
user = _user()
- project = Project.objects.create(name="Failure cleanup")
+ project = Project.objects.create(owner=user, name="Failure cleanup")
deployed = _ready(project)
fake_modal.deploy(
"overmind-dedicated", "H100_vllm_dedicated.infer", lambda **kwargs: {"status": 503}
@@ -345,7 +354,7 @@ def test_failed_warmup_releases_the_remote_floor_before_becoming_terminal(fake_m
@pytest.mark.covers("work-once")
def test_a_dedicated_request_is_read_back_from_its_saved_call(fake_modal):
user = _user()
- project = Project.objects.create(name="Dedicated request")
+ project = Project.objects.create(owner=user, name="Dedicated request")
model = _ready(project)
refresh_rates()
row = dedicated.start(model, user, gpu_type="H100")
@@ -372,7 +381,7 @@ def test_a_dedicated_request_is_read_back_from_its_saved_call(fake_modal):
@pytest.mark.covers("work-once")
def test_dedicated_unknown_acknowledgement_is_never_replayed(fake_modal):
user = _user()
- project = Project.objects.create(name="Unknown dedicated acknowledgement")
+ project = Project.objects.create(owner=user, name="Unknown dedicated acknowledgement")
model = _ready(project)
refresh_rates()
row = dedicated.start(model, user, gpu_type="H100")
@@ -400,7 +409,7 @@ def test_deleting_a_model_shuts_its_dedicated_pool_down(fake_modal, scripted):
scripted("http://inference.test").reply(200, json_body={})
refresh_rates()
user = _user()
- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
+ project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
ProjectMembership.objects.create(user=user, project=project)
deployed = _ready(project)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
diff --git a/tests/test_dedicated_usage.py b/tests/test_dedicated_usage.py
index e99dd2f1..681e5c05 100644
--- a/tests/test_dedicated_usage.py
+++ b/tests/test_dedicated_usage.py
@@ -2,6 +2,7 @@ import uuid
from datetime import timedelta
import pytest
+import time_machine
from django.utils import timezone
from overbae.models import BillingTelemetry, DedicatedDeployment, DeployedModel, Project, User
@@ -24,22 +25,61 @@ def test_dedicated_usage_is_model_scoped_and_preserves_missing_measurements():
)
assert dedicated_usage(model, "24h")["credits"] is None
- def charge(key, metadata):
+ def charge(deployment, metadata):
return BillingTelemetry.objects.create(
user=user,
project=project,
service="dedicated-inference",
amount=-2,
- idempotency_key=key,
+ cause_kind="dedicated_deployment",
+ cause_id=str(deployment),
metadata=metadata,
)
- charge(f"dedicated:{row.id}:one", {"minutes": 30, "replicas": 2, "gpu_type": "H100"})
- charge(f"dedicated:{uuid.uuid4()}:other", {"minutes": 30, "replicas": 2, "gpu_type": "H100"})
- old = charge(f"dedicated:{row.id}:old", {})
+ charge(row.id, {"gpu_seconds": 3600})
+ charge(uuid.uuid4(), {"gpu_seconds": 3600})
+ # A row from before containers reported their GPU seconds.
+ old = charge(row.id, {})
BillingTelemetry.objects.filter(pk=old.pk).update(timestamp=timezone.now() - timedelta(days=2))
result = dedicated_usage(model, "24h")
assert result["credits"] == 200
assert result["gpu_hours"] == 1
assert sum(p["credits"] for p in result["points"]) == 200
assert dedicated_usage(model, "all")["gpu_hours"] is None
+
+
+def test_model_cost_counts_shared_and_dedicated_time_inside_the_period():
+ from overbae.services.inference_metrics import model_metrics
+
+ project = Project.objects.create(name="Window", slug="window")
+ user = User.objects.create_user(email="[email protected]", password="test")
+ model = DeployedModel.objects.create(project=project, model_id="window-model")
+ row = DedicatedDeployment.objects.create(
+ project=project,
+ deployed_model=model,
+ gpu_type="H100",
+ rate_usd_per_gpu_hour=4,
+ credits_per_gpu_hour=400,
+ )
+ now = timezone.now()
+ for kind, cause, started in [
+ ("deployed_model", model.pk, now - timedelta(hours=48)),
+ ("dedicated_deployment", row.pk, now - timedelta(hours=12)),
+ ]:
+ BillingTelemetry.objects.create(
+ user=user,
+ project=project,
+ service="inference-ft-model",
+ amount=-4,
+ cause_kind=kind,
+ cause_id=str(cause),
+ started_at=started,
+ ended_at=now,
+ )
+ # Half the shared row ran inside the last day, all of the dedicated one.
+ with time_machine.travel(now, tick=False):
+ assert model_metrics(model, period="24h")["cost"] == pytest.approx(6)
+ assert model_metrics(model, period="all")["cost"] == pytest.approx(8)
+ application = model_metrics(model, period="24h", source="application")
+ assert application["cost"] is None and application["cost_this_month"] is None
diff --git a/tests/test_eval_context_suggestions.py b/tests/test_eval_context_suggestions.py
index 9e3d196e..f810d003 100644
--- a/tests/test_eval_context_suggestions.py
+++ b/tests/test_eval_context_suggestions.py
@@ -44,11 +44,11 @@ def check(**kwargs):
def test_cost_projection_uses_all_inputs_and_reserved_output_without_price_ranking(catalog):
result = suggestions.suggest_models(check(), inputs=[100, 300], uses_tools=False)
- assert result["estimated_cost_usd"] == pytest.approx(0.0408)
+ assert result["estimated_credits"] == pytest.approx(4.08)
assert [row["model"] for row in result["suggestions"]] == ["preferred", "cheaper"]
- assert result["suggestions"][0]["estimated_cost_usd"] == pytest.approx(0.0816)
- assert result["suggestions"][0]["cost_delta_usd"] == pytest.approx(0.0408)
- assert result["suggestions"][1]["cost_delta_usd"] == pytest.approx(-0.0204)
+ assert result["suggestions"][0]["estimated_credits"] == pytest.approx(8.16)
+ assert result["suggestions"][0]["credits_delta"] == pytest.approx(4.08)
+ assert result["suggestions"][1]["credits_delta"] == pytest.approx(-2.04)
assert "same judge" in result["suggestion_note"]
@@ -84,15 +84,15 @@ def test_requires_judge_schema_and_generation_tool_support(catalog):
def test_unknown_or_invalid_rates_are_not_zero_cost(catalog, price):
catalog[0]["completion_price"] = price
result = suggestions.suggest_models(check(), inputs=[500], uses_tools=False)
- assert result["estimated_cost_usd"] is None
- assert result["suggestions"][0]["cost_delta_usd"] is None
+ assert result["estimated_credits"] is None
+ assert result["suggestions"][0]["credits_delta"] is None
def test_zero_price_is_known_and_custom_endpoint_has_no_borrowed_catalog_price(catalog):
catalog[1]["prompt_price"] = catalog[1]["completion_price"] = 0
result = suggestions.suggest_models(check(), inputs=[500], uses_tools=False, custom=True)
- assert result["estimated_cost_usd"] is None
- assert result["suggestions"][0]["estimated_cost_usd"] == 0
+ assert result["estimated_credits"] is None
+ assert result["suggestions"][0]["estimated_credits"] == 0
def test_excludes_family_under_test(catalog):
@@ -112,7 +112,7 @@ def test_fitting_models_have_prices_but_do_not_suggest_or_change_selection(catal
original = check(status="fits")
result = suggestions.suggest_models(original, inputs=[100], uses_tools=False)
assert result["suggestions"] == []
- assert result["estimated_cost_usd"] is not None
+ assert result["estimated_credits"] is not None
assert original == check(status="fits")
@@ -124,14 +124,14 @@ def test_dropdown_checks_every_judge_and_keeps_unsafe_options(catalog):
"estimated_input_tokens": size,
"total_input_tokens": size * 2,
"checked_rows": 2,
- "estimated_cost_usd": 0.1,
+ "estimated_credits": 10,
}
for size in (100, 1000)
]
options = suggestions.judge_model_options(checks)
assert [option["status"] for option in options] == ["warning", "fits"]
- assert options[1]["estimated_cost_usd"] == pytest.approx(0.0422)
- assert options[1]["cost_delta_usd"] == pytest.approx(-0.1578)
+ assert options[1]["estimated_credits"] == pytest.approx(4.22)
+ assert options[1]["credits_delta"] == pytest.approx(-15.78)
def test_dropdown_missing_schema_or_limits_is_unverified(catalog):
@@ -151,8 +151,8 @@ def test_dropdown_same_judge_has_no_rounding_price_change(catalog):
"estimated_input_tokens": 123,
"total_input_tokens": 123,
"checked_rows": 1,
- "estimated_cost_usd": suggestions.token_cost(catalog[1], 123, 5000),
+ "estimated_credits": suggestions.token_cost(catalog[1], 123, 5000),
}
for _ in range(11)
]
- assert suggestions.judge_model_options(checks)[0]["cost_delta_usd"] == 0
+ assert suggestions.judge_model_options(checks)[0]["credits_delta"] == 0
diff --git a/tests/test_experiments.py b/tests/test_experiments.py
index e70df84d..168dc8ae 100644
--- a/tests/test_experiments.py
+++ b/tests/test_experiments.py
@@ -1143,7 +1143,7 @@ def test_notes_are_written_with_a_save_and_read_back_with_the_spend(setup):
assert not noted.isError, noted.structuredContent
read = call_tool("inspect_experiment", {"experiment": str(experiment.pk)}, context)
assert read.structuredContent["notes"] == "Plan: check rows."
- assert read.structuredContent["spend"] == {"measured_usd": 0.0, "unknown": []}
+ assert read.structuredContent["spend"] == {"spent_credits": 0.0, "not_attributed": []}
from overbae.services.experiments import describe
experiment.refresh_from_db()
@@ -1250,7 +1250,8 @@ def test_a_coding_agent_has_its_own_kernel_that_a_delete_forgets(setup, monkeypa
def test_unattended_runs_stop_at_a_triggers_spend_cap_and_a_person_starts_them_again(setup):
from decimal import Decimal
- from overbae.services.assistant import log, threads
+ from overbae.models import BillingTelemetry
+ from overbae.services.assistant import threads
context, cell = setup
experiment = records.create(context.project, context.user, document=flow(cell.pk))
@@ -1261,14 +1262,20 @@ def test_unattended_runs_stop_at_a_triggers_spend_cap_and_a_person_starts_them_a
instruction="Improve it.",
hours=24,
max_sends=4,
- max_spend_usd=Decimal("0.30"),
+ max_spend_credits=Decimal("30"),
)
thread = experiment.assistant_thread
- # Exactly the cap: 0.3 as a float is below Decimal("0.30"), and must not slip under it.
- log.append(thread, "assistant", {"text": "", "calls": [], "usage": {"response_cost": 0.3}})
+ # Exactly the cap, charged to the experiment on the ledger.
+ BillingTelemetry.objects.create(
+ user=context.user,
+ project=context.project,
+ experiment=experiment,
+ amount="-0.30",
+ service="assistant",
+ )
notice = {"request_key": "t", "text": "Improve it.", "origin": AssistantInput.Origin.TRIGGER}
threads.send(thread, context.user, **notice)
- with pytest.raises(InputValidationError, match="spend cap of \\$0.30"):
+ with pytest.raises(InputValidationError, match="spend cap of 30"):
runs.start(experiment, context.user, origin=ExperimentRun.Origin.ASSISTANT)
# Past its cap the trigger sends nothing: a send starts paid agent turns.
ExperimentTrigger.objects.filter(experiment=experiment).update(next_at=timezone.now())
diff --git a/tests/test_finetuning.py b/tests/test_finetuning.py
index 46d5b579..cd8545e4 100644
--- a/tests/test_finetuning.py
+++ b/tests/test_finetuning.py
@@ -61,7 +61,7 @@ def _job_payload(*, project_id: str, dataset_id: str, **overrides) -> dict:
def _setup_project_with_dataset() -> tuple[User, Project, Capability, Dataset]:
u = make_user(f"u-{uuid.uuid4().hex[:6]}@example.com")
- p = make_project()
+ p = make_project(owner=u)
ProjectMembership.objects.create(user=u, project=p)
a = make_capability(p)
ds = _dataset(a)
diff --git a/tests/test_finetuning_context_reco.py b/tests/test_finetuning_context_reco.py
index 43965b6f..2bccd851 100644
--- a/tests/test_finetuning_context_reco.py
+++ b/tests/test_finetuning_context_reco.py
@@ -33,7 +33,7 @@ CELERY_PATH = "overbae.tasks.finetuning.run_finetuning.apply_async"
def _setup() -> tuple[User, Project, Capability]:
u = make_user()
- p = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
+ p = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}", owner=u)
ProjectMembership.objects.create(user=u, project=p)
slug = f"a-{uuid.uuid4().hex[:8]}"
a = Capability.objects.create(project=p, name=slug, slug=slug)
diff --git a/tests/test_finetuning_monitor.py b/tests/test_finetuning_monitor.py
index 9a4df23b..b454208e 100644
--- a/tests/test_finetuning_monitor.py
+++ b/tests/test_finetuning_monitor.py
@@ -104,7 +104,6 @@ def test_provider_observation_retains_preparation_and_recovery_evidence(state):
with (
patch("overbae.services.finetuning_runner.get_runner", return_value=runner),
patch("overbae.services.finetuning_eval.tick_job_evals"),
- patch("overbae.tasks.finetuning._charge_modal_finetuning"),
):
observe_finetuning_job(job)
job.refresh_from_db()
diff --git a/tests/test_finetuning_new.py b/tests/test_finetuning_new.py
index 495a6ffc..c2cfec0f 100644
--- a/tests/test_finetuning_new.py
+++ b/tests/test_finetuning_new.py
@@ -98,7 +98,7 @@ def _ft_job_payload(project: Project, dataset: Dataset, **overrides) -> dict:
def _setup() -> tuple[User, Project, Capability]:
u = make_user()
- p = make_project()
+ p = make_project(owner=u)
ProjectMembership.objects.create(user=u, project=p)
a = make_capability(p)
return u, p, a
diff --git a/tests/test_inference.py b/tests/test_inference.py
index 0c930147..25e68adc 100644
--- a/tests/test_inference.py
+++ b/tests/test_inference.py
@@ -12,6 +12,7 @@ from rest_framework import status
from overbae.api.filters import NO_CAPABILITY
from overbae.models import (
+ BillingTelemetry,
Capability,
Dataset,
FinetuningJob,
@@ -61,8 +62,7 @@ def test_inference_client_check_health_returns_false_on_error(scripted):
def test_deployed_models_list_filters_to_the_no_capability_bucket():
u = make_user()
- p = make_project()
- make_member(u, p)
+ p = make_project(member=u)
capability = make_capability(p)
attributed_job = _job(p)
FinetuningJob.objects.filter(pk=attributed_job.pk).update(capability=capability)
@@ -91,8 +91,7 @@ def test_deployed_models_list_filters_to_the_no_capability_bucket():
def test_deployed_models_list_rejects_a_malformed_capability_id():
"""The ``NO_CAPABILITY`` sentinel costs the param its ``UUIDFilter``; the 400 is raised by hand."""
u = make_user()
- p = make_project()
- make_member(u, p)
+ p = make_project(member=u)
_deployed_model(p)
r = auth_client(u).get(reverse("deployedmodel-list"), {"capability": "not-a-uuid"})
@@ -116,8 +115,7 @@ def test_deployed_models_retrieve_forbidden_for_other_user():
def test_deployed_models_delete_marks_deleted(scripted):
gateway = scripted("http://inference.test").reply(json_body={"ok": True})
u = make_user()
- p = make_project()
- make_member(u, p)
+ p = make_project(member=u)
m = _deployed_model(p)
r = auth_client(u).delete(reverse("deployedmodel-detail", args=[str(m.id)]))
@@ -129,8 +127,7 @@ def test_deployed_models_delete_marks_deleted(scripted):
def test_deploying_a_live_model_keeps_it_serving_without_new_gpu_work(fake_modal):
u = make_user()
- p = make_project()
- make_member(u, p)
+ p = make_project(member=u)
job = _job(p, status="succeeded")
m = _deployed_model(p, job)
@@ -144,8 +141,7 @@ def test_deploying_a_live_model_keeps_it_serving_without_new_gpu_work(fake_modal
@pytest.mark.covers("recovery")
def test_retrying_a_failed_deployment_requeues_it_and_clears_the_error(fake_modal):
u = make_user()
- p = make_project()
- make_member(u, p)
+ p = make_project(member=u)
job = _job(p, status="deploying")
m = _deployed_model(p, job)
DeployedModel.objects.filter(pk=m.pk).update(
@@ -164,8 +160,7 @@ def test_retrying_a_failed_deployment_requeues_it_and_clears_the_error(fake_moda
def test_deployed_models_retry_rejects_undeployable_job():
"""A failed training job has no checkpoint — the deploy task would no-op and park it QUEUED."""
u = make_user()
- p = make_project()
- make_member(u, p)
+ p = make_project(member=u)
job = _job(p, status="failed")
m = _deployed_model(p, job)
DeployedModel.objects.filter(pk=m.pk).update(status=DeployedModel.Status.FAILED)
@@ -178,24 +173,10 @@ def test_deployed_models_retry_rejects_undeployable_job():
@pytest.mark.covers("ledger")
-def test_inference_pricing_estimate_and_unknown_gpu():
- from overbae.services.inference_pricing import estimate_call_cost, gpu_usd_per_second
-
- # H100 = $3.95/h → $/sec; 2000 ms of generation.
- cost = estimate_call_cost("H100", 2000)
- # Helper rounds to 6 dp, so compare within that resolution.
- assert cost == pytest.approx(2000 / 1000 * (3.95 / 3600), abs=1e-6)
- # Unknown GPU or missing timing → honest None, never 0.
- assert estimate_call_cost("TPUv9", 2000) is None
- assert estimate_call_cost("H100", None) is None
- assert gpu_usd_per_second("nope") is None
-
-
@pytest.mark.covers("measured-facts")
def test_model_metrics_endpoint_aggregates():
u = make_user()
- p = make_project()
- make_member(u, p)
+ p = make_project(member=u)
m = _deployed_model(p)
m.gpu_type = "H100"
m.save(update_fields=["gpu_type"])
@@ -206,10 +187,18 @@ def test_model_metrics_endpoint_aggregates():
project=p,
prompt_tokens=10,
completion_tokens=5,
- cost=0.001,
tokens_per_second=50.0,
latency_ms=300,
)
+ # The serving containers' charge for the model, as the container meter writes it.
+ BillingTelemetry.objects.create(
+ user=u,
+ project=p,
+ amount="-0.003",
+ service="inference-ft-model",
+ cause_kind="deployed_model",
+ cause_id=str(m.pk),
+ )
r = auth_client(u).get(reverse("deployedmodel-metrics", args=[str(m.id)]))
assert r.status_code == status.HTTP_200_OK
@@ -218,7 +207,7 @@ def test_model_metrics_endpoint_aggregates():
assert r.data["completion_tokens"] == 15
assert r.data["total_tokens"] == 45
assert r.data["cost"] == pytest.approx(0.003)
- assert r.data["cost_is_estimate"] is True
+ assert r.data["cost_is_estimate"] is False
assert r.data["avg_tokens_per_second"] == pytest.approx(50.0)
assert r.data["avg_latency_ms"] == pytest.approx(300.0)
diff --git a/tests/test_ledger_cause_migration.py b/tests/test_ledger_cause_migration.py
new file mode 100644
index 00000000..a5741f84
--- /dev/null
+++ b/tests/test_ledger_cause_migration.py
@@ -0,0 +1,96 @@
+from decimal import Decimal
+
+import pytest
+from django.db.migrations.executor import MigrationExecutor
+from django.db.models import Sum
+from migration_replay import scratch_database
+
+pytestmark = pytest.mark.covers("migrations")
+
+
+def test_usage_rows_gain_their_recorded_cause_and_balances_hold(django_db_blocker):
+ before = [("overbae", "0077_deployed_model_cancelled")]
+ after = [("overbae", "0078_ledger_cause")]
+ rows = [
+ ("grant", "50", "signup:7", {}),
+ ("finetuning-job", "-3.5", "finetuning-job:j1", {"job_id": "j1"}),
+ (
+ "dedicated-inference",
+ "-2",
+ "dedicated:d1:2026-11-01T00:00:00",
+ {"minutes": 4, "replicas": 1, "gpu_type": "H100"},
+ ),
+ ("workspace", "-0.25", "modal-sandbox:sb-1:2026-11-01T00:00:00", {}),
+ ("assistant", "-0.01", "openrouter:gen-1", {"llm_usage": {"served_model": "m/x"}}),
+ ]
+ with scratch_database(django_db_blocker) as database:
+ executor = MigrationExecutor(database)
+ executor.migrate(before)
+ state = executor.loader.project_state(before).apps
+ user = state.get_model("overbae", "User").objects.create(email="[email protected]")
+ old = state.get_model("overbae", "BillingTelemetry")
+ for service, amount, key, metadata in rows:
+ old.objects.create(
+ user=user, service=service, amount=amount, idempotency_key=key, metadata=metadata
+ )
+ executor = MigrationExecutor(database)
+ executor.migrate(after)
+ new = executor.loader.project_state(after).apps.get_model("overbae", "BillingTelemetry")
+
+ described = {
+ row.idempotency_key: (row.cause_kind, row.cause_id, row.actor_id, row.provider_ref)
+ for row in new.objects.all()
+ }
+ assert described["signup:7"] == ("", "", None, "")
+ assert described["finetuning-job:j1"] == ("finetune_job", "j1", user.pk, "")
+ assert described["modal-sandbox:sb-1:2026-11-01T00:00:00"] == (
+ "workspace_sandbox",
+ "sb-1",
+ None,
+ "sb-1",
+ )
+ assert described["openrouter:gen-1"][3] == "gen-1"
+ dedicated = new.objects.get(service="dedicated-inference")
+ assert (dedicated.quantity, dedicated.unit, dedicated.unit_usd) == (
+ 4,
+ "minute",
+ Decimal("0.5"),
+ )
+ assert new.objects.aggregate(total=Sum("amount"))["total"] == Decimal("44.24")
+
+
+def test_trigger_caps_become_credits(django_db_blocker):
+ before = [("overbae", "0079_metered_container")]
+ after = [("overbae", "0080_trigger_cap_credits")]
+ with scratch_database(django_db_blocker) as database:
+ executor = MigrationExecutor(database)
+ executor.migrate(before)
+ state = executor.loader.project_state(before).apps
+ user = state.get_model("overbae", "User").objects.create(email="[email protected]")
+ project = state.get_model("overbae", "Project").objects.create(name="P", slug="cap")
+ experiment = state.get_model("overbae", "Experiment").objects.create(
+ project=project, created_by=user, name="E"
+ )
+ trigger = state.get_model("overbae", "ExperimentTrigger")
+ for cap in (Decimal("2.50"), None):
+ trigger.objects.create(
+ experiment=experiment,
+ kind="schedule",
+ instruction="Go.",
+ max_sends=1,
+ hours=24,
+ max_spend_usd=cap,
+ created_by=user,
+ )
+ executor = MigrationExecutor(database)
+ executor.migrate(after)
+ new = executor.loader.project_state(after).apps.get_model("overbae", "ExperimentTrigger")
+ assert sorted(new.objects.values_list("max_spend_credits", flat=True), key=str) == [
+ Decimal("250.00"),
+ None,
+ ]
+
+ executor = MigrationExecutor(database)
+ executor.migrate(before)
+ old = executor.loader.project_state(before).apps.get_model("overbae", "ExperimentTrigger")
+ assert Decimal("2.50") in old.objects.values_list("max_spend_usd", flat=True)
diff --git a/tests/test_llm_and_modal_billing.py b/tests/test_llm_and_modal_billing.py
deleted file mode 100644
index 71bc437e..00000000
--- a/tests/test_llm_and_modal_billing.py
+++ /dev/null
@@ -1,306 +0,0 @@
-from __future__ import annotations
-
-import uuid
-from datetime import UTC, datetime, timedelta
-from decimal import Decimal
-from unittest.mock import MagicMock, patch
-
-import pytest
-from conftest import TRAIN_ROWS, frozen_dataset
-from django.contrib.auth import get_user_model
-
-from overbae.models import BillingService, BillingTelemetry, Project
-from overbae.models.finetuning import FinetuningJob
-from overbae.services.billing_ledger import balance_usd, charge_llm_usage
-from overbae.services.finetuning_runner import PollSnapshot
-from overbae.tasks.finetuning import _transition, observe_finetuning_job
-
-pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]
-
-User = get_user_model()
-
-
-def _user(email: str) -> User:
- return User.objects.create_user(
- email=email,
- password="x",
- clerk_user_id=f"clerk_{uuid.uuid4().hex[:10]}",
- )
-
-
-def _project() -> Project:
- return Project.objects.create(
- name=f"p-{uuid.uuid4().hex[:6]}",
- slug=f"p-{uuid.uuid4().hex[:8]}",
- )
-
-
-def test_charge_llm_usage_bills_the_reported_cost_and_is_idempotent():
- user = _user("[email protected]")
- before = balance_usd(user)
- stats = {
- "prompt_tokens": 1000,
- "completion_tokens": 500,
- "cached_tokens": 700,
- "response_cost": 1.25,
- "served_model": "openai/gpt-5.6-terra",
- }
- key = f"data-workshop:test:{uuid.uuid4()}"
- row = charge_llm_usage(
- user,
- stats,
- service=BillingService.DATA_WORKSHOP,
- idempotency_key=key,
- metadata={"source": "test"},
- )
- assert row is not None
- assert row.amount == Decimal("-1.25")
- assert row.metadata["llm_usage"]["served_model"] == "openai/gpt-5.6-terra"
- assert balance_usd(user) == before - Decimal("1.25")
-
- again = charge_llm_usage(
- user,
- stats,
- service=BillingService.DATA_WORKSHOP,
- idempotency_key=key,
- metadata={"source": "test"},
- )
- assert again is None
- assert BillingTelemetry.objects.filter(idempotency_key=key).count() == 1
- assert balance_usd(user) == before - Decimal("1.25")
-
-
-def test_charge_llm_usage_falls_back_to_catalog_pricing(monkeypatch):
- """A provider that reports no cost is priced from the model that served it,
- and cache reads must not be billed as fresh input."""
- user = _user("[email protected]")
- seen = {}
-
- def _estimate(model, inp, out, cached_tokens=None):
- seen.update(model=model, inp=inp, out=out, cached=cached_tokens)
- return 0.4
-
- monkeypatch.setattr("overbae.services.model_catalog.estimate_cost", _estimate)
- row = charge_llm_usage(
- user,
- {
- "prompt_tokens": 1000,
- "completion_tokens": 500,
- "cached_tokens": 700,
- "served_model": "openai/gpt-5.6-terra",
- },
- service=BillingService.DATA_WORKSHOP,
- idempotency_key=f"data-workshop:fallback:{uuid.uuid4()}",
- )
- assert row is not None and row.amount == Decimal("-0.4")
- assert seen == {"model": "openai/gpt-5.6-terra", "inp": 1000, "out": 500, "cached": 700}
-
-
-def test_charge_llm_usage_skips_an_empty_turn(monkeypatch):
- user = _user("[email protected]")
- monkeypatch.setattr("overbae.services.model_catalog.estimate_cost", lambda *a, **k: 9.99)
- assert (
- charge_llm_usage(
- user, {}, service=BillingService.DATA_WORKSHOP, idempotency_key="data-workshop:empty"
- )
- is None
- )
- assert BillingTelemetry.objects.filter(idempotency_key="data-workshop:empty").count() == 0
-
-
-def test_composite_decision_billing_preserves_known_cost_when_one_attempt_is_unknown(monkeypatch):
- user = _user("[email protected]")
- monkeypatch.setattr("overbae.services.model_catalog.estimate_cost", lambda *a, **k: None)
- row = charge_llm_usage(
- user,
- {
- "response_cost": None,
- "attempts": [
- {"response_cost": None, "served_model": "typesafe/jev-1.13"},
- {"response_cost": 0.02, "served_model": "openai/gpt-5.6-terra"},
- ],
- },
- service=BillingService.DATA_WORKSHOP,
- idempotency_key="semantic-check:partial",
- )
- assert row.amount == Decimal("-0.02")
- assert row.metadata["cost_incomplete"] is True
-
-
-def test_cached_decision_is_not_repriced_as_a_fresh_call(monkeypatch):
- user = _user("[email protected]")
- monkeypatch.setattr("overbae.services.model_catalog.estimate_cost", lambda *a, **k: 9.99)
- assert (
- charge_llm_usage(
- user,
- {"response_cost": 0, "cached": True, "prompt_tokens": 100},
- service=BillingService.DATA_WORKSHOP,
- idempotency_key="semantic-check:cached",
- )
- is None
- )
-
-
-def test_provider_reported_zero_cost_is_not_repriced(monkeypatch):
- user = _user("[email protected]")
- monkeypatch.setattr("overbae.services.model_catalog.estimate_cost", lambda *a, **k: 9.99)
- assert (
- charge_llm_usage(
- user,
- {"response_cost": 0.0, "prompt_tokens": 100, "served_model": "openai/gpt-5.6-terra"},
- service=BillingService.DATA_WORKSHOP,
- idempotency_key="semantic-check:reported-zero",
- )
- is None
- )
- assert not BillingTelemetry.objects.filter(
- idempotency_key="semantic-check:reported-zero"
- ).exists()
-
-
[email protected]("delay_minutes", [0, 5, 60])
-def test_modal_terminal_transition_charges_recorded_worker_time_once(delay_minutes):
- user = _user("[email protected]")
- project = _project()
- dataset = frozen_dataset(project, TRAIN_ROWS, name="ds", contract="train")
- started = datetime(2026, 7, 28, 12, 0, tzinfo=UTC)
- job = FinetuningJob.objects.create(
- project=project,
- dataset=dataset,
- base_model="Qwen/Qwen3-8B",
- provider=FinetuningJob.Provider.MODAL,
- status=FinetuningJob.Status.RUNNING,
- triggered_by=user,
- started_at=started,
- remote_job_id="run:fc",
- progress={
- "compute_usage": [
- {"usage_id": "worker", "gpu_type": "H100", "gpu_count": 1, "elapsed_seconds": 60},
- {"usage_id": "worker", "gpu_type": "H100", "gpu_count": 1, "elapsed_seconds": 120},
- {"usage_id": "worker", "gpu_type": "H100", "gpu_count": 1, "elapsed_seconds": 120},
- {"usage_id": "retry", "gpu_type": "H200", "gpu_count": 2, "elapsed_seconds": 30},
- ]
- },
- )
-
- with (
- patch(
- "overbae.services.finetuning_runner.ModalRunner._select_training_gpu",
- side_effect=AssertionError("Billing must not guess hardware from today's planner"),
- ) as select_gpu,
- ):
- completed = started + timedelta(seconds=150, minutes=delay_minutes)
- with patch("overbae.tasks.finetuning.timezone.now", return_value=completed):
- _transition(job, FinetuningJob.Status.SUCCEEDED)
- select_gpu.assert_not_called()
-
- job.refresh_from_db()
- assert job.cost_usd == Decimal("0.2073")
- assert job.cost_synced_at is not None
- rows = BillingTelemetry.objects.filter(user=user, service=BillingService.FINETUNING_JOB)
- assert rows.count() == 1
- assert rows.get().amount == Decimal("-0.2073")
- assert rows.get().metadata["basis"] == "recorded_worker_gpu_seconds"
- assert len(rows.get().metadata["measurements"]) == 2
-
- with (
- patch(
- "overbae.services.finetuning_runner.ModalRunner._select_training_gpu",
- return_value=("H100", 1),
- ),
- patch(
- "overbae.tasks.finetuning.timezone.now",
- return_value=completed + timedelta(minutes=5),
- ),
- ):
- _transition(job, FinetuningJob.Status.SUCCEEDED)
-
- assert (
- BillingTelemetry.objects.filter(user=user, service=BillingService.FINETUNING_JOB).count()
- == 1
- )
-
-
-def test_completed_chat_training_records_its_charge_before_deployment_and_never_twice():
- user = _user("[email protected]")
- project = _project()
- job = FinetuningJob.objects.create(
- project=project,
- dataset=frozen_dataset(project, TRAIN_ROWS, name="chat", contract="train"),
- base_model="Qwen/Qwen3-8B",
- provider="modal",
- status="running",
- triggered_by=user,
- remote_job_id="run:call",
- )
- runner = MagicMock()
- runner.poll.return_value = PollSnapshot(
- state="succeeded",
- step=8,
- total_steps=8,
- raw={
- "run_id": "run",
- "meta": {
- "compute_usage": [
- {
- "usage_id": "worker",
- "gpu_type": "H100",
- "gpu_count": 1,
- "elapsed_seconds": 120,
- }
- ]
- },
- },
- )
- runner.is_terminal_ok.return_value = True
- runner.is_terminal_fail.return_value = False
- runner.is_terminal_cancelled.return_value = False
- runner.fetch_epoch_losses.return_value = []
- with (
- patch("overbae.services.finetuning_runner.get_runner", return_value=runner),
- patch("overbae.services.finetuning_eval.tick_job_evals"),
- patch("overbae.tasks.model_deployment.register_finetuned_model.delay") as deploy,
- ):
- observe_finetuning_job(job)
- job.refresh_from_db()
- assert job.status == "deploying"
- assert job.cost_usd is not None
- receipt = job.result["compute_charge"]
- assert receipt["measurements"][0]["seconds"] == 120
- assert deploy.call_count == 1
- observe_finetuning_job(job)
- _transition(job, FinetuningJob.Status.FAILED, error="injected deployment failure")
- job.refresh_from_db()
- assert job.result["compute_charge"] == receipt
- entries = BillingTelemetry.objects.filter(idempotency_key=f"finetuning-job:{job.id}")
- assert entries.count() == 1
- assert entries.get().amount == -job.cost_usd
-
-
- "usages",
- [
- [],
- [{"usage_id": "worker", "gpu_type": "H100", "gpu_count": 1}],
- [{"usage_id": "worker", "gpu_type": "unknown", "gpu_count": 1, "elapsed_seconds": 120}],
- [
- {"usage_id": "worker", "gpu_type": "H100", "gpu_count": 1, "elapsed_seconds": 120},
- {"usage_id": "worker", "gpu_type": "L4", "gpu_count": 1, "elapsed_seconds": 121},
- ],
- ],
-)
-def test_missing_or_conflicting_worker_usage_cannot_be_replaced_by_collector_elapsed(usages):
- project = _project()
- dataset = frozen_dataset(project, TRAIN_ROWS, name="ds", contract="train")
- job = FinetuningJob.objects.create(
- project=project,
- dataset=dataset,
- base_model="Qwen/Qwen3-8B",
- provider="modal",
- status="running",
- started_at=datetime(2026, 7, 28, 12, 0, tzinfo=UTC),
- progress={"compute_usage": usages},
- )
- _transition(job, FinetuningJob.Status.SUCCEEDED)
- job.refresh_from_db()
- assert job.cost_usd is None and job.cost_synced_at is None
diff --git a/tests/test_mcp_finetuning.py b/tests/test_mcp_finetuning.py
index 97f48d4a..94dea6bd 100644
--- a/tests/test_mcp_finetuning.py
+++ b/tests/test_mcp_finetuning.py
@@ -36,7 +36,9 @@ def _context(*, permission: str | list[str] = "read") -> MCPContext:
password="pw",
clerk_user_id=f"clerk_{uuid.uuid4().hex}",
)
- project = Project.objects.create(name="Fine tuning", slug=f"ft-{uuid.uuid4().hex[:8]}")
+ project = Project.objects.create(
+ name="Fine tuning", slug=f"ft-{uuid.uuid4().hex[:8]}", owner=user
+ )
ProjectMembership.objects.create(user=user, project=project)
permissions = [permission] if isinstance(permission, str) else permission
token = APIToken(scope={"scope": "project", "permission": permissions})
diff --git a/tests/test_mcp_inventory.py b/tests/test_mcp_inventory.py
index 595a7f8b..209ae467 100644
--- a/tests/test_mcp_inventory.py
+++ b/tests/test_mcp_inventory.py
@@ -111,29 +111,34 @@ def test_batch_status_cursor_reports_changes_and_isolated_errors():
assert third["jobs"][0]["job"]["status"] == "failed"
-def test_project_spend_preserves_unattributed_charges_and_account_isolation():
- job_id = str(uuid4())
+def test_project_spend_groups_by_cause_across_services_and_stays_in_the_project():
+ job_id, run_id = str(uuid4()), str(uuid4())
context, other = mcp_context(), mcp_context()
- for user, project, amount, metadata in [
- (context.user, context.project, "-2", {"job_id": job_id}),
- (context.user, context.project, "-3", {}),
- (other.user, context.project, "-100", {}),
- (context.user, other.project, "-100", {}),
+ for project, amount, service, kind, cause in [
+ (context.project, "-2", "finetuning-job", "finetune_job", job_id),
+ (context.project, "-3", "evaluation", "eval_run", run_id),
+ (context.project, "-1", "evaluation", "eval_run", run_id),
+ (other.project, "-100", "evaluation", "eval_run", run_id),
]:
BillingTelemetry.objects.create(
- user=user,
+ user=project.owner,
project=project,
amount=Decimal(amount),
- service="finetuning-job",
- metadata=metadata,
+ service=service,
+ cause_kind=kind,
+ cause_id=cause,
)
result = call(context, "get_credit_usage", limit=1)
- assert Decimal(result["spent_credits"]) == 500
+ assert Decimal(result["spent_credits"]) == 600
assert result["total_groups"] == 2
assert result["next_offset"] == 1
- filtered = call(context, "get_credit_usage", training_job=job_id)
- assert Decimal(filtered["spent_credits"]) == 200
+ filtered = call(context, "get_credit_usage", cause_kind="eval_run", cause_id=run_id)
+ (group,) = filtered["groups"]
+ assert (Decimal(group["spent_credits"]), group["entries"]) == (400, 2)
+ assert (
+ Decimal(call(context, "get_credit_usage", service="finetuning-job")["spent_credits"]) == 200
+ )
def test_lineage_keeps_missing_pins_unknown_and_returns_deployment_identity():
diff --git a/tests/test_model_meter.py b/tests/test_model_meter.py
new file mode 100644
index 00000000..ea0ce9fb
--- /dev/null
+++ b/tests/test_model_meter.py
@@ -0,0 +1,112 @@
+import uuid
+from decimal import Decimal
+
+import pytest
+from asgiref.sync import async_to_sync
+from factories import make_member, make_project, make_span, make_user
+
+from overbae.core.llms import IncompleteCompletionError, call_llm, stream_llm_tools
+from overbae.innermind import span_processor
+from overbae.models import BillingService, BillingTelemetry
+from overbae.services import billing_ledger, model_meter
+from overbae.tasks import billing as billing_tasks
+
+pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]
+
+
+def owner():
+ return make_user()
+
+
+def project(owner):
+ return make_project(member=owner)
+
+
+def usage_rows():
+ return list(BillingTelemetry.objects.filter(amount__lt=0).order_by("timestamp"))
+
+
+def test_an_answered_call_is_charged_to_the_owner_at_the_provider_cost(fake_llm, owner, project):
+ member = make_user()
+ make_member(member, project)
+ fake_llm.on(lambda r: True, {"content": "ok", "usage": {"cost": 0.002}})
+ found = billing_ledger.cause(project.pk, BillingService.SCORING, "span", "s-1", actor=member)
+ with model_meter.billed(found):
+ call_llm("hi")
+
+ (row,) = usage_rows()
+ assert (row.user_id, row.actor_id, row.project_id) == (owner.pk, member.pk, project.pk)
+ assert (row.cause_kind, row.cause_id, row.service) == ("span", "s-1", "scoring")
+ assert (row.quantity, row.unit, row.unit_usd, row.amount) == (
+ Decimal(1),
+ "generation",
+ Decimal("0.002"),
+ Decimal("-0.002"),
+ )
+ assert row.idempotency_key == f"openrouter:{row.provider_ref}"
+
+
+def test_an_answer_cut_at_its_token_limit_is_still_charged(fake_llm, project):
+ fake_llm.on(
+ lambda r: True, {"content": "par", "finish_reason": "length", "usage": {"cost": 0.01}}
+ )
+ with (
+ model_meter.billed(billing_ledger.cause(project.pk, "evaluation", "eval_run", "r")),
+ pytest.raises(IncompleteCompletionError),
+ ):
+ call_llm("hi")
+ assert [row.amount for row in usage_rows()] == [Decimal("-0.01")]
+
+
+def test_an_unpriced_stream_is_charged_once_the_provider_prices_it(
+ fake_llm, owner, project, monkeypatch
+):
+ later = []
+ monkeypatch.setattr(billing_tasks.price_generation, "delay", lambda *a: later.append(a))
+ fake_llm.stream_rounds([([], "Hello.")], cost=None)
+ found = billing_ledger.cause(project.pk, "assistant", "assistant_thread", str(uuid.uuid4()))
+ with model_meter.billed(found):
+ stream_llm_tools([{"role": "user", "content": "hi"}], [])
+ assert usage_rows() == []
+ ((cause, generation, model, cost, usage),) = later
+ assert cost is None
+
+ fake_llm.generations[generation] = 0.02
+ for _ in range(2):
+ billing_tasks.price_generation.apply(args=(cause, generation, model, cost, usage))
+ (row,) = usage_rows()
+ assert (row.amount, row.user_id, row.cause_kind) == (
+ Decimal("-0.02"),
+ owner.pk,
+ "assistant_thread",
+ )
+
+
+def test_a_deleted_projects_generation_keeps_its_project_and_owner(fake_llm, owner, project):
+ cause = billing_ledger.cause(
+ project.pk, "assistant", "assistant_thread", str(uuid.uuid4())
+ ).as_dict()
+ project_id = project.pk
+ project.delete()
+ fake_llm.generations["gen-gone"] = 0.03
+ billing_tasks.price_generation.apply(args=(cause, "gen-gone", "m", None, {}))
+ (row,) = usage_rows()
+ assert (row.amount, row.user_id, row.project_id) == (Decimal("-0.03"), owner.pk, project_id)
+
+
+def test_a_call_with_no_cause_is_named_and_charged_to_no_one(fake_llm, caplog):
+ fake_llm.on(lambda r: True, {"content": "ok", "usage": {"cost": 0.002}})
+ call_llm("hi")
+ assert usage_rows() == []
+ assert "OpenRouter generation without a billing cause" in caplog.text
+
+
+def test_scoring_waits_while_the_owner_has_no_credits(fake_llm, owner, project):
+ billing_ledger.append_entry(user=owner, amount=Decimal("-50"), service="assistant")
+ span = make_span(project, trace_id="t-1")
+ assert async_to_sync(span_processor.score_project_spans)(project.pk, [span]) == []
+ assert fake_llm.requests == [] and fake_llm.decisions == []
+ span.refresh_from_db()
+ assert "score" not in span.eval_attributes
diff --git a/tests/test_native_evaluation_cancel.py b/tests/test_native_evaluation_cancel.py
index 59771397..d54e52b5 100644
--- a/tests/test_native_evaluation_cancel.py
+++ b/tests/test_native_evaluation_cancel.py
@@ -16,7 +16,7 @@ pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]
@pytest.fixture
def running(monkeypatch):
user = User.objects.create_user(email="[email protected]")
- project = Project.objects.create(name="Cancel", slug="cancel")
+ project = Project.objects.create(name="Cancel", slug="cancel", owner=user)
ProjectMembership.objects.create(project=project, user=user)
dataset = frozen_dataset(
project,
diff --git a/tests/test_operational_progress.py b/tests/test_operational_progress.py
index 61e794aa..44307eef 100644
--- a/tests/test_operational_progress.py
+++ b/tests/test_operational_progress.py
@@ -59,7 +59,6 @@ def test_training_terminal_timeline_matches_mcp_without_another_provider_call(
runner.fetch_epoch_losses.return_value = []
with (
patch("overbae.services.finetuning_runner.get_runner", return_value=runner),
- patch("overbae.tasks.finetuning._charge_modal_finetuning"),
patch("overbae.tasks.model_deployment.register_finetuned_model.delay") as deploy,
patch("overbae.celery.get_celery_app") as app,
):
diff --git a/tests/test_provider_check.py b/tests/test_provider_check.py
new file mode 100644
index 00000000..3f831b82
--- /dev/null
+++ b/tests/test_provider_check.py
@@ -0,0 +1,48 @@
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+
+import pytest
+from factories import make_project, make_user
+
+from overbae.models import BillingTelemetry
+from overbae.services import provider_check
+
+pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]
+
+
+def charge(project, usd, resource, when):
+ return BillingTelemetry.objects.create(
+ user=project.owner,
+ project=project,
+ amount=-usd,
+ service="evaluation",
+ resource=resource,
+ ended_at=when,
+ )
+
+
+def test_the_daily_check_alerts_only_when_ledger_and_bills_differ_by_more_than_two_percent(
+ fake_modal, fake_llm, settings, caplog
+):
+ settings.MODAL_ENVIRONMENT = "main"
+ project = make_project(member=make_user())
+ yesterday = datetime.now(UTC) - timedelta(days=1)
+ charge(project, 10, "modal H100 x1, 8 CPU, 64 GiB", yesterday)
+ charge(project, 5, "openrouter m", yesterday)
+ fake_modal.billing_items = [
+ SimpleNamespace(cost=10.1, environment_name="main"),
+ SimpleNamespace(cost=900, environment_name="other-environment"),
+ ]
+ fake_llm.key_usage_monthly = 5
+ before = list(BillingTelemetry.objects.values())
+
+ results = provider_check.check()
+
+ assert [result["within_tolerance"] for result in results] == [True, True]
+ assert "differs from the provider bill" not in caplog.text
+
+ fake_llm.key_usage_monthly = 6
+ (_, openrouter) = provider_check.check()
+ assert openrouter["within_tolerance"] is False
+ assert "differs from the provider bill by more than 2%" in caplog.text
+ assert list(BillingTelemetry.objects.values()) == before
diff --git a/tests/test_provider_pricing.py b/tests/test_provider_pricing.py
index c4b5a517..28596cd5 100644
--- a/tests/test_provider_pricing.py
+++ b/tests/test_provider_pricing.py
@@ -4,7 +4,6 @@ import pytest
from overbae.services import provider_pricing
from overbae.services.compute_costs import estimate_usage
-from overbae.services.inference_pricing import gpu_usd_per_second
pytestmark = pytest.mark.covers("ledger")
@@ -23,7 +22,7 @@ def test_current_workspace_rates_drive_costs_without_historical_charges(monkeypa
assert card["status"] == "current"
assert card["fetched_at"] and card["source"] == "modal.Workspace.billing.rates"
monkeypatch.setattr(provider_pricing, "current_rates", lambda: card)
- assert gpu_usd_per_second("H100") == 0.002
+ assert provider_pricing.gpu_rate(card, "H100") == 0.002
result = estimate_usage(
[
{
@@ -49,7 +48,7 @@ def test_unavailable_or_invalid_rates_do_not_fall_back_to_static_prices(monkeypa
assert failed["status"] == "unavailable" and failed["rates"] == {}
assert "private" not in str(failed)
monkeypatch.setattr(provider_pricing, "current_rates", lambda: failed)
- assert gpu_usd_per_second("H100") is None
+ assert provider_pricing.gpu_rate(failed, "H100") is None
monkeypatch.setattr(
provider_pricing,
"fetch_rates",
diff --git a/tests/test_scoring_isolation.py b/tests/test_scoring_isolation.py
index 51369e7a..e6bbe0d9 100644
--- a/tests/test_scoring_isolation.py
+++ b/tests/test_scoring_isolation.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import pytest
from asgiref.sync import async_to_sync
-from factories import make_project, make_span
+from factories import make_project, make_span, make_user
from overbae.innermind import comparison, deterministic, evidence, trajectory
from overbae.models import EvalRun, EvalScore, Span
@@ -53,7 +53,7 @@ def test_cyclic_ancestry_terminates_without_inventing_intent():
@pytest.mark.covers("tenancy")
@pytest.mark.django_db(transaction=True)
def test_trajectory_scores_only_the_admitted_project():
- a, b = make_project(), make_project()
+ a, b = make_project(member=make_user()), make_project(member=make_user())
root = make_span(a, trace_id="shared", eval_attributes={"score": 0.8})
other = make_span(b, trace_id="shared", eval_attributes={"score": 0.1})
assert async_to_sync(trajectory.score_traces)(a.pk, ["shared"]) == 1
diff --git a/tests/test_signals.py b/tests/test_signals.py
index 77522565..2807747a 100644
--- a/tests/test_signals.py
+++ b/tests/test_signals.py
@@ -34,7 +34,7 @@ pytestmark = [pytest.mark.django_db, pytest.mark.covers("metrics-math")]
@pytest.fixture
def context():
user = User.objects.create_user(email=f"{uuid.uuid4()}@test.com", password="pw")
- project = Project.objects.create(name="Signals", slug=f"signals-{uuid.uuid4()}")
+ project = Project.objects.create(name="Signals", slug=f"signals-{uuid.uuid4()}", owner=user)
ProjectMembership.objects.create(user=user, project=project)
key, token = APIToken.create_for_user(user, project=project)
client = APIClient()
diff --git a/tests/test_training_preparation.py b/tests/test_training_preparation.py
index 9950fe2b..a018c64c 100644
--- a/tests/test_training_preparation.py
+++ b/tests/test_training_preparation.py
@@ -7,6 +7,7 @@ from unittest.mock import Mock, patch
import pytest
from conftest import TRAIN_ROWS, frozen_dataset
from django.utils import timezone
+from factories import make_project, make_user
from modal.exception import NotFoundError
from rest_framework.test import APIClient
@@ -51,7 +52,7 @@ def preparation_volume(monkeypatch):
@pytest.fixture
def cell(settings):
settings.FINETUNING_BACKEND = "modal"
- project = Project.objects.create(name="Prep", slug="prep")
+ project = make_project("Prep", member=make_user())
return frozen_dataset(project, TRAIN_ROWS, contract="train").active_cell