# Attribution groups

**Last updated:** 2026-11-22T07:30:00-03:00 (UTC-3)

An attribution group is a financial grouping of one team's traffic: an **application**, a **harness** (a coding agent or batch runner), a **repository** or any **custom** grouping. Rules attribute each request to at most one group of its team, from facts the gateway owns: the authenticated team, the authenticated key and the canonical model alias. Budgets and TPM can then target a group, and a report shows spend per group with its coverage. Flag: `attribution_groups` (default `false`).

Groups are not [usage tags](/docs/features/usage-tags/). A tag is a label the client declares; a group is decided by the server and cannot be chosen or avoided by a header, the body, the end user or a session ID. That is why a group can carry a hard budget and a tag cannot. Both can be used together: the report groups by attribution, the analytics pages still filter by tag.

Groups are financial ownership only. They do not change routing, authorization, tenancy or plan rights, and a team role sees nothing new.

## Enable it

```yaml
features:
  usage_analytics: true       # required
  attribution_groups: true
attribution_groups:
  groups:
    - id: support-bot         # unique; ^[a-z][a-z0-9_-]{1,63}$
      kind: application       # application, harness, repository or custom
      team_id: acme           # the owning team (its ID, not its name)
      name: Support assistant # optional, up to 120 printable bytes
    - id: ci-monorepo
      kind: repository
      team_id: acme
    - id: acme-other
      kind: custom
      team_id: acme
  rules:
    - id: support-keys        # unique; same grammar as group ids
      group: support-bot
      precedence: 10          # 1-100000, unique within the team; lowest wins
      key_ids: [key_support_prod, key_support_eval]
    - id: ci-cheap-model
      group: ci-monorepo
      precedence: 20
      key_ids: [key_ci]
      models: [fast-chat]     # canonical model aliases
  teams:
    - team_id: acme
      unmatched: default_group   # unattributed, default_group or deny
      default_group: acme-other
```

The flag is an operator control, changes at runtime and applies on the next request. It needs PostgreSQL: migration 147 creates the rule set history, adds the captured attribution to usage events and durable receipts, and widens a reservation's charge bound to 140 so a group subject fits next to every other one. The new columns have no default and their shape checks are `NOT VALID` (existing rows hold no attribution), so the migration neither rewrites nor scans the usage tables; new rows are checked. Without storage the inference request answers `503 attribution_unavailable` and the API answers `503`.

### Fields and bounds

| Field | Default | Bounds and meaning |
| --- | --- | --- |
| `groups[]` | none | Up to 256. `id`, `kind` and `team_id` are required. |
| `groups[].name` | empty | Optional display name of the group in reports and the console, up to 120 printable bytes |
| `groups[].kind` | required | `application`, `harness`, `repository`, `custom`. Informational: every kind behaves the same. |
| `rules[]` | none | Up to 512. Each names an existing `group` and needs `key_ids`, `models` or both. |
| `rules[].precedence` | required | 1-100000, unique per team. The lowest matching precedence wins; there are no ties. |
| `rules[].key_ids` | any key | Up to 64 key IDs (YAML or managed). A rule naming a removed key simply never matches. |
| `rules[].models` | any model | Up to 32 canonical model aliases, matched exactly. |
| `teams[].team_id` | required | The team these settings apply to, by its ID; one entry per team. |
| `teams[].default_group` | none | The group of that team an unmatched request is attributed to; required with `unmatched: default_group`. |
| `teams[].unmatched` | `unattributed` | What a request of that team that matches no rule gets: `unattributed` (recorded as unmatched), `default_group` (attributed to `default_group`, a group of the same team) or `deny`. |
| whole policy | | 256 KiB of canonical JSON. |

A rule only ever sees requests of its group's team. A rule of team `acme` that names a key of team `beta` never matches, so one team cannot charge another team's group or move its own traffic there.

## How a request is attributed

Once per inference request, after authentication, team and model admission and before the durable receipt, the quota reservation or any provider call:

1. The gateway reads the effective rule set version (one indexed read; the parsed body is cached by version).
2. It takes the matching rule with the lowest precedence among the rules of the request's team. A rule matches when the key is in `key_ids` (if set) and the canonical model is in `models` (if set).
3. Without a match it applies the team's `unmatched` setting. With `deny` the request is refused with `422 attribution_group_required` and the provider is not called; its own usage event records it as `unmatched` under that version.
4. The result is captured once: the group (empty when unmatched), the rule (empty for a team default), the source (`rule`, `team_default` or `unmatched`) and the rule set version. The durable receipt, the quota reservation and the usage event carry the same values; the final event cannot move a receipt to another group.

Chat and the other inference routes, native Messages and Gemini, passthrough, video and each Realtime response are attributed. Administrative routes, MCP and `/v1/models` are not. A call the gateway makes while serving a client request of the same team (a moderation guardrail, an auto-routing helper, embeddings for a vector search) inherits that request's attribution; it never resolves rules for its own model. A moderation guardrail call without such a parent records no attribution rather than being refused. Every other internal call (batch lines, evaluations) is attributed like a direct request of its key and model, so a group budget or `deny` cannot be avoided through `/v1/batches`. Auto-routing helpers (the embedding or classifier call that chooses the target) run before the request is attributed and are resolved like requests of the same key: a team with `deny` and model-only rules must also cover those helper models, or use key rules.

## Budgets and TPM per group

A quota policy with `subject: group` and the group ID as `subject_id` limits that group's traffic, with everything a policy offers: TPM, TPD, USD per day, month, week, quarter, year or lifetime, `soft_budget`, alert thresholds and temporary increases.

```yaml
quotas:
  policies:
    - id: support-monthly
      subject: group
      subject_id: support-bot
      budget_usd: "250"
      budget_period: month
      alert_thresholds: [80, 100]
```

- The group ceiling is cumulative over every key and model that the rules attribute to the group, reserved in the same PostgreSQL transaction as every other applicable policy: concurrent requests never pass it together.
- An unknown outcome (timeout, crash, missing usage) keeps its hold until [reconciliation](/docs/features/quota-finance/) substantiates it; it never becomes zero.
- A group policy needs `attribution_groups`. In YAML it must name a group of the YAML rules. In the console it must name a group of the effective rule set (`422 unknown_quota_subject` otherwise, checked in the same transaction as the write), and a rule set version cannot drop a group that an enabled policy targets (`409 group_in_use`).
- **Flag off with a group budget.** If `attribution_groups` is turned off while an enabled group policy exists, requests of the team that owns that group are refused with `503 quota_unavailable` instead of running without the group ceiling. Other teams are unaffected. Disable or remove the group policies first.
- **Orphaned budgets.** A group policy that came from a YAML quota base for a group the effective (console) rule set does not define matches no request. `GET /api/v1/admin/attribution-groups` lists such policies in `orphaned_group_policies` (with `orphaned_group_policies_unknown: true` when the quota catalog could not be read), and the console warns about them.
- Status: group items appear from `GET /api/v1/admin/quota-policies/status?status_version=5`; earlier status versions leave them out.

## Rule versions

Every effective rule set is an immutable, numbered version; the database refuses to update or delete one.

- **YAML base.** The YAML block is adopted as version 1 the first time it is needed. When the effective version came from YAML and a restarted process has a different YAML, that process adopts it once, as the next version. A body that some version already held is never adopted again, so replicas still running the earlier YAML during a rolling change do not alternate versions; to return to an earlier body, use revert. A YAML base that would drop a group an enabled quota policy targets is not adopted: the current version stays, the gateway logs `attribution_base_not_adopted` and the API reports `base_differs: true`.
- **Console.** Publishing creates the next version (`source: console`). A later YAML change never replaces it; the API reports `base_differs: true` until an administrator reverts.
- **Revert** publishes the YAML body again as a new version (`source: yaml`). Nothing is deleted.
- Recorded requests keep the version they were attributed under, so a rule change never reinterprets history.

## API

All responses are `private, no-store`. Reads need a global role with `quotas:read`; writes need a live global administrator, `quotas:manage`, same origin and CSRF, and are audited (`attribution_groups.publish`, `attribution_groups.revert`). Team roles are refused.

| Method and path | What it does |
| --- | --- |
| `GET /api/v1/admin/attribution-groups` | The effective version: `version`, `source`, `fingerprint`, `policy`, `created_at`, `base_fingerprint`, `base_differs`, `group_kinds`, `orphaned_group_policies` |
| `PUT /api/v1/admin/attribution-groups` | `{version, policy}`: publish the next version under compare-and-set (`409 version_conflict` if another version was published) |
| `DELETE /api/v1/admin/attribution-groups` | `{version}`: publish the YAML base again |
| `GET /api/v1/admin/attribution-groups/versions?limit=50` | History, newest first (1-200) |
| `GET /api/v1/admin/attribution-groups/versions?version=N` | One version with its body |
| `GET /api/v1/admin/attribution-groups/report` | Spend per group with coverage; `from`, `to` (RFC 3339, at most 366 days, default the last 30), `team`, `format=csv` |

```bash
curl -b "$COOKIE_FILE" -H "X-CSRF-Token: $CSRF" -X PUT \
  -H 'Content-Type: application/json' \
  -d '{"version":1,"policy":{"groups":[{"id":"support-bot","kind":"application","team_id":"acme"}],"rules":[{"id":"support-keys","group":"support-bot","precedence":10,"key_ids":["key_support_prod"]}],"teams":[{"team_id":"acme","unmatched":"deny"}]}}' \
  http://localhost:8080/api/v1/admin/attribution-groups
```

### Report and coverage

```json
{
  "from": "2026-10-15T00:00:00Z",
  "to": "2026-11-14T00:00:00Z",
  "coverage": {"events": 1200, "by_rule": 1000, "team_default": 150, "unmatched": 20, "not_evaluated": 30, "versions": [1, 2]},
  "groups": [
    {"team": "acme", "group": "support-bot", "source": "rule", "requests": 1000, "input_tokens": 900000, "output_tokens": 90000,
     "estimated_usd": "1.26", "valued_known": 990, "valued_partial": 0, "valued_unknown": 6, "not_valued": 4, "tokens_unknown": 3, "rule_versions": 2}
  ],
  "truncated": false
}
```

- `coverage` counts every selected event: attributed by a rule, by a team default, unmatched, or **not evaluated** (recorded before the feature, with the flag off, or on a route that is not attributed). A group total is only as complete as its coverage.
- `team` filters before aggregation.
- Token sums leave out requests without a reported count; `tokens_unknown` says how many.
- `estimated_usd` sums only known [valuations](/docs/features/usage-valuation/), priced from the price book with discounts and margins frozen in each event. It is an estimate, not a provider charge; with `budget_charge_reports` each group also carries `budget_charge`, what its budgets took at the approved rates ([budget charge beside the estimate](/docs/features/usage-valuation/#budget-charge-beside-the-estimate)); partial, unknown and not valued requests are counted, never treated as zero. Provider charges are compared in [financial reconciliation](/docs/features/quota-finance/).
- Up to 500 rows (largest first); `truncated` says more exist. The CSV has the same columns plus a final `#coverage` line, with spreadsheet formulas neutralized.

## Console

**Access control → Attribution groups** shows the coverage, the spend table (with a CSV download), the rules in force (precedence, group, `key_ids`, `models`) and the team defaults (`unmatched`, `default_group`) as tables beside the rule set JSON editor, with its version and base state, and the version history. Global viewers read; only a global administrator publishes or reverts. Group budgets are edited in **Budget & TPM** like any policy, with subject **group**.

## Limits and upgrade notes

- Matching uses the authenticated team, key and canonical model only. There is no matching by user, project, end user, tag or header.
- Rule sets and captured attribution live in PostgreSQL; group budgets are qualified with the PostgreSQL quota store only.
- **Upgrade.** Migrate every replica (migration 147), upgrade them all, then turn the flag on, and only then add group policies. An older replica does not know `subject: group`: it neither attributes requests nor enforces group ceilings. To roll back, remove group policies, turn the flag off, then downgrade.
