# Integrating buckette into an LLM / agent system This doc is for an LLM or coding agent that needs to use buckette as a resource ledger for an agentic system — token budgets, tool-call quotas, spend limits, concurrency slots, etc. It assumes you already have API access (an API key and the base URL of your instance; `GET /openapi.json` has the full endpoint list). This doc focuses on *which concepts to reach for* and *how to wire them into an agent's control flow*. Also available at runtime: `GET /help` and `GET /help/:topic` return the same kind of guidance as structured JSON, by the instance you are talking to — useful if you (the agent) want to introspect instead of relying on this static doc. This guide is served as plain text at `GET /docs/llm.md`, so an agent that only has API access can fetch it directly. A help topic is `{heName, heSummary, heContent, heEndpoints, heTramaj}`. `heContent` is plain text and is always the answer for an agent, the CLI and `curl`. `heTramaj` is optional (`null` on most topics): the same topic as tramaj markup (headings, lists, emphasis, links between topics) for a client that renders it, such as the Console, which falls back to `heContent` when the field is `null` or does not parse. An agent can ignore it. Today only `human:topups` carries one. Everything here is the **tenant** surface: what an API key can do. buckette also has an operator surface — standing tenants up, plan limits, holds, teardown, instance diagnostics — gated on a credential no API key carries and documented separately, for whoever runs the instance. If you are wiring an agent against a tenant key, this file is the whole of what you can reach; the other document is not missing context you need. --- ## Accounts, tenants and first keys This instance has an account service in front of it (a control plane). Signing up, choosing a plan, creating a tenant and obtaining that tenant's first API key all happen there, not on this API. It has its own guide for agents: https://console-api.buckette.co/docs/llm.md Read it if you do not hold an API key yet, or if you need another tenant. Once you hold a key, this document is the one that applies. --- ## Start here: the first calls of a working setup Six calls make an agent's budget, every one with an API key in `Authorization: Bearer `. Each step names the section with the detail. 1. **Create a bucket, with a title.** `POST /buckets` `{"cbrResources": {"tokens": {"raCurrent": 100000, "raMaximum": 100000, "raReserved": 0, "raUnit": "tok", "raMode": "Locking"}}, "cbrMetadata": {"buckette/bucket-title": "agent budget"}}`. The answer is the bucket; keep its `bucketId`. "Bucket" and "Dimension" below; `GET /help/buckets`. 2. **Give it a schedule.** `PUT /buckets/:id/replenish-config` `{"rcSchedule": {"tag": "Monthly", "day": 1, "at": "00:00", "zone": "UTC"}, "rcAmounts": {"tokens": 100000}, "rcCarryover": "CarryoverNone", "rcOverflow": "OverflowDiscard"}`. "Replenishment"; `GET /help/replenishment`. 3. **Split a child for one run.** `POST /buckets/:id/split` `{"srAllocation": {"tokens": 20000}, "srMetadata": {"buckette/bucket-title": "run 4812"}}` answers `srChildId`. "Split / reclaim"; `GET /help/splitting`. 4. **Mint a key scoped to the child.** `POST /api-keys` `{"cakreName": "run-4812", "cakreScopes": ["ScopeConsume", "ScopeRead"], "cakreBucketId": ""}`; `cakrKey` is the key, shown once. Hand it to the sub-agent: it sees nothing outside the child. "Bucket-scoped delegated API keys"; `GET /help/delegation`. 5. **Consume before each call.** With that key, `POST /buckets/:childId/consume` `{"crAmounts": {"tokens": 1200}, "crMode": {"tag": "Strict"}}`. Read `tag` in the answer: `ConsumeSuccess` (go on; `coRemaining` is what is left) or `ConsumeShortfall` (nothing was taken: stop, or wait for `coEta`). "Consume modes"; `GET /help/consuming`. 6. **Reclaim when the run ends.** `POST /buckets/:childId/reclaim` `{"rrMode": "ReclaimAll", "rrCascade": true}` returns what is left to the parent, archives the child and turns off the keys delegated to it. "Split / reclaim". "Integration modes" near the end has the same flow with its variants (waiting instead of failing, reporting-only meters, mixed buckets), and `GET /help` lists the `how-to-*` recipes. If an integration of yours predates the product's rename, read "Appendix: a note on names" at the end. --- ## What buckette is Think of buckette as **IAM for machine spenders**: IAM answers "what can this identity *do*"; buckette answers "how much can this identity *spend*, and can it prove it did." A bucket-scoped API key is a spend-scoped credential; a `split` is provisioning a sub-entitlement; `reclaim` revokes it. Where a single Redis/Postgres counter usually falls short isn't the counter itself — it's what happens once a request has to wait for capacity (retry it correctly when it frees up, expire it cleanly if it never does, notify exactly once) or once more than one resource has to move together atomically. What customers typically build on top of this: - **Bounded, self-revoking budgets per sub-agent or task run** — split a child bucket before dispatching work, hand it a bucket-scoped key that can't see or touch anything outside its own subtree, reclaim it when the run ends so the key stops working automatically. - **A cost bulkhead against runaway spend** — gate LLM calls or tool invocations on a `Locking` dimension so a bug or a bad loop fails fast and bounded instead of draining an account; get paged via threshold webhooks before it's fully depleted, not after. - **Cross-resource atomic spend** — one action that must debit two or more independent budgets together (a per-mailbox rate limit *and* a campaign quota; a token budget *and* a concurrency slot) via `claims`, without a hand-rolled multi-row transaction. - **Cryptographic proof of consumption for a party you don't trust with credentials** — an external biller, auditor, or customer verifies a signed receipt offline, against your tenant's public key, with no API access to your system at all. - **Fair scheduling under scarce, refilling capacity** — queue work that can't be funded yet (`Async` consume/claims) and let it resolve in priority order without one large request starving behind a stream of small ones. The rest of this doc explains the primitives (buckets, dimensions, modes) and wiring patterns (webhooks, async resolution, delegation, receipts) needed to build any of the above. One thing to know before you wire any callback: buckette will not deliver to an arbitrary URL. Both webhooks and per-request callbacks go through the checks in "Outbound destination validation" below — worth reading *before* your first `POST /webhooks` returns a 400 you weren't expecting. ## Core concepts ### Bucket A **bucket** is the unit of resource tracking. It holds one or more named **dimensions** (e.g. `tokens`, `requests`, `usd`), each with its own balance, optional cap, and unit label. Buckets form a tree via **split**/**reclaim**: a parent bucket can carve out a child bucket with its own sub-allocation, which is useful for handing a bounded budget to a sub-agent, a single run, or a single tool call, without letting it touch the parent's full balance. A bucket is the right level of granularity for anything you want to independently query, freeze, expire, or webhook on — e.g. "this agent run," "this user's monthly quota," "this tenant." A bucket can also be deleted outright (`DELETE /buckets/:id`), which is distinct from freezing or archiving it: deletion is permanent and takes the whole subtree with it. See "Deletion" below. **Rule for agents: every bucket you create gets a title.** Put `"metadata": {"buckette/bucket-title": ""}` in the `POST /buckets` or `POST /buckets/:id/split` request itself (`cbrMetadata` / `srMetadata`), not in a later `PATCH`. A person will look at your buckets in the Console, and a bucket without a title is shown as a bare id and a status, which tells them nothing. Three levels, in order of importance: - **Required: a title**, `buckette/bucket-title`, a short string such as `"run 4812: summarise inbox"`. - **Ideally: labels**, `buckette/labels`, an array of strings such as `["agent:triage", "env:prod"]`. They show as chips and are what the Console and `GET /buckets?label=` filter on. - **Bonus: a description and a link**, `buckette/description` (a sentence on what the bucket funds) and `buckette/link-url` (a URL to the task, ticket or dashboard the bucket serves). ```json { "cbrResources": {"tokens": {"raCurrent": 20000, "raMaximum": 20000, "raReserved": 0, "raUnit": "tok", "raMode": "Locking"}}, "cbrMetadata": { "buckette/bucket-title": "run 4812: summarise inbox", "buckette/labels": ["agent:triage", "env:prod"], "buckette/description": "Token budget for the nightly inbox summary run.", "buckette/link-url": "https://tickets.example.com/4812" } } ``` A split takes the same keys: `{"srAllocation": {"tokens": 20000}, "srMetadata": {"buckette/bucket-title": "run 4812: summarise inbox", "buckette/labels": ["agent:triage"]}}`. Remember that a later `PATCH /buckets/:id` replaces the whole metadata value (see below), so repeat the title and labels whenever you patch that way, or use `PATCH /buckets/:id/metadata` to change single keys. A bucket's `metadata` field is a free-form JSON object — buckette doesn't interpret it. A `buckette/`-prefixed key namespace is reserved for display-convention keys that *clients* (not buckette itself) read, e.g. `buckette/bucket-title`/`buckette/icon-url`/`buckette/description`/`buckette/link-url` for a human-readable label/icon/blurb/external-reference-link in a UI, and `buckette/promised` — an object of dimension name to a number, e.g. `{"buckette/promised": {"usd": 1000}}`, recording what was promised for a dimension so a later overshoot can be shown against it. Set at any time (including retroactively) via the same `PATCH /buckets/:id` metadata path as every other key here; compare it against `GET /buckets/:id/stats`'s `bsTotalConsumedAllTime` per dimension, not `bsTotalReplenishedAllTime`. Until the rename to buckette these keys were spelled `budgetz/`. Metadata is stored as sent and never rewritten, so a bucket written before the rename still returns the old keys. Every reader (the `?q=` and `?label=` filters, the `key` metric label, the Console, the CLI) looks for `buckette/` first and reads `budgetz/` only when that key is absent; when both are present the `buckette/` one wins. The old spelling is read until 2026-11-10. Write `buckette/`, and when reading a reserved key back, read the new spelling first and fall back to the old one: the Console and the CLI move a key to its new spelling the next time they write it. Keys that ride on an operation (`buckette/drain`, `buckette/withdrawn-by` in a consume's metadata, as seen in events and webhook payloads) are written under the new spelling only. An operation's own metadata (a consume's `crMetadata`, a replenish's, a reservation's, a transfer's or a claim's, recorded in its event's `details.metadata`) can carry four display keys that the Console's bucket Activity timeline reads, for that one row: `buckette/icon-url` (an image drawn in place of the event's marker, 16 px; the marker comes back when it does not load), `buckette/link-url` (the row links to it, opened in a new tab), `buckette/title` and `buckette/summary` (a line and a shorter line under the event's name). Both URLs must be `http` or `https`; any other value, and a value that is not a string, is ignored. For example `{"crAmounts": {"tokens": 1200}, "crMetadata": {"buckette/title": "Ticket 4812 answered", "buckette/link-url": "https://support.example.com/t/4812"}}`. See the `metadata` help topic (`GET /help/metadata`) for the full list and why the prefix is reserved — avoid it for your own metadata keys. A bucket's metadata can also carry two Tramaj templates that the Console draws in the bucket's panel (the language of the Console's Monitors Template widgets): `buckette/panel-template`, a string, drawn under the bucket's Info table with `$ctx.bucket` (the bucket, with the field names of a Monitors template: `bucketId`, `bucketTitle`, `bucketStatus`, `bucketResources`, `bucketMetadata`, ...), `$ctx.events` (its Activity as loaded, newest first) and `$ctx.templateFrom` (the id of the bucket that holds the template); and `buckette/activity-columns`, an array of `{"name": ..., "template": ...}`, each a column added to the Activity table and drawn once per event with that event as `$ctx.row` (`erEventType`, `erActor`, `erDetails`, `erOccurredAt`). A column may give an element or a plain value. Both are inherited: a bucket without the key uses its nearest ancestor's, and an empty string or an empty array turns off what an ancestor sets. For example `` {"buckette/panel-template": ".p(\"`$ctx.bucket.bucketTitle` is `$ctx.bucket.bucketStatus`\")", "buckette/activity-columns": [{"name": "actor", "template": "$ctx.row.erActor"}]} ``. Metadata is the cold half of a bucket: a consume never rewrites it. A bucket's own `metadata` (create/patch/split) is capped at 5KB of JSON; per-request metadata on consume/claim/claim-reservation calls is capped at 1KB. Both are rejected as a 400 `InvalidOperation` when exceeded. **`PATCH /buckets/:id` replaces the whole metadata value; it does not merge.** `{"pbrMetadata": {"buckette/bucket-title": "x"}}` leaves the bucket with exactly that one key: every key the request does not repeat is gone, your own keys and the reserved ones alike. To update one key without touching the others, use `PATCH /buckets/:id/metadata` (below). The three cases of the `pbrMetadata` field: - `pbrMetadata` absent, or an explicit `null`: metadata is left as it is. - `pbrMetadata` set to a value: that value becomes the bucket's metadata. `{}` empties it. - `pbrClearMetadata: true`: metadata becomes JSON `null`, and a `pbrMetadata` sent in the same request is ignored. **A `PATCH /buckets/:id` can be made conditional.** Every bucket carries `bucketConfigVersion`, which moves on every configuration change: each `PATCH /buckets/:id` that changes something (dimension edits included), `PATCH /buckets/:id/metadata`, and the config `PUT`s (replenishment, thresholds, classes, unspent warning, top-up). A consume, a replenish or a hold does not move it. Send the value you read back as `pbrIfConfigVersion` and the PATCH applies only if the bucket is still at it; otherwise it answers `409 config_version_mismatch` and changes nothing. Read the bucket again, reapply your edit, and retry. This is for a writer that edits a whole object (the metadata) and writes it back; without the field the PATCH is unconditional, as before. ``` GET /buckets/:id {..., "bucketConfigVersion": 7, ...} PATCH /buckets/:id {"pbrMetadata": {...}, "pbrIfConfigVersion": 7} ``` **`PATCH /buckets/:id/metadata` updates keys atomically** (`ScopeAdmin`, like `PATCH /buckets/:id`). The body is the patch itself, a JSON Merge Patch (RFC 7396), not the `pbr*` envelope; the response is the resulting metadata value. ``` PATCH /buckets/:id/metadata {"buckette/bucket-title": "x", "old-key": null} ``` - A member set to a value sets that key and leaves every other key alone. - A member set to `null` removes that key. So a key cannot be set to `null` through this route. - An object member is merged into the stored object recursively: `{"buckette/promised": {"usd": 1200}}` changes `usd` and keeps the other dimensions; `{"buckette/promised": {"usd": null}}` removes one. - Arrays and other values replace. Two writers that each add a label to `buckette/labels` still race on that one key. - A body that is not an object (an array, a string) replaces the whole metadata value. Stored metadata that is `null` or not an object is treated as `{}` first. - The server reads and writes the row under a lock in one transaction, so two writers patching different keys cannot undo each other. The 5KB cap applies to the merged result. - The server does not know the `buckette/` names and rewrites no key. When you set `buckette/` on a bucket that still carries `budgetz/`, name both: `{"buckette/bucket-title": "x", "budgetz/bucket-title": null}`. - An older instance answers 404 (the route does not exist) rather than ignoring the call. `PATCH /buckets/:id` has no conditional write (no version or `If-Match` precondition): two writers that each read the whole object and send it back with `pbrMetadata` still end with the second writer's object, and the first writer's change is lost without an error. Use the merge route for that. #### Idempotent bucket creation (`cbrIdempotencyKey`) `POST /buckets` can carry an optional `cbrIdempotencyKey :: Text` — a caller-chosen key, not generated by buckette. This matters any time your own provisioning logic can run concurrently for the same logical entity — e.g. a "find-or-create the bucket for project X" flow where two requests both find no bucket yet and race to create one. Without a key, that race can create two buckets; with one, the second call is a safe no-op that returns the *same* bucket the first call created, not an error and not a duplicate. The key is **scoped per tenant** (not global, and not per-parent-bucket) — two different tenants can safely reuse the identical key string and get two independent buckets. Pick something that already identifies the real-world entity you're provisioning a bucket for (an external project id, a deterministic string you derive yourself), not a random value per attempt — a random value defeats the point, since every retry would look like a brand-new entity. Internally this is enforced by a unique index on `(tenant_id, idempotency_key)`, checked atomically at insert time, so it's safe under concurrent duplicate calls, not just sequential retries — the same posture as `repTransactionId` on replenish (see "Idempotent on-demand replenishment" below), applied to creation instead of a balance mutation. A repeat call with the same key returns the *original* bucket's response body unchanged — no new `bucket.created` event, no new webhook delivery — even if other fields in the repeat request body differ from the original call; only the key is checked. Deleting a bucket frees its key for reuse. The key is echoed back on every read as `bucketIdempotencyKey`, so a later `GET /buckets/:id` can confirm which key produced it. #### Idempotent split (`srIdempotencyKey`) `POST /buckets/:id/split` can carry an optional `srIdempotencyKey :: Text`, the same shape as `cbrIdempotencyKey` above (a caller-chosen key, not generated by buckette), for the same class of problem: a retried or concurrently-duplicated split must not mint a second child or debit the parent twice. Two differences from `cbrIdempotencyKey`, both because a split moves a balance rather than creating an empty bucket: - **Scoped per tenant *and* per parent bucket**, not per tenant alone — the same key string against two different parents produces two independent children, since the key is meant to identify one specific split operation off one specific parent, not a tenant-wide slot. - **A replay with a different request body is rejected with `409 idempotency_key_conflict`**, not silently ignored. `cbrIdempotencyKey` ignores body differences because a repeat create with the same key is meant to be a no-op regardless of what else was sent; a split's body determines how much money moves, so a caller accidentally reusing a key across two different requests is a bug worth surfacing rather than masking. A matching replay (same key, same parent, same request body) returns the *original* split's response unchanged — same child id, and the parent's *current* resources (which may have moved since the original split from unrelated activity — that's correct, not a frozen snapshot) — with no new `bucket.split` event and no new webhook delivery. **A split key is remembered for as long as its parent bucket exists. It does not expire.** This is unlike `crIdempotencyKey` below, which is forgotten after seven days: however much later the same key comes back against the same parent, it is a replay (or a `409` if the body differs) and never a second split. The child's fate does not matter — archive it, reclaim it or delete it, and the key still answers with that child's id (which then reads as archived, or `404`). So a key is safe to use as a permanent "this was already granted" marker, and a key string cannot be reused for a different split of the same parent. The record goes away in exactly two cases: the parent bucket is deleted (`DELETE /buckets/:id` on it or on an ancestor), after which a split against it is a `404` whatever the key, or the whole tenant is torn down. #### Idempotent consume (`crIdempotencyKey`) `POST /buckets/:id/consume` can carry an optional `crIdempotencyKey :: Text`, the same shape as `cbrIdempotencyKey`/`srIdempotencyKey` above (a caller-chosen key, not generated by buckette) — scoped **per tenant and per bucket**, like `srIdempotencyKey`. **Read this before relying on it — a consume key is stricter than bucket creation, and a mismatch is an error, not a replay:** - The **first** `consume` call under a given key runs for real, and its outcome — success (with the exact amounts consumed) or shortfall — is recorded, together with a fingerprint of the request: its `crAmounts` and its consume class (`crClass`). - **A later call reusing that key against the same bucket, with the same amounts and class, replays that first recorded outcome byte-for-byte.** It does not re-run the consume and does not emit a new `bucket.consumed` event or webhook. The mode (`crMode`), metadata, `crNonce` and callback are **not** compared: a retry may wait differently, and the replay answers with the first call's outcome (and receipt) whatever they say. - **A later call with different amounts or a different class answers `409` `idempotency_key_mismatch`** and runs nothing. A key reused with `{"crAmounts": {"usd": 1}}` the first time and `{"crAmounts": {"usd": 1000000}}` the second is a client bug, and it is reported as one. (Until 2026-11-06 this silently replayed the first outcome; a key recorded before that date has no fingerprint and still replays whatever the retry says, until its seven days are up.) Derive the key from something that uniquely identifies the one real-world consumption you're deduping (e.g. an upstream request id), never a constant or a loop counter. - **A key is remembered for seven days, counted from the first call under it. After that the same key is a new consume.** buckette deletes the recorded outcome once it is seven days old, and from then on a call carrying that key runs for real: it deducts again, emits a new `bucket.consumed` event and webhook, and is recorded afresh for another seven days. A replay does not extend the seven days. So the guarantee is "at most once per key **within seven days of the first call**", not forever: keep every retry of one real-world consumption inside that window (an hour-long retry loop is fine; replaying a week-old queue is not), and never rely on a key to dedupe a charge you might re-send later than that. Deletion runs in the background, so a key may still replay for a short while past the seven days; don't rely on that either. The window is fixed — not configurable per request, tenant or instance. A key's record also goes when its bucket is deleted (`DELETE /buckets/:id`), but by then the bucket answers 404 to a consume anyway. - A recorded **shortfall** outcome replays too, not just success — a caller retrying a failed consume with the same key gets told the same shortfall again rather than getting a fresh (possibly now-succeeding) attempt. Drop the key (or use a new one) to actually retry after replenishment. - Applies uniformly across `crMode` — `Strict`, `Partial`, `Wait`, and `Async` all record and replay whatever outcome they would otherwise return (for `Async`, that's the immediate `ConsumePending`/success/ shortfall response to *this* call, not the eventual scheduler-driven completion). - Omitting the key (the common case, and every caller's behavior before this field existed) means no dedup at all — every call executes fresh, exactly as before. - Safe under genuinely concurrent duplicate calls, not just sequential retries, and both calls normally get the same answer. How the duplicate waits depends on the first call's mode: - **First call `Strict` or `Partial`:** recording the key, the consume, the recorded outcome and the shortfall event (if any) commit together, as one write. A duplicate that arrives while the first is in flight **waits for it to finish, however long that takes, and then replays its outcome**: no polling, no timeout of its own beyond the request's. If the first call fails with an error (not a shortfall: a `404`, a frozen bucket, a database error), nothing was recorded under the key and the waiting duplicate runs for real. A key is never left half-recorded by a crash. - **First call `Wait` or `Async`:** the key is recorded before the work starts, because that work can take seconds. A duplicate checks for the outcome every half second for up to ~10s, then answers `500` if the first call is still running; retry in that case, same as any other `500`. #### Logging shortfalls (`bucket.consume_shortfall`) A starved bucket otherwise leaves no trace — the event log only ever recorded successful mutations, so a bucket refusing consume after consume looked exactly like one nobody was asking anything of. buckette logs a `bucket.consume_shortfall` event when a `Strict` request fails outright, a `Wait` request gives up after `wcMaxDelaySecs`, a `Partial` request still leaves some dimension short after consuming what it could, or a request is refused because the bucket has run out (`Depleted`, see "Running out is a shortfall too" below) — **but only when `crIdempotencyKey` was set on that same request, and only from the call that actually ran it.** This rides entirely on the idempotent-consume mechanism just described, rather than a separate dedup table: the *first* call under a given key is the only one that ever executes the request for real, so it is the only call that can ever produce a shortfall to log. Every later call reusing that key is a pure replay of the recorded outcome and never re-logs anything — not because of a second check, but because a replay never reaches the code path that logs at all. Concretely: - **No key means no event, on purpose.** Logging every shortfall unconditionally would let a client's retry loop against a starved bucket flood the event log with one entry per attempt; requiring a key (which also makes the *consume itself* idempotent, see above) is the mitigation. - **One event per key, by construction.** A client retrying an unsatisfiable request three times under one key produces exactly one `bucket.consume_shortfall` event (the first call's), the same way it produces exactly one recorded `ConsumeOutcome` — there is nothing extra to coalesce. Reusing a fresh key per logical attempt gets you one event per attempt instead, exactly as it gets you one real consume attempt per key. - **`Async` mode is excluded** — its shortfall is already recorded as `bucket.consume_pending`, and double-logging the same demand under two event kinds would make the two harder to reconcile, not easier. - **`POST /buckets/:id/check` never logs anything**, key or not, since it never goes through the idempotent-consume path at all and its whole point is to be a side-effect-free preview. A `bucket.consume_shortfall` event's `details` carries `requested`, `available`, `shortfall` (all per-dimension maps), `mode` (`"strict"`/`"partial"`/`"wait"`), `idempotency_key`, and `metadata` (the request's `crMetadata`, if any) — visible via `GET /buckets/:id/events` like any other event, and subject to the same retention as every other event (see "History retention" below; there is nothing special-cased for this event kind). **It is a webhook too.** Each of those log lines is also delivered, once, as a `bucket.consume_shortfall` webhook with the same `details`: ```json {"event": "bucket.consume_shortfall", "bucket_id": "...", "details": { "requested": {"tokens": 50}, "available": {}, "shortfall": {"tokens": 20}, "mode": "strict", "idempotency_key": "job-7/attempt-1", "metadata": {"job": "job-7"}}} ``` - **One delivery per log line**, so everything above holds for the webhook: a retry on the same key fires nothing, a consume with no key fires nothing, `Async` and `/check` fire nothing. A `Partial` that fell short fires it next to its `bucket.consumed`. - **It is per request, not a digest.** A caller that sends a fresh key with every attempt against a starved bucket gets one POST per attempt, up to its rate limit. Keep one key per logical piece of work, or read the aggregate (`GET /buckets/consume-shortfalls`, `bsTotalShortfallAllTime`) when the count matters more than each case. - Under a consume class the details also carry `class`, `floor` and, when the floor is what refused the request, `reason: "protected"`: do not page somebody to raise an allowance for those. - No setting on the bucket: subscribe a webhook to the event name (or to everything, with an empty `cwrEvents`). To see unmet demand in aggregate rather than event-by-event, `GET /buckets/consume-shortfalls?window_days=N` (`ScopeRead`, tenant-scoped, scope-root-honouring, same window clamp as `/buckets/flows` and `/buckets/recency`) returns one row per bucket and dimension with a shortfall in the window: `{"cstBucket", "cstDimension", "cstShortfall" (summed), "cstEvents" (count)}`. It only sees what got logged, so a tenant that never sets `crIdempotencyKey` sees nothing here even while starved. For the total rather than a window, `GET /buckets/:id/stats` carries two **accumulated shortfall totals** per dimension, kept on the bucket row the same way as `bsTotalConsumedAllTime` — one read, nothing to fold, and they outlive event-log retention: - `bsTotalShortfallAllTime` — consumes that carried a `crIdempotencyKey`. **Exact**: a key runs once (within its seven-day window, see "Idempotent consume" above), so a retried consume adds its shortfall once. It is bumped in the transaction that writes the `bucket.consume_shortfall` event, so it is always the sum of those events. - `bsTotalShortfallUnkeyedAllTime` — consumes that carried no key. Nothing tells a retry from new demand there, so every refused request adds its shortfall again: an **upper bound** on unmet demand, to be read as an overestimation. No event is written for these (see above), so this total is the only trace an unkeyed shortfall leaves. A consume counts in exactly one of the two. Both cover the same cases as the event — a `Strict` refusal, a `Wait` that gave up (once per request, not per poll), the unmet remainder of a `Partial`, and a refusal because the bucket ran out (below) — and exclude the same ones (`Async`, `/check`), as well as reservations and claims. Both are **direct**: a bucket's totals never include its descendants'. Both **start at zero** on the day the feature shipped (2026-10): shortfalls logged before that are not backfilled. **Running out is a shortfall too** (since 2026-10-15). A consume against a `Depleted` bucket (every `Locking` dimension at zero) is still refused with `depleted` (422; before 2026-10-31 the code was `bucket_not_active`, kept in `details.legacyCode`; its message says the bucket "has run out", and `details.reason` is `depleted`), but the demand is recorded: everything the request asked of a `Locking` dimension is its shortfall, with `available` zero. Unkeyed, it adds to the unkeyed total; with a `crIdempotencyKey`, it writes one `bucket.consume_shortfall` event and webhook and adds to the keyed total, once per key — **and the key keeps the refusal**: a retry under the same key answers the same `depleted`, even after a refill, the way a recorded shortfall replays. Use a new key for a new attempt. `Wait` is refused at once (and counted once); `Async` is not refused at all but queued as a pending consume (see the mode table under "Consume modes"), which is not a shortfall. A request that asks nothing of a `Locking` dimension has nothing to count. Totals before that date do not include these refusals. **Refused reservations and claims have totals of their own** (since 2026-10-20). `GET /buckets/:id/stats` also carries: - `bsTotalReserveShortfallAllTime` — demand refused to `POST /buckets/:id/reserve` on this bucket: the unmet part of a refused `Strict` reservation or of a `Wait` that gave up (once per request), the unmet remainder of a `Partial`, and, for a reservation refused because the bucket ran out (`depleted`), what it asked of a `Locking` dimension. - `bsTotalClaimShortfallAllTime` — the same for `POST /claims` and `POST /claim-reservations`, booked on **each target that was short**: an `AllOf` refusal on every target that lacked balance, a `FirstOf` refusal on every candidate it was refused by (so a sum across buckets counts that claim once per candidate), a `Partial` grant's unmet remainder per target, and a target that had run out. Neither is ever added to the consume totals above; add them yourself if you want one figure for all refused demand. A refused reservation or claim claims no idempotency key, so **every refused request adds, retries included**: both are upper bounds, like the unkeyed consume total. Each booking also writes an event in the same transaction and fires a webhook of the same name (since 2026-10-24): `bucket.reserve_shortfall` for a reservation, `bucket.claim_shortfall` for a claim or claim reservation, one per bucket short, one per refused request (no key coalesces them); their details are in `GET /help/events`. They exclude `Async` (that demand is a pending row), `/claims/check`, and Frozen or Archived refusals; the answer the caller gets is unchanged. Direct, and zero before that date. **Refused transfers have a total of their own too** (since 2026-11-09). `bsTotalTransferShortfallAllTime` is what `POST /transfers` asked of this bucket as its **source** and was refused because the source lacked it: the source's `toShortfall` of a refused `Strict` transfer or of a `Wait` that gave up (once per request), everything a transfer refused on a `Depleted` source asked, and the shortfall of an `Async` transfer that reached its deadline with the source still short. A transfer sent with `trTransactionId` is counted **once per id** (exact; a retry under the same id adds nothing); one sent without adds on every refused request (an upper bound). Each booking writes `bucket.transfer_shortfall` on the source and fires the webhook of that name. Not counted: a transfer refused because the destination had no room (the source had it), a Frozen or Archived source, scope, an invalid body or mode. **The reason is the total.** Each reason a request went unmet has its own total and its own event, never added to another: keyed consume (`bsTotalShortfallAllTime`, `bucket.consume_shortfall`), unkeyed consume (`bsTotalShortfallUnkeyedAllTime`, no event), reservation (`bsTotalReserveShortfallAllTime`, `bucket.reserve_shortfall`), claim (`bsTotalClaimShortfallAllTime`, `bucket.claim_shortfall`), transfer (`bsTotalTransferShortfallAllTime`, `bucket.transfer_shortfall`). Read one reason's lines with `GET /buckets/:id/events?event_type=`. **Which buckets have the largest totals.** None of the five totals above is in a windowed aggregate (and the unkeyed consume one leaves no event), so `GET /buckets/shortfall-ranking?limit=N` (`ScopeRead`, tenant-scoped, scope-root-honouring, all time) ranks them: for each of the five totals and each dimension, the `N` buckets with the largest non-zero amount (default 20, clamped to 1..200), answered as one row per bucket and dimension that made at least one cut, with all five amounts in that dimension, one column per reason: ```json {"sfkLimit": 20, "sfkBucketsWithShortfall": 3, "sfkRows": [{"srrBucket": "…", "srrDimension": "tokens", "srrConsume": 0, "srrConsumeUnkeyed": 7, "srrReserve": 10, "srrClaim": 2, "srrTransfer": 5}]} ``` `sfkBucketsWithShortfall` counts every bucket the key reaches with any non-zero total; when it equals the number of distinct buckets in `sfkRows`, nothing was cut. Rows are ordered by dimension, then by the five amounts summed (a sum across kinds that mixes an exact figure with upper bounds: use it to order, not to report). For the most recent shortfalls on one bucket, `GET /buckets/:id/events?event_type=bucket.consume_shortfall&limit=20`. ### Dimension Each dimension in a bucket is an independent counter: ```json { "raCurrent": 10000, "raMaximum": 10000, "raReserved": 0, "raUnit": "tok", "raMode": "Locking" } ``` - `raCurrent` — the live balance. - `raMaximum` — optional cap; also defines the `overflow` threshold (see below). Omit it, or send `null`, for an uncapped counter; responses always carry the key, as `null` when there is no cap. - `raReserved` — amount held by open reservations (see **Reserve** below); not directly settable. - `raAvailable` — on reads only: `raCurrent - raReserved`, what is free once the open holds are kept aside. Derived each time a bucket is read (bucket reads and lists, consume and reserve responses, webhook payloads), never stored, and ignored if a request sends it. It is not clamped (a `Reporting` or `MeteredOverage` dimension below zero reads below zero) and a consume class floor is not subtracted from it; `POST /buckets/:id/check` answers what one request may take. - `raUnit` — free-text label (`"tok"`, `"req"`, `"usd"`) for display only. - `raMode` — `"Locking"` (default), `"Reporting"` or `"MeteredOverage"`; see next section. - `raOverageLimit` — `MeteredOverage` only: how far below zero consumption may take the balance (the credit line). Absent from responses when there is none; refused on the other modes. A `consume` or `replenish` call can touch several dimensions of the same bucket atomically in one request — e.g. deduct both `tokens` and `requests` for a single LLM call, and either both succeed or (in `Strict` mode) neither does. ### Locking vs. Reporting mode (`raMode`) This is the key modeling decision for any dimension: **do you want buckette to gate the operation, or just track it?** - **`Locking`** (default) — the dimension participates in availability checks. `Strict`/`Wait`/`Async` consume modes reject when this dimension is short; `Partial` clamps to what's available. Use this for anything that must act as a hard limit — a cost cap, a concurrency slot, a rate quota. - **`Reporting`** — the dimension never blocks or clamps. Consumption always applies in full, and the balance may go negative or exceed `raMaximum`. Use this for anything you want to *measure* without gating on it — e.g. tracking total tokens spent per user for analytics/billing while the actual spend limit is enforced on a separate `Locking` dimension. Mode is set **per dimension**, so a single bucket can mix both — e.g. `usd` as `Locking` (hard spend cap that blocks further calls) alongside `tokens_reported` as `Reporting` (pure usage metric, never blocks). Consume requests don't choose a mode themselves; each dimension in the bucket always behaves according to its own `raMode`, regardless of `crMode` in the request. `raMaximum` stays meaningful for `Reporting` dimensions even though it no longer caps consumption — it defines the threshold at which the `overflow` event fires (see below), so you still get notified when a reporting-only counter exceeds its expected ceiling. ### Metered overage (`raMode: "MeteredOverage"`) The third mode is for an integrator who **meters their own customers**: an included allowance, then overage they bill for. Consumption first spends the balance, then may take it **below zero**, down to `-raOverageLimit`; past that line it is refused exactly as a `Locking` dimension is refused at zero. With no `raOverageLimit` it is never refused ("always serve, always bill"). ```json {"cbrResources": {"tokens": {"raCurrent": 1000, "raMaximum": 1000, "raReserved": 0, "raUnit": "tok", "raMode": "MeteredOverage", "raOverageLimit": 500}}} ``` - **The overage is measured, per deduction.** The part of each deduction that took the balance below zero is the overage: `coOverage` on the consume response (absent when there is none), `overage` on the `bucket.consumed` record, `dpOverage` / `lfOverage` in the per-period ledger and `bsTotalOverageAllTime` in `GET /buckets/:id/stats`, split by consume class as `cfOverage` in the ledger's classes, the counter `buckette_bucket_overage_total` in the Prometheus export and the `.overage` column of the CSV ledger export. It is a **part** of consumed, not an addition. Bill from `dpOverage`, not from the low-water mark: a top-up in the middle of a period would hide spending from `low`. - `Partial` clamps at the line; `Wait`/`Async`, `/check` and `coEta` all answer against the line. A hold (`reserve`) may reach into the overage, and the overage is measured when it is **committed**, against the balance then. - The bucket is `Depleted` when the dimension is **at its line** (never without a line), and a top-up that lifts it above the line wakes it. - **At a scheduled reset**, carry-over decides the debt: `CarryoverNone` forgives it (the next period starts from the dose; the debt is booked as `forgiven` — `dpForgiven`, `bsTotalForgivenAllTime`, `forgiven` in the `bucket.replenished` details, `buckette_bucket_forgiven_total` and the `.forgiven` CSV column — beside discarded, not part of it); `CarryoverLimited`/`CarryoverUnlimited` carry it, and the dose pays it first. - **Splits hand down budget, not debt**: a split allocates from the positive balance only; the child inherits the mode and the line. A reclaim or a delete never moves a child's debt to its parent: it stays on the child. - **Claims**: a `MeteredOverage` target can pay down to its line, so in `FirstOf` it is eligible while it has line left (put it last to make it the fallback). `MostAvailable` ranks targets that stay at or above zero before any that would go into overage, then by headroom (which counts the line). - **Consume classes** share the line: a class floor is counted above the floor of the gate, as it is for `Locking`. - **Thresholds**: `bucket.overage` fires when the dimension goes below zero (once per dip) and `bucket.overage_cleared` when it is back at zero or above (a top-up or a reset); `low`/`critical` work as for `Locking`; `depleted` is at the line. A manual top-up that writes debt off says so in `repForgiven`. - Change the line with `PATCH /buckets/:id` `{"pbrOverageLimits": {"tokens": 200}}` (`null` removes it). Lowering it below the current debt is allowed and simply refuses further consumption until the balance is back above it. A dimension with a negative balance cannot be removed. Without the mode, the closest composition is a claim `FirstOf InOrder [included, overage]`; it picks **one** bucket per request, so a request larger than what is left in `included` goes entirely to `overage` and overstates the bill. The mode measures the split on one bucket. ### Freezing a bucket `PATCH /buckets/:id` with `{"pbrStatus": "Frozen"}` freezes an `Active` or `Depleted` bucket; `{"pbrStatus": "Active"}` unfreezes it. A freeze stops spending, not bookkeeping: - **Spending is refused, at once.** A consume and `POST .../check` answer `422 bucket_not_active` in every mode; a `Wait` consume does not wait for an unfreeze. A reserve and a split of the frozen bucket are refused the same way. (An `Async` consume or reserve registered before the freeze keeps waiting; one asked for after it is refused; see the queued intents below.) - **A hold taken before the freeze still settles.** Its refresh, commit and cancel work as before: the freeze does not void or trap it. - **Credits still land.** A manual `POST .../replenish` is applied and the bucket stays `Frozen`; a reclaim of one of its children credits it. A scheduled replenishment is skipped while the bucket is frozen. - **It can still end.** A reclaim archives a frozen bucket, and so does its expiry. - **A freeze reaches every live descendant**; an unfreeze does not: each child is unfrozen on its own. - **Unfreezing goes back to what the balance says**: `Depleted` when every `Locking` dimension is at zero (a `Reporting` one does not count), else `Active`. - **Each one is an event.** A freeze is recorded and delivered as `bucket.frozen`, on the bucket the PATCH named, with `descendants` (how many the cascade reached; they get no event of their own); an unfreeze as `bucket.unfrozen`, with the `status` it went back to. Both carry `previous_status`, `status`, `actor` (the key) and, when the PATCH sent `pbrStatusReason` (free text, up to 500 characters, only with `pbrStatus`), `reason`. `GET /help/events` has the details. ### Adding a dimension to an existing bucket `PATCH /buckets/:id` (`ScopeAdmin`) with `pbrAddDimensions` adds dimensions to a live bucket, in exactly the per-dimension shape `POST /buckets` takes: ```json {"pbrAddDimensions": {"usd": {"raCurrent": 0, "raMaximum": null, "raReserved": 0, "raUnit": "usd", "raMode": "Reporting"}}} ``` - A name already on the bucket is **rejected**, never overwritten — use `pbrResourceLimits` to change an existing dimension's cap. The whole PATCH is all-or-nothing: a rejected addition applies none of the request. - `raCurrent` and `raReserved` must be non-negative, and `raReserved` must be `0` (no reservation can hold a dimension that didn't exist yet). - `pbrResourceLimits` in the same request can cap a dimension it adds. - Adding a positive `Locking` dimension to a `Depleted` bucket makes it `Active` again. A `Frozen` bucket stays frozen. - **No cascade.** Existing child buckets keep the dimension set they were split with; add the dimension to each child that needs it. - The new dimension has no history: `GET /buckets/:id/stats` totals simply don't list it until something consumes or replenishes it. Each added dimension logs one `bucket.dimension_added` event (`{"dimension", "resource"}`) to `GET /buckets/:id/events`. ### Flipping a dimension between modes `PATCH /buckets/:id` (`ScopeAdmin`) with `pbrDimensionMode` flips an existing dimension's `raMode`: ```json {"pbrDimensionMode": {"usd": {"dmcMode": "Locking", "dmcResetCurrent": 0, "dmcConfirmDemote": false}}} ``` - A name not on the bucket is **rejected**; add it first with `pbrAddDimensions` (applied first, so both can land in one request). - **Promoting to `Locking`**: if `raCurrent` is negative, or positive but over `raMaximum`, the flip is rejected unless you also pass `dmcResetCurrent` (a non-negative starting balance) — otherwise every future consume against a dimension that was tracking-only would instantly read as already exhausted. If the balance is already non-negative and within `raMaximum`, the flip needs no reset, and passing `dmcResetCurrent` anyway is rejected as unneeded. - **Demoting to `Reporting`**: requires `dmcConfirmDemote: true` — the failure mode here is silent (the dimension stops gating consumption), not a data hazard, so this is a confirmation flag rather than a balance check. `dmcResetCurrent` doesn't apply to this direction and is rejected if set. - Flipping a dimension already in the target mode is a no-op (still subject to the same `dmcResetCurrent`/`dmcConfirmDemote` "not needed" rejections above, to catch a stale request rather than silently ignore it). - **No cascade.** Only this bucket's mode changes; already-split children keep whatever mode they inherited at split time. - **To and from `MeteredOverage`**: `dmcOverageLimit` sets the line with the flip (rejected with the other two modes). `Locking` -> `MeteredOverage` is always allowed. `Reporting` -> `MeteredOverage` needs `dmcResetCurrent` only when the balance is below the new line (or over `raMaximum`). `MeteredOverage` -> `Locking` needs it when the balance is negative, and drops the line. `MeteredOverage` -> `Reporting` needs `dmcConfirmDemote: true`, as from `Locking`. - Each flipped dimension logs one `bucket.dimension_mode_changed` event (`{"dimension", "mode", "resetCurrent"}`, plus `overageLimit` when set) to `GET /buckets/:id/events`; a `pbrOverageLimits` change logs `bucket.overage_limit_changed` (`{"dimension", "overageLimit"}`). ### Consume modes (`crMode`) Set per request, applies to all `Locking` dimensions in that request (`Reporting` dimensions ignore it and always succeed in full): | Mode | Behavior on shortfall | |---|---| | `Strict` | Reject the whole request; no dimension is touched. | | `Partial` | Consume as much as is available per dimension; never fails. | | `Wait` | Poll up to `wcMaxDelaySecs`, then behave like `Strict`. | | `Async` | Behave like `Strict` initially; on shortfall, register a pending intent (`PendingConsume`) instead of failing — see **Async consumption** next. | `Async` also queues on a `Depleted` bucket (one that has run out), where every other mode is refused with `depleted`: the response is a `ConsumePending` whose shortfall is everything asked of a `Locking` dimension, and the scheduler serves it once a replenishment run or a top-up reactivates the bucket (since 2026-10-17). Only a credit that leaves a `Locking` dimension above zero (a `MeteredOverage` one above its line) reactivates it; a credit to a `Reporting` dimension alone leaves it `Depleted` (since 2026-10-20). A `Frozen` or `Archived` bucket is still refused in every mode, `Async` included, and so is a `Depleted` one on `/check`. #### The order the waiting queues are served in Four kinds of request wait in queues: queued (`Async`) consumes, queued reserves, queued claims and queued claim reservations. The queues are kept apart, and each 30 s tick serves them one after the other, always in this order: 1. queued consumes (`crMode: Async`), soonest deadline first; 2. queued reserves (`rrvMode: Async`), soonest deadline first; 3. queued claims, by `clrPriority` (see "Queued claims"); 4. queued claim reservations, by `clrrPriority`. In the first two, every intent its bucket can cover is served, and one that cannot does not hold the bucket against the ones behind it. So **a queued consume on a bucket is served before a queued claim on that bucket, whatever the claim's priority**: when a top-up makes room for one of them, the consume gets it. A claim's place in line (`ciQueuePosition`) counts the queued consumes and reserves on its buckets for that reason (`ciIntentsAhead`). To have a request take its turn by priority, queue it as a claim (a one-target `AllOf` is a single-bucket consume). ### When could it succeed? (`coEta`) A `ConsumeShortfall` (and a `ConsumePending`) carries `coEta`: the earliest time the bucket's own replenishment schedule could cover the request, per short dimension (`seDimensions`) and overall (`seOverall`, the long pole). Each answer is one of: - `{"tag": "EtaAt", "eaSeconds": 7980, "eaAtUnix": 1790000000}`, seconds from now and the same instant as a unix timestamp. - `{"tag": "EtaNever", "eaReason": ...}`: waiting never closes the gap. Reasons: `ExceedsMaximum`, `ExceedsCarryoverNone`, `ExceedsCarryoverLimited` (the balance can never hold that much), `OverflowRejectStall` (`OverflowReject` will start skipping runs first), `AfterExpiry`, `BucketArchived`, `BucketDepleted` (the bucket is `Depleted`, so the gate refuses with `depleted`, and no scheduled run will reactivate it: no schedule or next run, it expires first, or the run credits no Locking or MeteredOverage dimension; a manual replenish of one would). Never on a `ConsumePending`: see below. - `{"tag": "EtaUnknown", "eaReason": ...}`: scheduled replenishment doesn't get there, but something else might. Reasons: `NoSchedule`, `NoReplenishAmount`, `NotYetScheduled`, `BucketFrozen`, `HeldByReservations`, `HeldByClassFloor` (the request's consume class protects the balance with a floor that does not release in time, e.g. `release: none`; no reservation is involved). The ETA agrees with the consume gate: for a `Depleted` bucket it is never "now" even when the requested dimensions have balance (or are `Reporting`); it is the next replenishment run, the one that reactivates the bucket (or the later run that covers a short dimension), or `EtaNever`/`BucketDepleted`. An `Async` consume queued on a `Depleted` bucket (a `ConsumePending`) waits, and a top-up or a manual replenishment serves it as well as a scheduled run. So when no scheduled run will reactivate the bucket its ETA is `EtaUnknown` (`NoSchedule`, `NotYetScheduled`, or `NoReplenishAmount` when the run credits no Locking or MeteredOverage dimension), as for an `Active` bucket without a schedule, never `EtaNever`/`BucketDepleted`; a bucket that expires before its next run is `EtaNever`/`AfterExpiry` (since 2026-10-24). `POST /buckets/:id/eta` keeps the answer above: it is asked for a consume that the gate would refuse. Overall is `EtaNever` if any dimension is, else `EtaUnknown` if any is, else the latest `EtaAt`. It is a **lower bound**: it assumes nothing else consumes in the meantime and ignores the scheduler's 30s tick. It describes the bucket consumed from only, never its ancestors. To ask before trying, `POST /buckets/:id/eta {"etqAmounts": {"tokens": 500}}` (`ScopeRead`, read-only) returns the same `ShortfallEta`; for a request that fits now it is `EtaAt` with `eaSeconds: 0` and no dimensions. Use it to pick between `Wait` (seconds away), `Async` (hours away), and giving up (`EtaNever`). ### Consume classes and protection floors (`crClass`) A budget often has several ways to be spent that are not worth the same: interactive requests and a batch job on one monthly allowance. If the batch job runs first and takes everything, interactive work is refused until the reset; if the batch job is forbidden, what interactive work leaves unused expires. A **consume class** lets the bucket hold part of its balance back from the lower-value work early in the period, and release it as the reset approaches. There is no timer, no cushion bucket and no order of preference to keep in your own code. **A request names a class.** `consume` and `check` take an optional `crClass`, a short name (1 to 64 characters out of `A-Z a-z 0-9 . _ -`): ```json {"crAmounts": {"tokens": 50000}, "crMode": {"tag": "Strict"}, "crClass": "batch"} ``` **A bucket declares its classes** with `PUT /buckets/:id/class-config` (`ScopeAdmin`; the body replaces the whole declaration, and the response is the bucket, which carries it as `bucketClassConfig`): ```json { "classes": { "interactive": {}, "batch": {"tokens": {"floor": 400000, "release": "linear"}}, "backfill": {"tokens": {"floor": 800000, "release": "step", "lead_seconds": 259200}} }, "default_class": "batch" } ``` Per class and dimension, a **floor**: a consume of that class succeeds only if what it leaves available is at or above the floor. ``` allowed <=> (raCurrent - raReserved) - requested >= floor(class, dimension, now) ``` A class declared as `{}` has no floor and may spend everything. No order between classes is declared anywhere: it follows from the floors. `release` says how a floor goes down over the bucket's replenishment period (the time between two scheduled runs): | `release` | Floor at time t | For | |---|---|---| | `none` | constant | a set-aside that never opens | | `linear` | `floor x (time left before the next run / period length)` | the default when `release` is omitted: protection shrinks as the period runs out | | `step` with `lead_seconds` | the whole floor until `lead_seconds` before the next run, then zero | "batch may take the leftover in the last three days" | A bucket with no replenishment schedule has no period, and only `none` is accepted on it (say it explicitly, since an omitted `release` is `linear`). A floor names one of the bucket's own dimensions; `PUT` refuses anything else with `invalid_class_config`. **Which class a request is in** is decided in two steps. 1. *The key.* A key may list the classes it may name (`cakreClasses` on `POST /api-keys`; shown as `cakrClasses` / `akiClasses`). An empty list means all, which is every key that names none. A key limited to one class consumes as that class when `crClass` is omitted. A key limited to several must name one (`400 class_required`). Naming a class outside the list is `403 class_not_allowed`, decided before the bucket is read. 2. *The bucket.* A request that still names no class is in the bucket's `default_class` when it has one. Otherwise it is in no class and is checked against no floor, which is what every consume did before classes existed. A request naming a class the bucket does not declare is refused with `400 unknown_class`, whatever the balance: a typo fails loudly instead of spending without protection. It is an error, not a shortfall, so it is not counted in the shortfall totals. **Classes are not inherited**: a bucket made by a split declares its own, so a vocabulary used across a tree has to be declared on every bucket consumed from with it. What each mode does under a floor: | Mode | With a floor | |---|---| | `Strict` | refused when the request would cross the floor | | `Partial` | clamped to what is above the floor, not to the balance | | `Wait` | polls; succeeds when a replenishment or the floor's release makes room | | `Async` | the pending consume keeps its class, and the scheduler's fulfilment applies the same check | | `check` | answers with the floor applied | A `Reporting` dimension is never gated, by a floor either. **What you get back.** When a class applied, the outcome (`ConsumeSuccess` and `ConsumeShortfall`) carries `coProtection`: ```json {"cpClass": "batch", "cpFloor": {"tokens": 371204.5}, "cpProtected": true} ``` `cpFloor` is the class's floors at that instant (dimensions with nothing protected are left out). `cpProtected: true` means the balance alone would have served the whole request and the floor is what held it back: on a shortfall, or on a `Partial` that was clamped. The `bucket.consume_shortfall` event (written for a consume with an idempotency key) carries `class`, `floor` and, in that case, `reason: "protected"`. That is demand refused on purpose; do not read it as "the allowance is too small". `bucket.consumed` in the event log carries `class`. `coEta` under a class is the **earlier of two instants**: the replenishment that brings the request above the whole floor, and the floor going down (`step`: `lead_seconds` before the next run; `linear`: the instant the floor falls to what the request leaves). It is a lower bound, never a promise. `POST /buckets/:id/eta` takes `etqClass` for the same answer without trying (a key limited to several classes that names none is answered as no class). **Reserve.** `POST .../reservations` takes `rrvClass`, with the same rules as `crClass` (the key's list, the bucket's `default_class`, `unknown_class`), and is held to the same floor at reserve time, against current minus reserved. A refusal is `ReserveShortfall` with `roProtection` (the same object as `coProtection`). An `Async` reserve keeps its class and the scheduler applies the floor at fulfilment. **Commit does not re-check**: the hold was granted under the floor of its time. The hold stores its class (the effective one, the bucket's default included) and the commit counts under it in the per-class ledger. Without this a floor that gates `consume` would be bypassed by reserving first. **Claims.** `POST /claims` (and `/claims/check`) takes `clrClass` and `POST /claim-reservations` takes `clrrClass`, with the rules of `crClass`, applied to **each target bucket**: a target pays (or is held) only if the balance it keeps is at or above that bucket's own floor for the class, against current minus reserved. A target that does not declare the class refuses the whole call (`unknown_class`); a `FirstOf` pick skips a target whose floor the amount would cross. A queued (`Async`) claim or claim reservation keeps its class and the scheduler applies the floors of each tick (a claim whose class a target stops declaring waits until its deadline). A granted claim reservation is not re-checked at commit; it stores the class named on the request (not a target's default) and the commit books every grant under it. The claim shortfall lists the targets that fell short and carries no `roProtection`. Limits to know before relying on it: - **Protection is statistical, not a guarantee.** A floor keeps the lower class out; it does not promise the higher class that the balance will be there (another caller of the same class can take it). A job that needs a guarantee still uses a reservation. - **A class is something the caller says.** It binds only through a key limited to a class: hand the batch job a `ScopeConsume` key with `"cakreClasses": ["batch"]` and it cannot present itself as `interactive`. A key limited to some classes may only mint keys limited to some of those, never an unlimited one. - **Consume, check, reserve, claims and claim reservations apply a floor; split does not.** A key limited to some classes is refused on `POST .../split` (`403 class_limited_key`). - **A floor above what the bucket ever holds refuses the class** for as long as it stands. With `step` that is a legitimate way to say "only in the last three days". - **Removing a class starts refusing its callers at once** (`unknown_class`). `DELETE /buckets/:id/class-config` removes all of them. - **Changing the schedule afterwards is not re-validated.** A `linear` or `step` floor on a bucket whose schedule was removed stays whole. **Suggested floors** (`ScopeRead`, read-only): `GET /buckets/:id/class-floor-suggestion?order=a,b,c&periods=8&coverage=90&dimension=` proposes a floor per class from the closed periods of the per-period ledger and replays it. `order` is the classes from highest utility to lowest (it may be left out when the declared floors already rank them; otherwise `400 order_required`); `periods` is how many closed periods to read (8, at most 52); `coverage` is the percentile of the higher classes' per-period demand that the floor protects (90, 50 to 100). Per dimension and class the answer has `suggested` (`{floor, release: "linear"}`, null for the top class), `current`, the higher classes' demand per period, and a `replay` with and without the floors (`refused_by_floor`, `shortfall_avoided`) next to the ledger's actual figures. `proposed_class_config` is the declaration with the floors written in, in the body `PUT /buckets/:id/class-config` takes; nothing sets it for you. The ledger holds each period's totals and not when in the period they happened, so the replay assumes demand is spread evenly over the period (the shape a `linear` release protects against) and ignores credits inside a period. Read the `assumptions` it returns. See `GET /help/classes`. **Proposing a replenishment policy** (`ScopeRead`, read-only): `GET /buckets/:id/replenishment-dry-run?dimension=tokens&period=week&coverage=100`. The on-ramp is reporting mode: a `Reporting` dimension never refuses, so its `consumed` is its whole demand. Run it for a few periods, then ask. The closed periods of the per-period ledger are regrouped on a UTC calendar grain (`day`, `week` from Monday, `month` from the 1st) or the bucket's own `schedule`; a calendar period with no row is a period of zero demand. With at least 3 whole periods two policies come back, sized at the `coverage` percentile of per-period demand (100 by default, 50 to 100), rounded up to `demand.unit_grain`: - `reset`: amount = cap, `CarryoverNone`; - `carry_over`: `CarryoverUnlimited` under the same cap, with the smallest amount that refuses no more than `reset` does (`null` when that is `reset`'s own amount). Send `amount`, `cap` and `carryover=none|unlimited` together to dry-run a policy of your own as `custom`. Each is replayed over the record with the scheduler's own arithmetic, starting from today's balance as the switch would leave it (`replay.start`: kept when it is between zero and the cap or the dimension is already `Locking`, otherwise reset to the policy's amount, less what is held), so the replay reads as the record played again from where switching leaves you: `served`, `refused`, `discarded_carryover`, `discarded_overflow`, `left`, `periods_refused`, and the same per period. Without `period`, the coarsest grain with 3 whole periods is answered (the bucket's `schedule` first when it has one); `grains` lists what the record supports, and naming another is `400 period_not_available`. `periods` is how many closed rows to read (120, at most 400), within your history retention. Every series period carries `mode`, the dimension's mode when it closed: on anything but `reporting` the demand is a floor (a refused caller may not have asked again). `periods_censored` counts those; `uncensored_only=true` drops them. Each proposal's `switch` is two bodies to send, in this order: `PATCH /buckets/:id` (`switch.patch_bucket`: the cap as `raMaximum` and the flip to `Locking`, with `dmcResetCurrent` when the balance is negative or above the cap) and `PUT /buckets/:id/replenish-config` (`switch.put_replenish_config`). When the bucket already has a config, the body keeps its schedule, its other dimensions and its bucket-wide carry-over, so only the rule that agrees with that carry-over gets a switch; `switch_blocked` says why the other has none. Nothing is applied for you. If the `PATCH` is refused because the balance moved, read again and retry. `subtree=true` sizes a parent from the demand of the parent and every bucket under it, for a parent whose children do the consuming. Each bucket's record is read on its own terms (whole periods only), then added: on a calendar grain by the period a row starts in, on `period=schedule` into the parent's own periods. Balance moved between buckets of the subtree is not demand. `subtree` and `subtree_buckets` say it was asked and how many buckets under the parent were read (at most 500); the policy and the switch are the parent's. See `GET /help/replenishment`. ### Async consumption — wiring the callback The primary callback mechanism is buckette's **webhook subscription system**, set up once, ahead of time, independently of any particular consume call — `crMode: Async` itself doesn't require a URL or endpoint on the request. (A per-call callback URL is also available — `acCallbackUrl` inside `AsyncConfig` — as an addition on top of this, covered under "Per-request callback" below; it doesn't replace the subscription step.) If you skip both — no standing subscription and no `acCallbackUrl` — `Async` mode still registers the pending intent correctly, but nothing will ever tell you when it resolves — you'd have to poll `GET /buckets/:id/pending-consumes` yourself instead. Two-step wiring: 1. **Subscribe once**, before you ever send an `Async` consume request: ```json // POST /webhooks {"cwrUrl": "https://your-service/hooks/buckette", "cwrEvents": ["bucket.resources_available", "bucket.consumed", "bucket.consume_expired"], "cwrSecret": "optional-hmac-signing-secret"} ``` (An empty `cwrEvents` array subscribes to every event type instead of listing specific ones.) This is a standing subscription for the tenant — it fires for every matching event on every bucket, not just one call. Not every URL is accepted: `cwrUrl` must be `https`, must resolve to a publicly routable address, and must be **authorized** — its host on the tenant's callback allowlist **and** a verified destination claim covering the URL. Both, not either. If registration fails with a 400 naming one of them, see "Outbound destination validation" below; it is the same machinery the per-request callback path answers to. 2. **Send the consume call** with `crMode: Async`: ```json // POST /buckets/:id/consume {"crAmounts": {"tokens": 500}, "crMode": {"tag": "Async", "contents": {"acMaxDelaySecs": 3600, "acAutoConsume": true}}} ``` If resources are available immediately, this behaves exactly like `Strict` and returns `ConsumeSuccess` right away — no webhook involved. Only on shortfall does it return `ConsumePending {coPendingId, ...}` and register the intent; the scheduler retries it in the background (`acMaxDelaySecs`, capped at 86400s / 24h) until it's satisfiable or the deadline passes. What arrives at your webhook URL once the intent resolves depends on `acAutoConsume`: - **`acAutoConsume: true`** — the scheduler deducts the resources automatically the moment they're available, and your webhook receives `bucket.consumed`. Nothing further to do on your end; treat it exactly like a synchronous consume that happened to complete late. - **`acAutoConsume: false`** — nothing is ever deducted automatically. Your webhook instead receives `bucket.resources_available`, which is a signal to go re-issue the consume call yourself (a synchronous `Strict` retry will now succeed). Prefer this if your webhook receiver isn't reliably up — auto-consuming resources that nobody ends up using is wasted budget. - **If the deadline passes first** (`acMaxDelaySecs` elapses before the resources ever became available), your webhook receives `bucket.consume_expired` instead (`reason: "deadline"`), and the pending intent is dropped. **What changes under a waiting intent.** Every tick looks at the bucket again, as it is then: - **Frozen after it was queued:** the intent keeps waiting, even if the bucket could now pay; it is served once the bucket is unfrozen, or expires at its deadline. (Registering one on a bucket that is already `Frozen` is refused with `422 bucket_not_active`, and nothing is queued.) - **Its consume class removed** from the bucket's declaration: it keeps waiting to its deadline and is never served without that class's floor. - **Archived or deleted:** it ends (`bucket.consume_expired`, `reason: "bucket_gone"`). - **The API key that registered it revoked, expired or deleted** (since 2026-11-10): it ends at the next tick, unserved (`reason: "key_inactive"`), whatever the bucket holds. It is a check when the intent is served, not a fence: a tick that was already serving it when the key was revoked may still go through. Intents registered before this change are served as before. The same holds for queued reserves (`bucket.reserve_expired`), transfers (`bucket.transfer_expired`), claims (`claim.expired`) and claim reservations (`claim.reservation_expired`), each with its own reasons (below). While a pending intent is outstanding, `GET /buckets/:id/pending-consumes` lists it and `DELETE /buckets/:id/pending-consumes/:id` cancels it early (e.g. the workflow step that wanted the resources was itself aborted). `POST /buckets/:id/check` supports `crMode: Async` too, for a notify-only "tell me when this would succeed" watch that never deducts, regardless of `acAutoConsume`. `rrvMode: Async` on `POST /buckets/:id/reservations` works identically — same two-step wiring, same `acMaxDelaySecs`/`acAutoConsume` semantics, except the resolved events are `bucket.reserved` / `bucket.resources_available` / `bucket.reserve_expired` and the mutation is reserving rather than deducting. #### Per-request callback: an alternative to the standing subscription The webhook subscription above is tenant-wide — every matching event on every bucket goes to the same URL(s), forever. If instead you want a callback scoped to *this one call* — e.g. a distinct, state-carrying URL per outstanding request (HATEOAS-style: `https://svc/tasks/abc123/resume`) rather than demultiplexing a shared endpoint by `coPendingId` yourself — set `acCallbackUrl` (and optionally `acCallbackSecret`, HMAC-signed exactly like `cwrSecret`) inside `AsyncConfig`: ```json {"crMode": {"tag": "Async", "contents": { "acMaxDelaySecs": 3600, "acAutoConsume": true, "acCallbackUrl": "https://svc.example.com/tasks/abc123/resume", "acCallbackSecret": "optional-signing-secret"}}} ``` This fires exactly once, when this specific pending intent resolves — **additively alongside** any matching tenant-wide subscription, never in place of it. Same event names, same payload shape, same signature format, same retry backoff as the webhook path above. **What your receiver answers decides whether buckette tries again**, for a webhook and a callback alike. Answer a 2xx once you hold the event. A 5xx or a 429 is a failed attempt and is retried (30 s, doubling, capped at 1 h, 8 attempts in all), as is no answer at all (10 s timeout, refused connection); a `Retry-After` on a 429 or 503 (seconds or an HTTP-date) is honoured for that retry, capped at 1 h. Any other 4xx ends the delivery: it is not sent again. So a receiver mid-deploy should answer 503, not 400, and a receiver that is shedding load answers 429 with a `Retry-After`. Retries can repeat an event your receiver already processed (it answered 503 after acting on it, or its 2xx did not arrive within 10 s), so make handling idempotent. Nothing in the API lists per-request callback deliveries, so keep your own record if you need one: buckette's retry bookkeeping for a callback is internal, and is deleted about a week after the delivery succeeded or was given up on (the exact window can differ from one instance to another). One prerequisite: because `/consume`/`/reserve` only require `ScopeConsume` — a lower bar than the `ScopeAdmin` that `POST /webhooks` itself requires — a free-form `acCallbackUrl` would let any `ScopeConsume` key make buckette issue outbound requests to a host of its choosing. So the URL has to be authorized the same way a webhook URL is: its host on the tenant's callback allowlist (`ScopeAdmin`-only), **and** a verified destination claim covering it. ```json // PUT /callback-allowlist {"calrHosts": ["svc.example.com", "*.tasks.example.com"]} ``` Hosts match exactly, or via one leading `*.` wildcard (`"*.tasks.example.com"` matches `foo.tasks.example.com`, not the bare `tasks.example.com` itself). `https` is required regardless. An empty or never-set allowlist — the default for every tenant — accepts **no** callback URLs; this is fail-closed, not opt-out, and validated synchronously on the consume/reserve request itself (a disallowed host rejects the whole call, before any pending row is created). See `GET /help/callback-allowlist` for full details. For the proof half, **claim the domain rather than each URL**: this pattern's whole point is a distinct URL per outstanding request, and those cannot be enumerated in advance. A caller with a handful of stable resume endpoints can claim them individually instead. See "Outbound destination validation" below for both kinds; the rules there are exactly the rules a webhook URL gets, with no per-path exceptions. ### Reserve vs. consume `consume` deducts `raCurrent` immediately. `reserve` instead increments `raReserved` without touching `raCurrent` — use this to hold capacity for work that hasn't started yet (e.g. reserve tokens for a call you're about to make, then either commit by consuming or release the reservation if the call is aborted). `raReserved` reduces what's *available* for other consumers (`available = raCurrent - raReserved`, which every read carries as `raAvailable`) without changing the reported balance. A reserve can carry `rrvTransactionId`, a caller-chosen id under the same rule as `repTransactionId` on replenish: unique per tenant (any bucket), remembered for seven days, never colliding with another tenant's. Unlike replenish, a repeat is refused, `400` with "transactionId already used for a reservation", and holds nothing; the first reservation carries the id as `rvTransactionId`. `POST .../reservations/:rid/commit` takes an optional body, `{"crqAmounts": {...}}`, keyed by dimension the same way `rrvAmounts` is. Omit it (or omit a dimension from it) to commit that dimension's full held amount — today's default behavior. Supply a smaller amount per dimension to commit only that much: the difference between what was held and what you actually commit is released back to availability rather than consumed, so a reservation made against an upfront estimate doesn't have to eat the whole hold when actual usage turns out to be less. `0` for a dimension commits none of it and releases that dimension's whole hold (a hold on two dimensions used on one only). A commit amount can't be negative, can't exceed what's held for that dimension (but see the `MeteredOverage` exception below), and can't name a dimension the reservation didn't reserve — all are rejected as `InvalidOperation`. **Committing past the hold on a `MeteredOverage` dimension.** A run that used more than it held may name the real amount in `crqAmounts` on a `MeteredOverage` dimension, instead of committing the hold and booking the rest as a second consume that could be refused after the work is done. The part above the hold is taken by the commit and checked exactly as a `Strict` consume of it would be at that moment: the bucket must be active, the floors of the class the hold was made as apply, every other hold on the bucket is left alone, and the balance may go down to minus `raOverageLimit` and no further. Past the line the **whole commit** is refused, `409 insufficient_resources` with the shortfall per dimension in `errDetails`; nothing is deducted and the hold stays active, so commit it again with less (a commit of what it holds always fits). A dimension with no line is never refused, as for a consume. The excess is overage like any other (`coOverage`, `overage` on `bucket.consumed`). This is a bound, not a way around it: a hold and its commit never take a dimension further past its line than a consume could. `Locking` and `Reporting` dimensions, and a commit with `crqTransferTo`, keep the rule that no amount exceeds the hold. Partial amounts are only accepted when authenticated as the tenant (API key); a request authenticated via `X-Buckette-Commit-Token` (see "Trusted-third-party receipts" below) must omit `crqAmounts` and always commits the full held amount, since the token itself carries no amount and a leaked token shouldn't be able to choose one. **Transfer** (`crqTransferTo`): add a bucket id to the commit body, `{"crqTransferTo": ""}`, to have the committed amounts land as a credit on that bucket instead of simply ceasing to exist: reserve on the source, commit with `crqTransferTo` set to the destination. Use it when the amount must be guaranteed before the work that earns it; when no hold is needed, or you want to wait for the source to be able to pay, `POST /transfers` (the "Transfers" section below) moves the amount in one call. The source bucket still emits `bucket.consumed` as usual; the destination emits its own `bucket.credited` event rather than `bucket.consumed`, so neither side's event log implies the other side's amount vanished. The commit is delivered to webhooks as `bucket.reservation_committed` (with `transferred_to`); `bucket.credited` is an event-log line only (see `GET /help/events`). The destination must be a different bucket in the same tenant, must already have every dimension being transferred (an unknown dimension is rejected, same as elsewhere), and the credit can't push any dimension's `raCurrent` past its `raMaximum` — rejected outright rather than silently capped, since discarding part of a transfer silently would be a worse failure than a 400. Like `crqAmounts`, only accepted when authenticated as the tenant — an `X-Buckette-Commit-Token` request must omit `crqTransferTo` too. **Metadata** (`crqMetadata`): add any JSON to the commit body, `{"crqMetadata": {"session": "...", "model": "..."}}`, to say what the settled work was. It is the same field as consume's `crMetadata`: at most 1 KiB encoded (a larger one is a `400`, and nothing is committed), written as `metadata` in the `bucket.consumed` record of the commit, which `GET /buckets/:id/events` returns. Unlike `crqAmounts` and `crqTransferTo`, it is accepted on a commit authenticated with `X-Buckette-Commit-Token`: it moves no capacity, the token is good for that one commit, and the relying party settling the reservation is the one that knows which session or model did the work. The record's actor tells the two apart: a token commit is written by the nil key id (`00000000-0000-0000-0000-000000000000`). It is also kept on the hold, as `rvSettlementMetadata`. **Webhooks for the end of a hold.** A commit, a cancel and a release (next section) are each delivered to webhooks after their transaction: `bucket.reservation_committed` (the details of the `bucket.consumed` the commit records: `amounts`, `held_amounts`, `reservation_id`, `metadata` the commit's, `reservation_metadata` the hold's, and `class`, `overage`, `transferred_to` when they apply), `bucket.reservation_cancelled` (`reservation_id`, `amounts` released, `metadata` the hold's) and `bucket.reservation_released`. A hold's own expiry is `bucket.reservation_expired` (`reservation_id`, `amounts` released, `metadata` the hold's; it was delivered as `bucket.reserve_expired` before, which now names only a queued reserve giving up). Not as `bucket.consumed`: a subscription to every event gets one delivery per commit. Subscribe to the four by name (or to every event) to follow holds from their `bucket.reserved` to their end. ### Releasing a reservation with an outcome — slots On a bucket whose dimension counts concurrent work (a slot, a lock, a seat), finishing the work has to give the slot back. A commit doesn't (it spends the amount for good: the slot would be gone until the next replenishment), and a cancel does but says the work was abandoned. Release says it finished: ```json POST /buckets/:id/reservations/:rid/release {"rlrOutcome": "done", "rlrMetadata": {"pr": "https://example.test/pr/12"}} ``` The hold is released exactly as a cancel releases it (`raReserved` goes down, `raCurrent` is untouched), its status becomes `released`, and the outcome and metadata are kept on it (`rvOutcome`, `rvSettlementMetadata`) and carried on `bucket.reservation_released` (`reservation_id`, `amounts`, `outcome`, `metadata`, and the hold's own as `reservation_metadata`). `rlrOutcome` is a label of your own, 1 to 64 characters with no control character (`done`, `failed`, `superseded`); `rlrMetadata` is any JSON, at most 1 KiB. Both optional. Returns the `Reservation`; `400` if it isn't active, `404` if it doesn't exist. API key only (scope `consume`); a commit token admits nothing but its commit. Rule of thumb: commit when the hold measured something spent (tokens, money, minutes), release when it guarded a turn. A commit of `0` for every dimension also frees the hold, but records a `bucket.consumed` of nothing and no outcome. ### Listing and reading reservations `GET /buckets/:id/reservations` lists the bucket's holds, newest first, a page at a time (scope `read`): - `status`: `active` (the default), `committed`, `cancelled`, `expired`, `released`, or `all`; - `api_key_id`: the holder, the key that took the hold (`rvApiKeyId`; for a hold the scheduler granted from a queued `Async` reserve, the key that registered it). `null` for a hold no key took (an auction's escrow) and for holds taken before the field existed; - `metadata`, repeatable: `key:value` (split at the first colon), keeping the holds whose `rrvMetadata` has that top-level key with that string value, e.g. `?metadata=feature:2382dd72&metadata=team:billing`. At most 10; a number or object under the key never matches; - `limit`: 1 to 500, default 100; - `cursor`: when more holds follow, the response carries an `X-Next-Cursor` header; send its value back as `cursor` for the next page. No header: last page. The value is opaque. A parameter it can't read is a `400` naming it, never a wider list. `GET /buckets/:id/reservations/:rid` reads one hold, whatever its status. ### Transfers — moving an amount from one bucket to another `POST /transfers` moves `trAmounts` from `trFrom` to `trTo`, two buckets of your tenant that your key can see, in one transaction: either all of it moves, or nothing does. Any two buckets, related or not (a parent topping up a child, two siblings, two roots); never across tenants. It is the unqueued, simpler sibling of a claim: consume's `Strict` and `Wait` modes, no priority queue. Use it for the parent-to-child top-up (a session's child bucket growing from the machine bucket as it spends), for rebalancing between siblings, or wherever you would otherwise reserve on one bucket and commit with `crqTransferTo` without needing the hold. ```json POST /transfers { "trFrom": "", "trTo": "", "trAmounts": {"tokens": 200}, "trMode": {"tag": "Strict"}, "trClass": "batch", "trTransactionId": "topup-2026-11-02T21:00-session-7", "trMetadata": {"session": "7"}, "trNonce": "relying-party-nonce" } ``` - `trMode` is `crMode`'s JSON: `{"tag": "Strict"}` answers now; `{"tag": "Wait", "contents": {"wcMaxDelaySecs": 30}}` polls the source every 500 ms for up to 300 s and answers with the last attempt; `{"tag": "Async", "contents": {"acMaxDelaySecs": 3600, "acAutoConsume": true, "acCallbackUrl": "..."}}` makes one attempt and, if it is short (or the source is `Depleted`), queues the transfer for the scheduler (below). `Partial` is refused (`400 invalid_mode`: a transfer moves what was asked or nothing). - The **source** is checked as a `Strict` consume of `trAmounts` would be: `raCurrent - raReserved` above the floor of `trClass` (a class-limited key transfers as its class), with two differences. A `MeteredOverage` dimension never goes into overage for a transfer (a moved amount is budget handed over, not debt: a source already in debt is short by the whole amount), and a `Reporting` dimension is checked at zero (a consume of it always succeeds because it reports a cost that happened; a transfer reports nothing). A `Depleted` source is refused (`422 depleted`); a `Frozen` or `Archived` one too (`422 bucket_not_active`), in every mode. - The **destination** must have every dimension named (else `400 invalid_transfer`, naming the side), and the credit must fit under its `raMaximum`. `Active`, `Depleted` and `Frozen` destinations take the credit (a freeze stops spending, not receiving); a `Depleted` destination goes back to `Active` when the credit ends a gating dimension above its floor, as a replenish does. `Archived` is refused. - The answer is HTTP 200 either way: `TransferSuccess` (`toMoved`, `toSourceRemaining`, `toDestinationBalance`, `toReceipt`, `toProtection`) or `TransferShortfall` (`toShortfall` on the source, `toDestinationRoom` on the destination: the part of the credit that does not fit, `toAvailable` for the dimensions fine on both sides, `toEta` as a consume's `coEta`, about the source only). A shortfall moves nothing. When the **source** lacked the amount (or was `Depleted`), it is counted as a shortfall on the source, a reason of its own: a `bucket.transfer_shortfall` line and webhook, and `bsTotalTransferShortfallAllTime` (see "Refused transfers" under the shortfall totals). Once per `trTransactionId` when sent, once per refused request otherwise; a `Wait` counts once when it gives up, an `Async` one only if it expires short. No room on the destination, a Frozen source, scope or a bad body is not a shortfall. - `trTransactionId` has reservation semantics, not consume's replay: a granted transfer uses the id up and a second call with it is `400 transaction_id_used`; a refused one does not, so a retry of a shortfall runs again. Per tenant, remembered seven days. - `trNonce` mints a receipt (see "Trusted-third-party receipts") with `eventType` `bucket.transferred` and `bucketId` the **source**: it attests the debit; the destination is not in the payload. A relying party that must know where the budget went reads `to_bucket_id` from the event, or puts it in the nonce it chooses. - Events: `bucket.transferred` is recorded on the source and delivered **once** (webhook `bucket_id` = the source; `from_bucket_id` and `to_bucket_id` in the payload), `bucket.credited` is recorded on the destination, both with the same `transfer_id`. The ledger books a move: `total_moved_out` on the source, `total_moved_in` on the destination, never `total_consumed`, so a period reconciles and a top-up is not spend on the parent (`GET /buckets/pacing` and the consumption breakdown do not show it). - Scope `consume`, on a key whose bucket scope contains both buckets: a delegated key can only rebalance within its roots. Rate limits apply as on every route. Two transfers the other way round, or a transfer and a claim over the same two buckets, lock both rows in one statement in ascending bucket id, so they wait on each other and never deadlock. **Queued transfers (`Async`).** The immediate attempt is the same locked attempt as `Strict`; granted, you get `TransferSuccess` and nothing is queued. Short on the source, short of room on the destination, or a `Depleted` source (refused for `Strict`/`Wait`, queued here, as an `Async` consume is): the answer is `TransferPending` (`toPendingId`, the shortfall snapshot `toShortfall`/`toDestinationRoom`/`toAvailable`/`toEta`, `toAuto`, `toExpiresAt` = now + `acMaxDelaySecs`, capped at a day), and the scheduler retries it every tick, in deadline order, **without priority or fairness** (a stream of small queued transfers can starve a large one; a caller that needs a place in line uses a queued claim). When it goes through: `acAutoConsume: true` moves it and sends `bucket.transferred` (webhook and your `acCallbackUrl`, with `pending_id`, `from_bucket_id`, `to_bucket_id`, `amounts`, `source: "async"`, `receipt` when `trNonce` was sent); `acAutoConsume: false` moves nothing and sends `bucket.resources_available`, leaving the move to you. Past the deadline, or when a bucket is archived or deleted, `bucket.transfer_expired` (`reason`: `deadline`, `source_gone`, `destination_gone`, or `key_inactive` when the API key that registered it was revoked, expired or deleted since). A `Frozen` source keeps the transfer waiting (a freeze stops spending), and so does a class the source no longer declares. `trTransactionId` is used up at registration, so a retry of the registration is `400 transaction_id_used` rather than a second queued row. `GET /pending-transfers` (scope `read`) lists your tenant's queued transfers still pending, in service order, both buckets within your key's scope; `DELETE /pending-transfers/:id` (scope `consume`) cancels one, `409 not_pending` when the scheduler got there first (it records `bucket.transfer_cancelled`; nothing is delivered). An instance where no process runs the `queues` duty refuses an `Async` transfer with `503 duty_unattended`, as it refuses an `Async` consume. ### Automatic top-up — a bucket refilled from another one when it runs low A transfer you make yourself is one move. A **top-up policy** is a standing one: set it on the bucket that receives, and the scheduler moves a dose to it from the source whenever it runs low. This is the parent-to-child top-up made automatic: a session's child bucket that grows from the machine bucket as it spends, with per-child accounting, instead of being handed everything up front (and what is left unspent flows back by reclaim, as ever). ```json PUT /buckets//topup-config { "tuSource": "", "tuTrigger": {"tokens": {"tag": "AbsoluteThreshold", "contents": 100}}, "tuDose": {"tokens": 500}, "tuCap": {"tcpAmounts": {"tokens": 5000}, "tcpPeriodSeconds": 86400}, "tuClass": null } ``` - **When.** At each scheduler tick (every 30 s, on the instance running the `replenish` duty), a top-up is due when any `tuTrigger` dimension's *available* balance (`raCurrent - raReserved`) is at or below its level: `AbsoluteThreshold` an amount, `PercentThreshold` 0-100 of the dimension's `raMaximum` (which it must have). At most one top-up per bucket per tick, so size the level and the dose for about 30 s of spend. - **How much.** `tuDose`, lowered (never raised) to what is left of `tuCap` in the current period and to the room under the bucket's `raMaximum`. A split child is capped at its allocation unless it was split with `srChildLimitMode: "InheritParentMax"`: raise its maximum, or it will not grow. `tuCap` is optional; a period (60 s to a year) opens with the first top-up after the previous one ended. - **With what rules.** A `Strict` transfer's (section above): all of the dose or nothing, never below the source's class floors (`tuClass`, resolved by your key as `trClass` is, and declared by the source), never into overage, a `Reporting` source dimension gated at zero. A `Frozen` source or bucket waits; a `Depleted` source is short. - **Booked as a move**, not as spend: moved out of the source and in on the bucket, `bucket.transferred` recorded on the source and `bucket.credited` on the bucket, both with `source: "topup"`; `bucket.transferred` is delivered to your webhooks with `from_bucket_id`, `to_bucket_id`, `amounts`, `toSourceRemaining`, `toDestinationBalance`. - **A source that cannot pay** moves nothing, and its shortfall is booked on it **once per shortage** (`bucket.transfer_shortfall`, `mode` and `source` `"topup"`, counted in `bsTotalTransferShortfallAllTime`), not on every tick the shortage lasts. The first tick that finds the source able to pay moves the dose and ends the shortage. - **Refused when set:** `400 invalid_topup_config` (the bucket as its own source, an empty trigger or dose, a non-positive amount, a dimension missing on either bucket, a percentage on a dimension with no maximum, a cap outside its bounds), `400 unknown_class`, `400 topup_cycle` (the source tops itself up, directly or through others, from this bucket: the same budget would go back and forth), and `404 bucket_not_found` naming whichever bucket is not yours or outside your key's scope. Scope `admin` for `PUT`/`DELETE`, `read` for `GET`. - `GET /buckets/:id/topup-config` answers `{tcvConfig, tcvState}`, the bookkeeping being `tusPeriodStartedAt`, `tusMovedInPeriod`, `tusShortSince`, `tusLastTopupAt`, `tusTopups`; `404` when there is no policy. `DELETE` removes it (`204`, also when there was none); a `PUT` replaces it whole and starts the bookkeeping again. - **A policy that can no longer run is removed by the scheduler**, which records `bucket.topup_removed` on the bucket (`reason`: `source_gone`, `source_archived`, `dimension_missing`, `class_not_declared`). ### Growing a reservation When the work turns out to need more than the hold, grow it rather than taking a second reservation (which would mean a second commit and a second `bucket.consumed`): ```json POST /buckets/:id/reservations/:rid/grow {"grqAmounts": {"tokens": 200}, "grqTransactionId": "run-42:topup-1"} ``` `grqAmounts` is **added** to what the reservation holds, per dimension; a dimension it doesn't hold yet is added to it (it must be on the bucket). The addition is checked like a `Strict` reserve of those amounts, at this moment: the bucket must be active, and the amounts available above the floors of the class the reservation was made as. It is all or nothing: a shortfall answers `ReserveShortfall` (`roShortfall`, `roAvailable`), adds nothing, and is booked as refused demand like a reserve's (`bucket.reserve_shortfall` with the `reservation_id`). On success the answer is `ReserveSuccess` with the hold's new `rvAmounts`, and the event log gets `bucket.reservation_grown` (`amounts` added, `held_amounts` now), which is also delivered to webhooks subscribed to it, like `bucket.reserved`. `grqTransactionId` is optional and is an idempotency key of its own: a repeat is a `400` and adds nothing. API key only (scope `consume`); a commit token minted at reserve time stays good and commits the grown hold in full. ### Refreshing a reservation — reservation-as-lock / leader election A reservation's `rvExpiresAt` is fixed at creation time by default — once it lapses, the scheduler releases the hold automatically (Alice's hold expires, Bob can grab it). `POST .../reservations/:rid/refresh` extends (or clears) that expiry on an still-active reservation, letting a still-in-progress holder renew its hold instead of it lapsing: ```json {"rfrExpiresAt": "2026-08-01T00:00:00Z"} ``` `{"rfrExpiresAt": null}` clears the expiry entirely (never expires until cancelled/committed). This is an absolute replacement, not a relative extension — repeated refreshes ("push it out another 30s from now") don't compound drift the way a relative extend would. Returns the updated `Reservation`; 400 if the reservation isn't `active` (already committed, cancelled, or expired), 404 if it doesn't exist. This gives reservations real lock semantics: a single reservation on a resource-limit-1 dimension is a lease, and whoever keeps successfully refreshing it before it lapses is effectively "leader" — a holder that stops (crashes, network partition) lets the hold expire on the scheduler's next sweep, so a contender's own reservation attempt can then succeed. `GET /buckets/:id/reservations` lists the currently-active reservation(s) a contender would check against, with the key that holds each (`rvApiKeyId`). `{"rfrExpiresAt": null}` clears the expiry only on a bucket without a reservation policy (next section); under one, it takes the policy's default. ### Default and maximum hold lifetime — the bucket's reservation policy A hold taken without `rrvExpiresAt` never expires on its own: if the client crashes between reserve and commit, the amounts stay held until someone cancels them. A bucket can carry a reservation policy so forgotten holds free themselves: ```json {"cbrReservationPolicy": {"default_ttl_seconds": 600, "max_ttl_seconds": 3600}} ``` on `POST /buckets`, or the same object as `pbrReservationPolicy` on `PATCH /buckets/:id`. `GET /buckets/:id` shows it as `bucketReservationPolicy` (`null` when the bucket has none). Either field may be left out; each is 1 to 31622400 seconds (366 days), and the default may not exceed the maximum (`400` otherwise). - **A hold with no expiry asked for** expires `default_ttl_seconds` after it is taken; with no default but a maximum, `max_ttl_seconds` after. - **An expiry asked for past `now + max_ttl_seconds`** is clamped to it; one within it is kept as asked. - **Refresh** follows the same rule from the moment of the refresh: it can extend a hold up to `max_ttl_seconds` from now, never further, and `{"rfrExpiresAt": null}` renews it by the default. - **Async reserves** get the policy when the scheduler takes the hold, from that moment. The `rvExpiresAt` returned (and listed) is the one applied, and a commit token never outlives it. Expiry itself is unchanged: the scheduler's sweep releases the hold and fires `bucket.reservation_expired`. The patch replaces the whole policy (`{}` removes it) and is recorded as `bucket.reservation_policy_changed`; holds already taken keep their expiry. A split's child inherits its parent's policy (patch the child to change it). Buckets without a policy, which is every bucket until one is set, behave as before. An auction's escrow holds follow their bid's expiry, not the policy; claim reservations are not covered by it. ### Depleted and Archived buckets - **`Depleted`** (every `Locking` dimension at zero) refuses spending until it is credited: a consume, a split and a reserve answer `422 depleted` (an `Async` consume or reserve queues instead, see above). A replenish, a transfer in, the credit of a child's reclaim or of a deleted child's roll-up (since 2026-11-14), or a positive `Locking` dimension added by `PATCH` makes it `Active` again when a gating dimension ends above its floor. - **`Archived`** (reclaimed or expired) is history: every way of spending from it or moving into it is refused with `422 bucket_not_active` (consume in every mode, `/check`, reserve, split, claims and `/claims/check`, claim reservations, a transfer either way), and so are a top-up policy and a second reclaim; a freeze or an unfreeze is `400 invalid_operation`. What would change what it holds or would do next is refused the same way (`422 bucket_not_active`): `POST /buckets/:id/replenish` (a replay of a transaction id already applied is still the no-op `200`), the `replenish-config`, `threshold-config`, `class-config` and `unspent-warning` PUTs, and every dimension edit on `PATCH /buckets/:id` (`pbrAddDimensions`, `pbrRemoveDimensions`, `pbrResourceLimits`, `pbrDimensionMode`, `pbrOverageLimits`; a request carrying one writes nothing else either). Its metadata can still be edited, and a policy can still be removed (the `DELETE`s). A hold left on it by `ReclaimUnusedOnly` can still be committed or cancelled (that is the mode's purpose). It stays readable, with its history. ### Bucket statistics — cumulative totals and history completeness `GET /buckets/:id/stats` reports cumulative spend and refill per dimension, each as two figures: - `bsTotalConsumed` / `bsTotalReplenished` — folded from the event log's `bucket.consumed` entries / the replenishment log at request time. - `bsTotalConsumedAllTime` / `bsTotalReplenishedAllTime` — a running total stored directly on the bucket row, incremented atomically alongside every consume/reservation-commit/claim-consume/replenish mutation, since the bucket was created. - `bsTotalShortfallAllTime` / `bsTotalShortfallUnkeyedAllTime` — the same kind of running total for demand that was **refused**: see "accumulated shortfall totals" under idempotent consume above. The first is exact (keyed consumes), the second an upper bound (unkeyed). - `bsTotalReserveShortfallAllTime` / `bsTotalClaimShortfallAllTime` — the same for refused reservations and refused claims (and claim reservations), totals of their own, upper bounds: see "Refused reservations and claims" there. - `bsTotalTransferShortfallAllTime` — the same for transfers refused because this bucket, their source, lacked the amount: exact per `trTransactionId`, an upper bound for transfers sent without one. - `bsTotalDiscardedAllTime` — the same kind of running total for allowance that refills **discarded**, by cause and then dimension (`{"carryover": {...}, "overflow": {...}}`): see "What a refill discards" under Replenishment. Written only by a refill, never by a consume. "Replenished" means everything ever **added** to the bucket, starting with the balance it was created with — by `POST /buckets`, by a split (the child's allocation), or when a dimension is added to a live bucket with a starting `raCurrent`. Each of those appears in the replenishment log too, with `rlSource` `created`, `split` or `dimension_added`, so the two figures below still agree. A refill counts what it actually added, which can be less than what was requested (see "Replenishment"). So for any dimension, `bsTotalReplenishedAllTime − bsTotalConsumedAllTime` exceeds the current balance by exactly what carryover policy has forfeited (`bsTotalDiscardedAllTime.carryover`, for refills since that total exists) — and by whatever split, reclaim and delete moved between buckets, which neither total counts. Buckets older than this rule (2026-09) carry requested amounts, and no opening balance, in their pre-existing totals. Under normal operation the two agree exactly. They can diverge if this bucket's log history has been truncated — old event-log and replenishment-log entries deleted by the tenant's own retention window (see "History retention" below) or by the deletion of a tenant — in which case the *AllTime figure keeps counting from bucket inception regardless, while the log-folded figure only reflects whatever history rows are still present. Comparing the two tells you whether you can trust the log-folded figure as complete: equal means nothing's missing; all-time exceeding log-folded means some history was purged. `bsCurrentBalance`/`bsFractionRemaining` (the live `raCurrent` snapshot, plus percent-of-`raMaximum` where set) round out the response. ### Bucket-scoped delegated API keys By default an API key can see/touch every bucket in its tenant. When you're handing a sub-agent (or an external partner) a bucket via **split**, you usually also want to hand it a key that *can't* see the parent bucket, its siblings, or anything outside the subtree it was given. Set `cakreBucketId` on `POST /api-keys` to confine the new key to that bucket and its descendants: ```json {"cakreName": "sub-agent-run-42", "cakreScopes": ["ScopeConsume", "ScopeRead"], "cakreBucketId": ""} ``` A scoped key can `split`/`reserve`/`consume` freely within its own subtree, but any bucket ID outside it — including the parent it was split from — returns `BucketNotFound`, not `Forbidden` (so it can't even confirm the parent exists). It can delegate further (mint its own sub-scoped keys) but only within its own subtree, never wider, and never an unscoped key. Minting doesn't require `ScopeAdmin`: any key can call `POST /api-keys`, as long as the scopes it requests for the new key are ones it already holds itself — a `ScopeConsume`-only key can delegate a `ScopeConsume`-only key onto a bucket it just split off, but can't hand out `ScopeAdmin`, `ScopeRefill`, or anything else it doesn't have. This is the natural pairing with the delegation pattern in **Example use cases** below: split a child bucket for each sub-agent, then mint it a key scoped to exactly that child, so a misbehaving or compromised sub-agent can't spend or even observe budget outside what it was given. Reclaiming the bucket (or letting it expire) automatically deactivates every key delegated to it, so you don't need to separately revoke sub-agent keys when a run ends. Keys delegated to its *descendants* go too on expiry, which archives the whole subtree, but on reclaim only with `rrCascade: true`: a plain reclaim archives the one bucket and leaves its children, and their keys, as they were. See the `delegation` help topic (`GET /help/delegation`) for the full rule set. A key can also be scoped to **several** roots at once — set `cakreBucketIds` (plural) to a list instead of the singular `cakreBucketId`: ```json {"cakreName": "cross-team-key", "cakreScopes": ["ScopeRead"], "cakreBucketIds": ["", ""]} ``` Every rule above applies to the union of the roots rather than to one: in-scope is "inside any of them", delegating further must stay inside the union, and a root that's already covered by another root in the same request (a bucket and its own descendant) is dropped rather than kept twice. `cakrBucketId`/`akiBucketId` in responses stay populated only when the key has exactly one root, for callers that haven't moved to the plural `cakrBucketIds`/`akiBucketIds` yet. A key can also be limited to some **consume classes** (`cakreClasses`), which is what makes a class binding instead of advisory: see "Consume classes and protection floors" above. ### Soft-revoking a key (moving its expiry) `DELETE /api-keys/:id` stops a key at once. To retire a key gracefully, so requests already in flight finish, move its expiry instead (needs `ScopeAdmin`, same visibility rule as the `DELETE`): ```json PUT /api-keys//expiry {"sakeExpiresInMinutes": 3} ``` Give exactly one of `sakeExpiresInMinutes` (relative to now) or `sakeExpiresAt` (an absolute time). Expiry is checked on every request. The route only ever shortens a key: the new expiry is the earlier of the key's current one and the one asked for, so a key that has already expired (or expires sooner) keeps its own, and that is not an error. To give a key more time, mint a new one. The response is the key's `GET /api-keys` entry, with the expiry that now holds; an unknown, out-of-view or already deactivated key is a 404. ### Trusted-third-party receipts Delegated keys (above) solve "let a sub-agent touch its own budget." Signed receipts solve a different problem: **let an external relying party verify that a consumption really happened, without giving it any buckette credentials at all.** Useful when a third party (a payment processor, an SLA auditor, a downstream service you don't operate) needs cryptographic evidence — not just your word — that a resource was actually consumed. Attach a `crNonce` (on `POST /buckets/:id/consume`) or `rrvNonce` (on `POST /buckets/:id/reservations`) — a nonce **chosen by the relying party**, not by you — and the response carries a signed, Ed25519 usage receipt (`coReceipt`) attesting "bucket X consumed amount Y at time Z for nonce N". Hand that receipt to the relying party; it verifies the signature itself, completely offline, using the tenant's public key from the unauthenticated `GET /tenants/:tenantId/receipt-public-key` — no callback into buckette, no shared secret provisioned in advance. No nonce, no receipt: this is fully opt-in and costs nothing on the common path. (This is a signed receipt of usage, unrelated to a billing receipt.) **The names before the rename are gone.** Receipts were called "proof tokens" before, and were sent as `coProofToken`, `cloProofToken` and `proof_token`, with the key at `GET /tenants/:tenantId/proof-public-key`. None of those is sent or served any more (the old key path is a 404): read `coReceipt`, `cloReceipt`, `receipt` (webhook and callback payloads, a claim's `ciGrantResult`) and `GET /tenants/:tenantId/receipt-public-key`. Records written before the rename are never rewritten: an event-log row or a claim's stored grant from before keeps `proof_token` (a claim's `ciGrantResult` is served with `receipt` beside it), and an idempotent replay of a consume recorded then answers with `coReceipt`. `GET /help/proofs` is now `GET /help/receipts`; the old topic name still answers. Receipts issued before the rename keep verifying: the signed payload has two versions, below, and version 1 never expires. This works on `crMode: Async` too: if the consume can't be granted immediately, the nonce rides along on the pending intent, and once the scheduler actually deducts the resources, the receipt isn't returned synchronously (there's no response left to return it on) — it's delivered via the `bucket.consumed` webhook/callback payload's `receipt` field instead. Reservations additionally support **commit tokens** (`rsCommitToken`, returned when `rrvNonce` is set on reserve): a token scoped to exactly one reservation, letting the relying party call `POST .../reservations/:rid/commit` **directly**, via an `X-Buckette-Commit-Token` header, with no `Authorization` header and no buckette API key ever issued to it. The commit itself, if the reservation had a nonce, also returns a receipt (same nonce, carried through reserve → commit → receipt). This is the pattern for "reserve capacity now, let someone else outside your system finalize it later" — e.g. reserve budget for a task, hand the commit token to the worker that actually performs it, and let that worker settle the reservation itself. A commit-token- authenticated request always commits the full held amount and must not send `crqAmounts` (see "Reserve vs. consume" above) — the token has no notion of amount, so a partial commit is only available to the tenant-authenticated (API key) caller, who can see and choose what to release. It may send `crqMetadata`, to say which session or model did the work (see "Reserve vs. consume" above). The token is good for that one commit and nothing else: every other route (consume, reserve, check, claims, cancel, refresh, reads, and the commit of any other reservation) refuses it, even on its own bucket. Same async caveat as consume: on `rrvMode: Async`, the commit token can't be minted until the scheduler actually creates the reservation, so it isn't in the initial `ReservePending` response — it arrives on the `bucket.reserved` webhook/callback payload's `commit_token` field once the hold is granted. The commit-token auth path is rate-limited **per tenant**. The caller holds no API key, so the token's own tenant is the finest-grained identity available, and it's charged against two dials: a dedicated commit-token limit (`ctnCommitTokenRateLimitRpm`/`ctnCommitTokenRateLimitBurst`, defaulting to 30rpm/burst-5 when unset — omitted means *default*, not unlimited) and the tenant's general `ctnRateLimitRpm`/`ctnRateLimitBurst`. Whichever binds first wins. A relying party retrying a transient failure a few times is fine; repeatedly hammering the endpoint with a leaked-but-still-valid token returns `429`. A commit token names its tenant by an opaque encrypted reference, not a readable id — so, unlike a receipt, it **can't be verified offline**. It is a bearer capability you present to buckette, not a receipt you check. If you need something a third party can verify independently, use a receipt. ```json // POST /buckets/:id/consume {"crAmounts": {"tokens": 500}, "crMode": {"tag": "Strict"}, "crNonce": ""} // -> {"tag": "ConsumeSuccess", "coConsumed": {...}, "coRemaining": {...}, // "coReceipt": "."} ``` Claims (`POST /claims`, see below) support the same pattern via `clrNonce` — one receipt per claim, covering every `ClaimGrant` the claim produced (so both `AllOf`, where every target paid, and `FirstOf`, where exactly one did, are attested uniformly, with nothing to correlate across multiple receipts): ```json // POST /claims {"clrTargets": [...], "clrStrategy": {"tag": "AllOf"}, "clrMode": {"tag": "Strict"}, "clrNonce": ""} // -> {"tag": "ClaimSuccess", "cloGrants": [...], // "cloReceipt": "."} ``` If the claim can't be granted immediately and is queued instead (`clrMode: Async`), the nonce rides along on the pending claim and the receipt is minted whenever the scheduler eventually grants it — there's no synchronous response to return it on, so fetch it from `GET /claims/:cid` (`ciGrantResult.receipt`) once `ciStatus` is `granted`, or read it off the `claim.granted` webhook/callback payload. See the `receipts` help topic (`GET /help/receipts`) for the exact receipt format and the relying party's verification steps. #### The signed payload: version 1 and version 2 A receipt is `base64url(payloadJSON) + "." + base64url(signature)`, unpadded, with an Ed25519 signature over the payload bytes exactly as decoded (no `alg` field). The payload comes in two versions, and **a verifier must accept both**: a receipt is a historical fact and is never re-signed, so version 1 stays valid with no end date. Version 1, every receipt issued before version 2 became the default, and what an instance set to version 1 still signs (its keys are sorted): ```json {"ppAmounts":{"tokens":3},"ppBucketId":"00000005-0000-0006-0000-000700000008","ppEventType":"bucket.consumed","ppNonce":"rp-nonce-1","ppOccurredAt":"2026-10-24T01:00:00Z","ppReservationId":null,"ppTenantId":"00000001-0000-0002-0000-000300000004","ppTyp":"proof","ppV":1} {"clpClaimId":"00000009-0000-000a-0000-000b0000000c","clpEventType":"claim.granted","clpGrants":[{"cgBucketId":"00000005-0000-0006-0000-000700000008","cgConsumed":{"tokens":3},"cgRemaining":{"tokens":7}}],"clpNonce":"rp-nonce-2","clpOccurredAt":"2026-10-24T01:00:00Z","clpTenantId":"00000001-0000-0002-0000-000300000004","clpTyp":"claim_proof","clpV":1} ``` Version 2, the same facts under unprefixed keys (`typ` is `receipt` for a consume or a reservation commit, `claim_receipt` for a claim; a claim's `grants` keep their `cg*` shape, the one the claim's response carries): ```json {"v":2,"typ":"receipt","tenantId":"00000001-0000-0002-0000-000300000004","bucketId":"00000005-0000-0006-0000-000700000008","nonce":"rp-nonce-1","amounts":{"tokens":3},"eventType":"bucket.consumed","occurredAt":"2026-10-24T01:00:00Z","reservationId":null} {"v":2,"typ":"claim_receipt","tenantId":"00000001-0000-0002-0000-000300000004","claimId":"00000009-0000-000a-0000-000b0000000c","nonce":"rp-nonce-2","grants":[{"cgBucketId":"00000005-0000-0006-0000-000700000008","cgConsumed":{"tokens":3},"cgRemaining":{"tokens":7}}],"eventType":"claim.granted","occurredAt":"2026-10-24T01:00:00Z"} ``` `reservationId` (`ppReservationId`) and `claimId` are always present, `null` when there is none. Version 2's keys come in a fixed order, but verify the bytes and then parse the JSON; don't depend on the order. **Which version an instance signs.** New receipts are version 2 by default. The instance's operator chooses, so an instance may still sign version 1, and every receipt issued before the switch is version 1. Read both. Both versions are signed by **the same tenant key**, served by the same `GET /tenants/:tenantId/receipt-public-key`; the key carries no version. **Telling them apart.** The version is which key is present, not a value in a shared key: - `v` present: version 2. `v` must be `2` (refuse any other value), and `typ` must be `receipt` or `claim_receipt`. - otherwise `ppV` present: a version-1 consume receipt; `ppV` must be `1` and `ppTyp` `"proof"`. Or `clpV` present: a version-1 claim receipt; `clpV` must be `1` and `clpTyp` `"claim_proof"`. - none of them: not a receipt (a commit token, for one, has `cpV`). **Verifying either.** 1. Split at the one `.` and base64url-decode both halves. 2. Read the tenant id *without trusting it yet* (`tenantId`, else `ppTenantId` / `clpTenantId`) and fetch that tenant's public key. 3. Verify the Ed25519 signature over the decoded payload bytes as they are. 4. Check the version and `typ` as above. 5. Check the nonce (`nonce`, else `ppNonce` / `clpNonce`) is the one you issued, and apply your own staleness policy to `occurredAt` (`ppOccurredAt` / `clpOccurredAt`): receipts carry no expiry. ```python import base64, json from nacl.signing import VerifyKey # PyNaCl def b64d(s): return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)) def read_receipt(payload: dict) -> dict: """The version-independent fields of a verified payload, or ValueError.""" if "v" in payload: if payload["v"] != 2 or payload.get("typ") not in ("receipt", "claim_receipt"): raise ValueError("unsupported receipt version or typ") p = payload kind = "claim" if p["typ"] == "claim_receipt" else "consume" return {"version": 2, "kind": kind, "tenantId": p["tenantId"], "nonce": p["nonce"], "occurredAt": p["occurredAt"]} for prefix, typ, kind in (("pp", "proof", "consume"), ("clp", "claim_proof", "claim")): if prefix + "V" in payload: if payload[prefix + "V"] != 1 or payload.get(prefix + "Typ") != typ: raise ValueError("unsupported receipt version or typ") return {"version": 1, "kind": kind, "tenantId": payload[prefix + "TenantId"], "nonce": payload[prefix + "Nonce"], "occurredAt": payload[prefix + "OccurredAt"]} raise ValueError("not a receipt") def verify(receipt: str, public_key_b64url: str, expected_nonce: str) -> dict: payload_part, sig_part = receipt.split(".") payload_bytes = b64d(payload_part) VerifyKey(b64d(public_key_b64url)).verify(payload_bytes, b64d(sig_part)) facts = read_receipt(json.loads(payload_bytes)) if facts["nonce"] != expected_nonce: raise ValueError("nonce mismatch") return facts ``` To get the key before verifying, call `read_receipt` on the unverified payload for its `tenantId` only, then fetch `GET /tenants/{tenantId}/receipt-public-key` (`tpkPublicKey`) and call `verify`. **Test vectors.** The payloads above, signed with the Ed25519 key whose 32-byte seed is `0x2a` repeated (a test key, used nowhere), give these receipts. Both verify against that one public key, and each is the consume payload above byte for byte: ``` version 1: eyJwcEFtb3VudHMiOnsidG9rZW5zIjozfSwicHBCdWNrZXRJZCI6IjAwMDAwMDA1LTAwMDAtMDAwNi0wMDAwLTAwMDcwMDAwMDAwOCIsInBwRXZlbnRUeXBlIjoiYnVja2V0LmNvbnN1bWVkIiwicHBOb25jZSI6InJwLW5vbmNlLTEiLCJwcE9jY3VycmVkQXQiOiIyMDI2LTEwLTI0VDAxOjAwOjAwWiIsInBwUmVzZXJ2YXRpb25JZCI6bnVsbCwicHBUZW5hbnRJZCI6IjAwMDAwMDAxLTAwMDAtMDAwMi0wMDAwLTAwMDMwMDAwMDAwNCIsInBwVHlwIjoicHJvb2YiLCJwcFYiOjF9.hbtj9Pq_XaNMovRvYyXv1QtegNXvKY3DurleolotH3ZVD_NCRRimOLPdgfLgf6jZoI6_55t8oGH_lWUYPqqeDA version 2: eyJ2IjoyLCJ0eXAiOiJyZWNlaXB0IiwidGVuYW50SWQiOiIwMDAwMDAwMS0wMDAwLTAwMDItMDAwMC0wMDAzMDAwMDAwMDQiLCJidWNrZXRJZCI6IjAwMDAwMDA1LTAwMDAtMDAwNi0wMDAwLTAwMDcwMDAwMDAwOCIsIm5vbmNlIjoicnAtbm9uY2UtMSIsImFtb3VudHMiOnsidG9rZW5zIjozfSwiZXZlbnRUeXBlIjoiYnVja2V0LmNvbnN1bWVkIiwib2NjdXJyZWRBdCI6IjIwMjYtMTAtMjRUMDE6MDA6MDBaIiwicmVzZXJ2YXRpb25JZCI6bnVsbH0.Z1YDuiO6T_AhxzkrwnQ1Pw2WMWzcgdMtGAhzzTBJb8S6M-9dL-jMWnT-rr_LR3oMrHI8pFJ7caYSJ1TvH5LwDg ``` ### Claims — consuming across several buckets at once A single `consume` call is atomic across the *dimensions* of one bucket. When one action must settle against several *buckets*, use a **claim** (`POST /claims`). A claim names a list of targets — each a bucket plus the per-dimension amounts to take from it — and a strategy: - **`AllOf`** — deduct from every target atomically, or from none. The canonical case: sending one email must pay 1 from the mailbox's rate-limit bucket *and* 1 from the campaign's quota bucket; if either would run dry, neither is touched. - **`FirstOf pickPolicy`** — deduct from exactly one target, chosen among the *eligible* ones (Active, and able to fully pay its own amounts right now) by `pickPolicy`. The canonical case: send from whichever of three mailboxes still has credit. The response names the bucket that paid, so route the work accordingly. A frozen, depleted, or short candidate is simply not eligible this attempt (not a hard failure by itself); the shortfall response diagnoses every candidate (shortfall, available, bucket status) when *none* are eligible. - `PickInOrder` — the first eligible target in request order. Use when you already have a priority among candidates (e.g. a preferred mailbox first, fallback mailboxes after). - `PickMostAvailable` — the eligible target with the most spare headroom after paying. Spreads load toward whichever bucket has the most room right now. - `PickRoundRobin` — the eligible target least recently paid from (based on its `bucket.consumed` event history; never-used targets go first). Spreads load evenly over time across an interchangeable pool, rather than always favoring request order or momentary headroom. ```json {"clrStrategy": {"tag": "AllOf"}, "clrMode": {"tag": "Strict"}, "clrTargets": [ {"ctBucketId": "", "ctAmounts": {"emails": 1}}, {"ctBucketId": "", "ctAmounts": {"emails": 1}}]} ``` ```json {"clrStrategy": {"tag": "FirstOf", "contents": "PickRoundRobin"}, "clrMode": {"tag": "Strict"}, "clrTargets": [ {"ctBucketId": "", "ctAmounts": {"emails": 1}}, {"ctBucketId": "", "ctAmounts": {"emails": 1}}, {"ctBucketId": "", "ctAmounts": {"emails": 1}}]} ``` `clrMode` reuses the consume modes: `Strict` (one atomic attempt), `Partial` (`AllOf` only — clamps each target independently, never fails, rejected for `FirstOf`), `Wait` (polls the strict attempt), and `Async` (queue the claim; see next section). Targets must be distinct buckets, 16 at most; buckets are locked in a deterministic order internally, so concurrent overlapping claims can't deadlock. Every bucket a claim deducts from gets a normal `bucket.consumed` event in its own log, so per-bucket stats and audit trails are unaffected by whether traffic arrives via `/consume` or `/claims`. Those rows carry a `claim_id` in their details, which is how you stitch one claim's per-bucket rows back together. For a queued claim it's the claim's id. A synchronous claim is never stored, so it mints a correlation id instead and returns it as `ClaimSuccess.cloCorrelationId`: it matches the event log, but `GET /claims/:cid` doesn't know it. A queued claim's lifecycle is in each target's log too: `bucket.claim_pending` when queued, then one of `bucket.consumed` (granted), `bucket.claim_notified` (`acAutoConsume: false`; its `amounts` names the bucket(s) that would pay), `bucket.claim_expired`, or `bucket.claim_cancelled` (a `DELETE`, or a target's subtree was deleted, which adds a `reason`). Rather than reading each target bucket's own event log and stitching by `claim_id` yourself, `GET /claims/:cid/events` returns that stitched timeline directly — every event across every touched bucket, oldest first, keyed on `claim_id` regardless of whether `:cid` is a queued claim's real id or a synchronous claim's `cloCorrelationId` (which has no row in `GET /claims/:cid`). Same `limit`/`offset` pagination as `GET /buckets/:id/events`. A bucket-scoped key sees it only when every bucket the claim touched lies in its subtree — otherwise, same as an unknown id, a 404. `POST /claims/check` mirrors `POST /buckets/:id/consume`'s `/check` — a non-mutating dry-run over the same `ClaimRequest` shape, useful to ask "would this multi-bucket claim be granted right now" without actually spending anything. It supports the same mode dispatch, including `Async`, which registers a notify-only queued claim (never auto-consumes, regardless of `acAutoConsume`) instead of failing on shortfall. ### Queued claims — scheduling consumption under constraints A claim with `crMode`-style `{"tag": "Async", "contents": {"acMaxDelaySecs": 3600, "acAutoConsume": true}}` that can't be granted immediately is **queued** (the response is `ClaimPending` with a claim id) and served by the scheduler's 30 s tick as a queue under constraints: - **Ordering** — `clrPriority` descending (higher served first, default 0), FIFO within a priority. Within the claims queue only: every tick serves the queued consumes and reserves first (see "The order the waiting queues are served in"), so a queued consume on a claim's bucket goes first whatever the claim's priority. - **Share per tick** — each tick attempts up to 25 pending claims per tenant. They are picked by priority, then least recently attempted first (never attempted, then the one attempted longest ago, then oldest), so claims that stay pending take turns instead of keeping the ones behind them out: a payable claim behind 30 that cannot be paid is reached on the next tick or the one after. The picked claims are served in the order above. - **Fairness** (`clrQueueDiscipline`) — `"QueueBlocking"` (default): a claim that still can't be granted holds its place, and later-queued claims touching any of its target buckets are skipped for that tick, so a large claim can't be starved forever by a stream of small ones draining the same buckets. It holds them on the ticks that do not pick it too: a later claim on one of its buckets that could be granted is not granted while it is pending, even when the later one was picked and it was not (it is not attempted then, so it holds its buckets until a tick picks and grants it). It holds them against an arriving claim too: an `Async` claim that its buckets could pay when it arrives is granted at once only if no pending `QueueBlocking` claim ahead of it (higher priority, or the same priority and older) names one of its buckets; otherwise it is queued behind that claim (`ClaimPending`, and `ciWaitReason: "behind"` with `ciBlockedBy` naming it). Synchronous modes (`Strict`, `Partial`, `Wait`) and `/claims/check` do not look at the queue. `"QueueOpportunistic"`: the claim yields — later claims may grab the resources first, maximizing throughput at the risk of starvation, and it holds nothing against an arriving claim. - **Depleted targets** — a target that has run out (`Depleted`) does not refuse an `Async` claim: it is queued like one that is short, and granted once a replenishment run or a top-up reactivates the bucket (since 2026-10-17; an `AllOf` with one `Depleted` target queues too). A `Frozen` or `Archived` target is still refused with `bucket_not_active`, and is reported ahead of a `Depleted` one when a claim names both. Synchronous modes and `/claims/check` answer a `Depleted` target as before (a refusal for `AllOf`, an ineligible candidate for `FirstOf`). The same holds for queued claim reservations below. - **Resolution** — with `acAutoConsume: true` the scheduler deducts as soon as the claim is satisfiable and fires a `claim.granted` webhook; with `false` it fires `claim.resources_available` and leaves the deduction to you (re-POST a synchronous claim). Hitting `acMaxDelaySecs` fires `claim.expired`. - **Frozen after queueing** — a target frozen after the claim was queued does not refuse it: the claim waits (an `AllOf` claim is not granted while any of its targets is `Frozen`) until the target is unfrozen or the deadline passes. A synchronous `AllOf` claim naming a `Frozen` target is refused with `422 bucket_not_active`, never answered with a `ClaimShortfall`. - **Registering key gone** — a queued claim (or claim reservation) whose API key has been revoked, expired or deleted since it was queued is given up at the next tick, unserved: `claim.expired` (`claim.reservation_expired`) with `reason: "registering key inactive"` (since 2026-11-10; see "What changes under a waiting intent"). - **Precedence** (`clrDependsOn`, since 2026-11-15) — a list of earlier claims of your tenant (at most 16, distinct) this claim may be granted only after: "B only after A", a permit before the dig, a pipeline's second stage after its first. A dependency counts as granted when its status is `granted` or `notified`. Each must be a queued claim your key can see (`400 unknown_dependency` otherwise; a synchronous claim has no id to name) that has not already ended (`409 dependency_failed` if it is `expired` or `cancelled`). - A synchronous claim (`Strict`, `Partial`, `Wait`) and `/claims/check` are refused with `409 dependency_not_granted` while a dependency is not granted; once every one is, the claim is served as if it named none. - An `Async` claim is queued at once (`ClaimPending`, no immediate attempt) and waits: `ciWaitReason: "dependency"`, `ciBlockedBy` the first dependency it waits on, `ciWaitingOn` all of them, and no `ciQueuePosition`. While it waits it is not in the queue at all: it is not attempted however funded its buckets are, it takes no share of the tick, and it holds none of its buckets even as `QueueBlocking` (a dependency has nothing to do with contention). - A later tick releases it into the queue once every dependency is granted, where it is served by priority like any claim (a claim granted on one tick has its dependents released on the next), or expires it when a dependency ends without being granted: `claim.expired` with `reason` `"dependency expired"`, `"dependency cancelled"` or `"dependency missing"` and `dependency` naming it, also on its `bucket.claim_expired` rows. Its own `acMaxDelaySecs` still applies while it waits. A chain (C after B after A) moves one link per tick. - `ciDependsOn` is the list the claim was made with. No cycle can form: a dependency exists before the claim that names it, and the list never changes. Claim reservations take no dependencies. Since `clrMode` reuses the exact same `AsyncConfig` type as `crMode`/`rrvMode`, a queued claim can also carry `acCallbackUrl`/`acCallbackSecret` — the same per-request callback described under "Per-request callback" above, subject to the same destination validation. It fires once, additively alongside any matching tenant-wide webhook, when the claim resolves (`claim.granted` / `claim.resources_available` / `claim.expired`). `GET /claims?status=pending` lists the queue, `GET /claims/:cid` shows one claim including its `grant_result` once resolved, and `DELETE /claims/:cid` cancels a pending claim (e.g. the workflow step was aborted). This is the piece to reach for when your workflow wants "run this step once budget frees up, in a fair order" rather than fail-or-block. Add `?bucket_id=` to narrow the list to claims touching one bucket (same param on `GET /claim-reservations` and `GET /pending-claim-reservations` below); `limit`/`offset` follow the usual 50-default/200-max pagination. Both reads also say **where a pending claim stands and why it still waits**, replaying the scheduler's next pass on the current balances (the same order, per-tenant share, blocked buckets and strategy rules the tick uses): - `ciQueuePosition` — its 1-based place in line: its place in your tenant's whole claims queue, whatever filter chose the page (first the 25 the next tick attempts, in the order it serves them, then the rest in the order later ticks pick them up: priority descending, then never or least recently attempted, then oldest), plus `ciIntentsAhead`. So `1` means nothing is served before it on its buckets. - `ciIntentsAhead` — how many queued consumes and reserves that take something (auto-consume or auto-reserve; notify-only ones take nothing and are not counted) name one of its buckets: the tick serves them before any claim. Already counted in `ciQueuePosition`. - `ciLastAttemptAt` — when a tick last picked the claim for an attempt; `null` if none has yet. - `ciWaitReason` — `short` (`ciShortfalls` lists, per target, what it lacks after what the queued consumes and reserves and the claims ahead of it would take), `behind` (`ciBlockedBy` is the `QueueBlocking` claim ahead that cannot be granted and holds one of its buckets; `null` when your key cannot see that claim), `not_attempted` (not among the 25 the next tick picks), `grantable` (nothing stops it: the next tick should grant it), `deadline_passed` (the next tick expires it), `bucket_not_active`, `bucket_missing`, `unknown_class`, `unavailable`, `unreadable`, or `dependency` (waiting on a claim in `ciWaitingOn`, see "Precedence" above; no `ciQueuePosition` then). It is a snapshot: a top-up, a consume or another claim before the tick can change the answer. All of these are `null` on a claim that is not pending. `ciGrantedAt` is when the scheduler granted a queued claim (`granted`, or `notified` for `acAutoConsume: false`), the same time as its receipt's and webhook's; `null` while pending, on expired and cancelled claims, and on claims granted before the field existed. ### Claim reservations — hold across several buckets, commit or release later `reserve`/`commit` (see "Reserve vs. consume" above) has a multi-bucket analog: `POST /claim-reservations` takes the same `clrrTargets`/`clrrStrategy` shape as a claim, and instead of deducting, bumps `raReserved` on every target it holds (`AllOf`: all of them; `FirstOf`: just the one winning target, chosen at reserve time same as a synchronous claim). Use this when several buckets' capacity needs to be held together before work starts, and finalized (or backed out) only once it's known whether the work succeeded: ```json // POST /claim-reservations {"clrrStrategy": {"tag": "AllOf"}, "clrrMode": {"tag": "Strict"}, "clrrTargets": [ {"ctBucketId": "", "ctAmounts": {"emails": 1}}, {"ctBucketId": "", "ctAmounts": {"emails": 1}}]} ``` `clrrMode` supports the full `Strict`/`Partial`/`Wait`/`Async` set, same as a plain claim. `POST /claim-reservations/:id/commit` deducts `raCurrent` and releases the hold on every target the reservation actually grabbed, in one transaction; `DELETE /claim-reservations/:id` releases the hold without deducting anything (the workflow step was aborted). `GET /claim-reservations[?status=]` and `GET /claim-reservations/:id` list/inspect them the same way as plain reservations. Each held bucket logs `bucket.reserved` with the reservation's `claim_reservation_id`, as do the `bucket.consumed` rows a commit writes and the `bucket.claim_reservation_released` rows a release writes. A commit's `ClaimSuccess.cloCorrelationId` is that same id. A queued claim reservation logs `bucket.claim_reservation_pending`, then either the `bucket.reserved` rows above or one of `bucket.claim_reservation_available` (auto-reserve off), `bucket.claim_reservation_expired` or `bucket.claim_reservation_cancelled`, all keyed by its `pending_id`. `GET /claim-reservations/:id/events` is the same stitched, oldest-first timeline as `GET /claims/:cid/events` above, keyed on `claim_reservation_id` instead. Like single-bucket reservations, set `clrrNonce` to get back a `crsCommitToken` — a signed, **tightly-scoped** commit token a relying party can present via `X-Buckette-Commit-Token` to finalize the reservation itself, with no buckette API key at all. Unlike the single-bucket version, this token carries **zero ambient scope** rather than being scoped to one bucket — a claim reservation can span several buckets, so there's no single bucket to confine it to — it is only ever accepted by the commit and release endpoints for the exact reservation id it names. Committing a nonce-bearing claim reservation returns a `ClaimSuccess.cloReceipt`, same verification path as any other claim receipt. On `clrrMode: Async`, the token can't be minted until the scheduler actually grants the reservation, so `ClaimReservePending` doesn't carry one — it's delivered via the `claim.reserved` webhook/callback payload's `commit_token` field once granted (see "Queued claim reservations" below), same async delivery single-bucket `rrvNonce` reservations use. #### Queued claim reservations (`clrrMode: Async`) A claim reservation that can't be granted immediately, or that a pending `QueueBlocking` claim reservation ahead of it holds behind (the two queues are served apart: a queued claim does not hold a claim reservation, nor the reverse), is queued (the response is `ClaimReservePending` with a pending id) and served by the same scheduler tick, under the same fairness rules as queued claims: `clrrPriority` (descending, default 0) and `clrrQueueDiscipline` (`"QueueBlocking"`/`"QueueOpportunistic"`, same semantics as `clrQueueDiscipline` — see "Queued claims" above). The `acAutoConsume` flag on the `Async` config is reused to mean "auto-reserve" here: - **`acAutoConsume: true`** — once the targets are fundable, the scheduler actually holds them and creates a real claim reservation (same as the synchronous path — you can `GET /claim-reservations?status=active` to find it, or read its id straight off the `claim.reserved` webhook/callback payload's `claim_reservation_id` field), then fires `claim.reserved`. If the original request carried `clrrNonce`, that payload also carries a `commit_token` field — the commit token that couldn't be minted synchronously (see "Claim reservations" above). - **`acAutoConsume: false`** — nothing is ever held. The scheduler fires `claim.reservation_available` once the targets *would* be fundable, and it's on you to re-POST `/claim-reservations` yourself to actually grab the hold. - **Deadline passed** — fires `claim.reservation_expired` and the pending intent is dropped. `GET /pending-claim-reservations[?status=]` lists the queue, `DELETE /pending-claim-reservations/:id` cancels one still pending. These are top-level routes (not nested under a bucket), same reasoning `/claims` itself already uses — a claim reservation can span several buckets. The list says where a pending one stands and why it waits, exactly as `GET /claims` does for claims (see "Claims" above): `pcrQueuePosition`, `pcrIntentsAhead`, `pcrWaitReason` (same values as `ciWaitReason`), `pcrBlockedBy`, `pcrShortfalls`, `pcrLastAttemptAt`, and `pcrGrantedAt` once the scheduler granted it (`granted`, or `notified` without auto-reserve). The queue is picked and served as the claims' is (25 per tenant per tick, least recently attempted first within a priority). Two differences follow from the scheduler serving this queue *after* the claims on every tick: the replay starts from the balances the claims ahead would leave, so a claim can make a claim reservation `short`; and positions and blockers count claim reservations only (a claim never holds a bucket against one), plus, in the position, the queued consumes and reserves on its buckets (`pcrIntentsAhead`), as for a claim. A granted auto-reserve claim reservation holds its amounts from the ones behind it. ### Auctions — bidding a price for units of a bucket A claim waits its turn; a bid says what the work is worth. A bucket's owner (`ScopeAdmin` on it) can put an **auction** on the bucket: at each round, on a schedule, a lot of whole **units** is allocated among the standing bids, highest price per unit first, and each winner receives a **child bucket** split off the auctioned one, with a key it collects once. buckette sorts the prices the bidders write and clears; it computes no value of its own. `GET /help/auctions` is the reference; this is the shape. ``` PUT /buckets//auction {"kind": "quantity", "unit": {"gpu_hours": 1}, "priceUnit": "points", "schedule": {"tag": "IntervalSecs", "contents": 300}, "reservePrice": 2, "pricing": "uniform", "award": {"expiresAfterSeconds": 3600, "keyScopes": ["ScopeConsume"]}} ``` `unit` is the bundle a bid buys multiples of (several dimensions in a fixed ratio are one good: `{"tokens": 1000, "requests": 10}`). `lot` defaults to `"available"`, every whole unit the bucket can supply; `class` names a consume class whose floors the lot stays above. This version takes `kind: "quantity"` and `visibility: "sealed"` only, and two fundings: `"unfunded"` (the default; the price is a number that is compared and recorded, nothing is spent) and `"funded"` (the price is spent from a bucket of the bidder's, below). A participant holds a key with **`ScopeBid`** on the bucket (mint one with `POST /api-keys`, `cakreScopes: ["ScopeBid"]`). That key places, reads, changes and cancels its own bids and collects what it wins, and nothing else: it cannot consume from the auctioned bucket or read its balance. ``` POST /buckets//auction/bids {"units": 40, "minUnits": 10, "price": 7, "expiresInSeconds": 3600} GET /bids?status=standing&bucket_id= -> this key's bids across auctions, newest first (an admin key: every bid of the tenant) GET /bids/ -> status standing | filled | cancelled | expired, awardBucketId, auctionKind POST /bids//key -> {"cakrKey": "...", "cakrBucketIds": [""]} (once) ``` A bid may carry `"callbackUrl"` (with optional `"callbackSecret"` and `"callbackMetadata"`), a one-shot callback exactly like an Async request's `acCallbackUrl`: the host on the callback allowlist and a live destination claim, else the bid is refused. It is POSTed, with the retry queue, for that bid's `bid.won`, `bid.outbid`, `bid.cancelled` and `bid.expired` (not `bid.placed` or `bid.changed`), in addition to any webhook. A bid read back (`POST /buckets//auction/bids`, `GET /bids`, `GET /bids/`, a `PATCH`) shows it as `callbackUrlTruncated`, never whole: scheme, host and port, the first path segment only when it is at most 16 characters with no digit, `…` for the rest of the path and `?…` for a query string, so that a token in the URL is not echoed back. `https://hooks.example.com/bids/t0k3n?sig=x` reads `https://hooks.example.com/bids/…?…`. It is `null` without a callback, and `callbackSecret` is never returned. At a round, bids are sorted by price, then placement (earlier first), then id; each is offered what is left of the lot, up to what it still wants, and a bid whose offer is under its `minUnits` is skipped for this round. The clearing price is the lowest price that received anything: under `uniform` every winner pays it, under `pay_as_bid` each its own. A bid partly filled stands for the rest, and a later win tops up the same award bucket. Watch `bid.won` / `bid.outbid` (webhooks, with the round's `clearing_price`) rather than polling, and read `GET /buckets//auction/rounds` for the per-bid lines (`won`, `partial`, `outbid`, `below_reserve`, `min_fill_unmet`). **Funded bids.** On an auction with `"funding": "funded"` and, say, `"priceUnit": "credits"`, every bid names `payerBucketId`, a bucket of yours with a `credits` dimension that the bid key reaches. `ScopeBid` alone holds the escrow there; the bid key needs no `ScopeConsume`, so it cannot spend the pool it bids on. The bid's whole worth (`price × units`) is held there as a reservation when you bid (`escrow`, `escrowReservationId` on the bid); a payer that cannot hold it refuses the bid (409 `escrow_shortfall`, with the shortfall), so one budget cannot back more bids than it holds. A round spends what you owe (`pricePaid × units awarded`, a `bucket.consumed` on the payer with the bid and round ids) and keeps holding what your remaining units are worth; cancelling, expiry and removal release it. Leave the escrow reservation alone: a key that also holds `ScopeConsume` can cancel it, and the next round then cancels the bid (`escrow_released`). The trade in a bid-only key: it can hold (never spend) any bucket among its roots that has the price dimension, by naming it as payer, so give a bidder a key whose roots are the pool and its own payer. **Bucket auctions.** `"kind": "bucket"` sells the bucket itself, once: the owner splits off a sub-bucket with what they mean to sell and lists it. ``` PUT /buckets//auction {"kind": "bucket", "closesAt": "2026-12-01T12:00:00Z", "priceUnit": "points", "reservePrice": 5, "award": {"expiresAt": "2026-12-08T12:00:00Z"}} GET /buckets//auction -> catalogue: resources, replenishConfig, expiresAt, awardExpiresAt, keyScopes POST /buckets//auction/bids {"price": 12} ``` No unit, schedule, lot or class. A bid is for the bucket (`units` 1 or absent) and stands until `closesAt`. At `closesAt` the highest bid at or above the reserve wins; under `uniform` it pays the second-highest price, or the reserve when it bid alone (so set a reserve). The winner collects a key on the listed bucket (`POST /bids//key`), which then expires at `award.expiresAt`; every other bid ends (`expired`, reason `outbid`), and the auction closes. A sold bucket cannot be listed again (409 `bucket_sold`). Every bid read back (`GET /bids`, `GET /bids/`, the auction's bid list) says which kind of auction it is on, `"auctionKind": "quantity"` or `"bucket"`: a list across auctions can tell a price for a whole bucket from a price per unit without reading each auction. For an agent: bid when the bucket is scarce and the work has a value you can state; claim when it does not. Spend what you win with the collected key, which is scoped to the award bucket alone and expires with it; reclaim the award (`POST /buckets//reclaim`) when done to give the rest back to the pool for the next round. ### Split / reclaim `split` carves a child bucket out of a parent's balance (the allocation is deducted from the parent, atomically). `reclaim` archives a child and returns its remaining balance to the parent (`ReclaimUnusedOnly`) or all of it (`ReclaimAll`). The request body carries `rrMode` and `rrCascade`, both required: `{"rrMode": "ReclaimAll", "rrCascade": false}` (`rrCascade: true` archives the child's own children first; `rrReason` is an optional note). A child gets the dimensions `srAllocation` names, each with the parent's `raMode`, plus every `Reporting` dimension of the parent that it does not name, at `0`, so the child carries the parent's meters. An amount must be positive, except that `0` is accepted on a `Reporting` dimension. A child does not inherit the parent's replenishment schedule either, nor its threshold configuration or unspent warning, and its metadata is only `srMetadata` (nothing is copied from the parent's). The balance check is on the `available` amount (`raCurrent - raReserved`, from zero up) of every dimension named, a `Reporting` one included: a split moves what exists, so it never takes the parent below zero (`409 insufficient_resources` otherwise). A retry of a split that carried an `srIdempotencyKey` is answered with the original child even when the parent is no longer `Active` (frozen or archived), whereas a split without a key on such a parent is refused with `422 bucket_not_active`. This is the natural pattern for "budget per sub-agent" or "budget per task run": split off a bounded child bucket before dispatching work, reclaim what's left when it finishes. Reclaim is not deletion — the bucket stays readable, with its history, in `archived` status. Use `DELETE /buckets/:id` when you actually want it gone. The parent is credited whatever the reclaiming key is scoped to, so a sub-agent's key scoped to its own bucket can hand its leftovers back. A top-level bucket (`rrParentId: null`) has nowhere to return them and keeps them. A `Depleted` parent the returned amount lifts above its floor on a gating dimension is `Active` again, as after a replenish; the roll-up of a deleted child does the same. Holds: `ReclaimAll` returns held amounts too, so it voids every reservation and claim reservation on the buckets it archives (`rrReservationsVoided`), and they can no longer be committed; `ReclaimUnusedOnly` leaves the held amounts and the holds in place, so an in-flight commit still lands on the archived bucket. Reclaiming a bucket that is already archived is refused (`422 bucket_not_active`). By default, a child's `raMaximum` per dimension is capped at exactly what it was allocated — it can be replenished back up to that amount, but no higher, even if the parent had a much larger (or no) cap. Pass `"srChildLimitMode": "InheritParentMax"` to instead give the child the parent's own ceiling for that dimension, matching the pre-existing behavior. Independently, `"srShrinkParentMax": true` reduces the parent's own `raMaximum` by the allocated amount for each split dimension (floored at the parent's post-split balance) — useful when the parent's ceiling should shrink alongside its balance rather than staying fixed. ### Deletion `DELETE /buckets/:id` removes a bucket and its whole subtree for good. It is two-phase and returns **202**, not 204: the bucket is already gone as far as every read is concerned, but erasing it finishes in the background. Synchronously, before the 202 returns: - Whatever balance the subtree still holds is rolled up to the nearest ancestor that isn't itself being deleted (`bdsReclaimed`). A top-level bucket has nowhere to put it, so it's reported as `bdsDropped` rather than silently counted as returned. - The subtree stops existing for `GET /buckets/:id`, `GET /buckets`, consume, check, split, reserve, the Prometheus export, and the tenant's bucket quota — the plan slot is free again immediately. - API keys delegated into the subtree stop working (`bdsApiKeysRevoked`), outstanding reservations are voided (`bdsReservationsVoided`), and queued claims naming it are cancelled. Afterwards a background sweep drains the subtree's history — event log, replenishment log, reservations, pending consumes/reserves, recorded `crIdempotencyKey` outcomes, the `srIdempotencyKey` records of splits made *from* the subtree's buckets, delegated keys — in small batches, then removes the bucket rows. Poll `GET /buckets/:id/deletion`, which keeps answering after the bucket itself is gone: `bdsRemainingRows` counts down and `bdsDecommissionedAt` stays null until it reaches zero. A `bucket.deleted` webhook fires on request, `bucket.decommissioned` on convergence. Deletion is irreversible and there is no grace period. If you want spending to stop but the bucket to stay readable, freeze it (`PATCH /buckets/:id` with `{"pbrStatus": "Frozen"}`) or reclaim it — both keep the bucket and its history. A repeat `DELETE` on the same bucket returns 404, since by then it is invisible to you. `GET /buckets/deletions` lists every deletion still draining for your tenant, oldest first, with the same fields as the per-id route. Use it when you don't already hold the ids: a deleted bucket is invisible to `GET /buckets`, so this is the only way to enumerate what's still in flight. Converged deletions drop out of the list — the per-id route still answers for those — and a bucket-scoped key only sees deletions rooted inside its own subtree. `DELETE /buckets/:id/hard` is the low-level primitive underneath: fully synchronous, no roll-up, and it fails with 409 while anything still references the subtree — which, given every bucket has a `bucket.created` event from birth, is the normal answer unless you have already purged its history. It exists for tenant teardown, not for clients. ### History retention A tenant can have a retention window: how many days of event and replenishment history buckette keeps before a background sweep deletes the rest. **By default there is no window — history is kept forever**, unless the tenant's plan sets one. When a window is configured, the practical effects are: - `GET /buckets/:id/events` and `GET /buckets/:id/replenishments` return only what still falls inside it. On a short window (24 hours, say) these can legitimately come back empty on a bucket that has seen plenty of traffic. This is configuration, not a bug or an outage. - `GET /buckets/:id/stats`' log-folded totals (`bsTotalConsumed`, `bsTotalReplenished`) shrink accordingly, while `bsTotalConsumedAllTime`/`bsTotalReplenishedAllTime` keep counting from bucket inception — they live on the bucket row, not in the logs. If you need a lifetime figure, read the *AllTime fields; they are exact regardless of retention. See "Bucket statistics" above. - Nothing else is touched. Buckets, balances, reservations, claims, webhooks and API keys are unaffected — retention only prunes the two log tables. Deletion happens on the scheduler's 30s tick in bounded batches, so a tenant that has just had a window applied to years of accumulated history drains over many ticks rather than in one step. Old rows still being present shortly after a window is set is expected. `GET /tenants/me/usage` answers "what is this window actually keeping?" with an ordinary `ScopeRead` key — `tuHistoryRowsPerDay` is how fast you write log rows, estimated from the trailing 7 days, and `tuHistoryRetainedRows` is roughly what your window keeps at that rate (null when history is kept forever). `tuHistoryDeletedThrough` is the watermark before which nothing survives, and `tuHistoryRowsDeleted` the lifetime count removed. Treat the rate as an estimate: it's wrong for a bursty or seasonal tenant, and on a window shorter than 7 days it's measured over the window itself, since the sweep has already removed the rest of the sample. Like the other reporting reads (see "Reporting / observability mode"), it may lag the latest writes by the replication delay. **The window is set for you, not by you.** Retention is configured when your tenant is provisioned (it comes with the tenant's plan), so as an API caller you observe a window rather than change one — there is no tenant-authenticated route that sets it. Worth knowing anyway, because it bounds what can be done to you without your noticing: *lengthening* a window is an ordinary plan edit, while *shortening* one deletes audit history irreversibly and takes a separate, explicitly-confirmed call. A plan change cannot quietly truncate your logs. ### Claim-history retention A second, distinct optional window governs claims, claim reservations and pending claim reservations instead of the two logs above — these are operational queue state, not an audit log, so it's a separate dial rather than a reuse of history retention. **By default there is no window — claim history is kept forever**, same fail-safe default. When configured, a background sweep deletes *resolved* rows past the window (`granted`/ `notified`/`expired`/`cancelled` for claims and pending claim reservations, `committed`/`released`/`cancelled` for claim reservations) — a still-`pending` or still-`active` row is never touched regardless of age. Practical effect: `GET /claims`, `GET /claim-reservations` and `GET /pending-claim-reservations` can return fewer historical entries than you might expect on a tenant with this window configured, the same way event/replenishment history can disappear under the log-retention window above. Same set-for-you, monotonic-lengthen / explicit-confirmed-shorten shape — there is no tenant-authenticated route that sets it either. ### Replenishment Buckets can refill automatically on a schedule or on demand via `POST /buckets/:id/replenish` (e.g. triggered by a payment webhook). The schedule itself is set with `PUT /buckets/:id/replenish-config` (`ReplenishConfig`, `rcSchedule`: `IntervalSecs`, `DailyAtUTC`, `Every`, `Daily`, `Weekly` or `Monthly`, below) and applies to the **whole bucket, not per dimension** — one `rcSchedule` refills every dimension the bucket has. If different dimensions need different refill cadences, they can't share a bucket and must be split into separate buckets. Carryover policy (`CarryoverNone`/`Limited`/`Unlimited`) controls whether unused balance rolls over, and overflow policy (`OverflowDiscard`/`Reject`) controls what happens if a refill would exceed `raMaximum`. This is separate from and unrelated to `raMode` — it governs top-ups, not consumption. **Schedule forms.** `IntervalSecs` (`{"tag":"IntervalSecs","contents":300}`, free-running: counted from the scheduler pass that last fired it) and `DailyAtUTC` (`contents: [9,30]`, hour 0-23 and minute 0-59 checked on write; a schedule stored before that check with a value out of range, such as `[25,99]`, fires every day at its minutes from midnight modulo a day, here 02:39) are the original two and stay. Four forms say what a person means, with named fields: ```json {"tag":"Every","count":6,"unit":"hours","anchor":"2026-10-12T00:00:00Z"} {"tag":"Daily","at":"09:00","zone":"Europe/Paris"} {"tag":"Weekly","weekday":"monday","at":"09:00","zone":"UTC"} {"tag":"Monthly","day":1,"at":"00:00","zone":"UTC"} {"tag":"Monthly","day":"last","at":"23:59","zone":"UTC"} ``` `unit` is seconds, minutes, hours, days or weeks (fixed lengths: an `Every` counts absolute time from its `anchor`, so a day is 86400 s whatever a local clock does; the step may not be shorter than the scheduler's 30 s cycle). The anchor is an RFC 3339 instant, stored and returned as written; one in the past is the usual case, one in the future means nothing fires before it. `at` is `HH:MM`; `zone` is `UTC` or an IANA name and is required. Unknown fields, zones and out-of-range values are a 400. `Monthly` with a `day` the month lacks fires on the month's last day (31 is 30 April) and the next month is on the day again; `"last"` says it outright. A local time a clock change skips fires just after the gap; one that happens twice fires the first time. What you PUT is what `GET /buckets/:id/replenish-config` returns in `rcvConfig`, unchanged, and `rcvSchedule` beside it is core's reading of it: `text` ("every month on the 1st at 00:00 UTC"), `nextRunAt` and `period` (`start`, `end` of the period now; null for `IntervalSecs`). `POST /replenish-schedule/preview` with a schedule as the body (any valid key, no scope; no bucket is read or written) returns that same reading for a schedule not yet saved, after the same checks the PUT makes, so a form can show "every Sunday at 00:00 Europe/Paris, next run ..." before saving. A missed run is paid by counting the occurrences of the rule since the bucket was due (one dose each, in one event, capped at 500), and the next run is the next occurrence after now, on the same grid: a monthly bucket whose scheduler was down for two months is paid three doses and is next due on the coming 1st, whatever time the pass found it. Where something needs a period's length (a `linear` floor's release, a request's ETA, a poll's backoff), it is the real one: 31 days in October, 30 in November, a 23-hour day across a clock change. Each scheduled or polled entry of `GET /buckets/:id/replenishments` carries `rlPeriodStart` and `rlPeriodEnd`, the period that run closed (the one the `/periods` ledger closes in the same transaction); both are null on older entries, on an API refill, and for `IntervalSecs`, which has no grid. **Reset dimensions: a meter cleared at every scheduled run** (`rcResetDimensions`, a list of dimension names). The listed dimensions start from zero at every scheduled run, its catch-up of missed doses included, whatever `rcCarryover` says: a `CarryoverNone` for those dimensions only. A listed dimension the run's dose does not name is set to 0; one it names is set to its dose. A manual top-up (`POST /buckets/:id/replenish`) resets none of them: it adds its amounts under `rcCarryover` and leaves a listed dimension as it is. The case it is for: a `Reporting` dimension counting calls, cleared each month, next to a `Locking` balance that carries over: `{"rcAmounts": {"tokens": 1000}, "rcCarryover": "CarryoverUnlimited", "rcOverflow": "OverflowDiscard", "rcResetDimensions": ["calls"]}`. Any mode may be listed. Absent or null is `[]`. `PUT` answers 400 `unknown_dimension` for a dimension the bucket does not have and `reset_dimension_polled_set` for one a `PollSet` source maps. **Tree envelope: a refill net of what the children still hold** (opt-in, `rcEnvelope`). The rule it enforces: a team can never spend more than its allowance in a period. With `"rcEnvelope": {"teScope": "EnvelopeSubtree"}` on a parent whose monthly allowance is 1,000,000 tokens, a leftover child still holding 300,000 at the refill means the parent is topped up by 700,000 and the tree totals 1,000,000; the child keeps its 300,000 until spent or reclaimed (nothing is clawed back: children holding more than the allowance leave a dose of 0). `EnvelopeSubtree` counts every live descendant and is the scope to use; `EnvelopeChildren` counts direct children only, for nested allowances that each carry an envelope. Held is the descendants' `raCurrent` floored at 0, per dimension of the dose (an amount under reservation is inside `raCurrent` and counts; archived and expired descendants hold nothing); the carry-over and overflow policies then run on the reduced dose as usual. The `bucket.replenished` event and webhook of such a run carry `envelope: {held, withheld}` next to `amounts` (the requested dose) — `withheld` is not a discard, the children hold it. Every such run also records it, whether or not the balance changed: `rlAmountsWithheld` on `GET /buckets/:id/replenishments` (`{}` when it withheld nothing, `null` on a run with no envelope or from before 2026-11-15), `dpWithheld` on `GET /buckets/:id/periods` and `lfWithheld` on `GET /buckets/periods`, booked with the run's credit to the period the run opens. Scheduled fixed-dose runs only: `POST /buckets/:id/replenish` ignores it, and `PUT` refuses it with a polled source (`envelope_requires_fixed_amounts`) or without a schedule (`envelope_requires_schedule`). Absent or `null` is off, and every config written before the field reads back and behaves as before. **What counts as "replenished" is what was actually added, not what was asked for.** `repAdded` in the response, the replenishment-log entry (`GET /buckets/:id/replenishments`' `rlAmountsAdded`) and the stats totals all record, per dimension, the part of the new balance this refill supplied: an `OverflowDiscard` refill counts only what fit under `raMaximum`, and a rejected `OverflowReject` refill counts 0. Balance that `CarryoverNone`/`Limited` drops is forfeited, not a negative refill — the refill's own grant still counts in full. The amount you *requested* stays on the `bucket.replenished` event (`GET /buckets/:id/events`, `details.amounts`) and in the webhook payload of a scheduled refill. **What a refill discards is recorded too, by cause.** The shape is the same everywhere, cause → dimension → amount: ```json {"carryover": {"tokens": 40}, "overflow": {"tokens": 10}} ``` - `carryover` — balance that was in the bucket and that the reset removed: all of it under `CarryoverNone`, the part above `rcCarryoverMax` under `CarryoverLimited`. This is allowance that went unused. - `overflow` — the part of the dose above `raMaximum` that `OverflowDiscard` turned away. It never entered the balance. The two are different kinds of amount, which is why they are not one number: per dimension, `closing = opening + credited − carryover` and `requested = credited + overflow`. Add them together only if "everything that did not survive" is really what you mean. (One edge: a balance already above `raMaximum` — the maximum was lowered under it — is clipped by the cap, and the clipped part is counted under `overflow`.) Only amounts above zero appear. A dimension or a cause that discarded nothing is absent, and a refill that discarded nothing reads `{}`. | Where | Field | |---|---| | `POST /buckets/:id/replenish` response | `repDiscarded` | | `GET /buckets/:id/replenishments`, per run | `rlAmountsDiscarded` — `null` on a run older than the feature: not recorded, which is not zero (`rlAmountsWithheld` beside it is the tree envelope's, not a discard) | | `GET /buckets/:id/stats` | `bsTotalDiscardedAllTime` — running total on the bucket, this bucket only, started at `{}` when the feature shipped (no backfill) | | `bucket.replenished` event | `details.discarded` | | `bucket.replenished` webhook | `discarded` (scheduled or polled refill), `repDiscarded` (manual) | | `bucket.replenish_discarded` webhook | `discarded`, the same from every source | The event and the webhook are written only when the balance **changed**. A `CarryoverNone` reset of an untouched bucket forfeits the whole balance and refills it to the same figure: the log row and the running total record the forfeit, the event and the webhook do not fire. Read the total or the log for a complete account. **To be told of a discard as it happens, subscribe to `bucket.replenish_discarded`.** It is fired once for every refill that discarded more than zero (scheduled, polled, or `POST /buckets/:id/replenish`), **whether or not the balance changed**, and never for one that discarded nothing: ```json {"event": "bucket.replenish_discarded", "bucket_id": "...", "details": { "source": "periodic", "discarded": {"carryover": {"tokens": 40}}, "credited": {"tokens": 100}, "balance": {"tokens": 100}}} ``` - `source` is `"periodic"`, `"poll"`, or the request's `repSource`. `credited` is what landed; `balance` is the balance after the refill, for the dimensions `discarded` names. `doses` appears only on a late scheduled refill that credited several missed doses at once, and `metadata` only on a manual top-up that sent `repMetadata`. - One per refill, so at most one per bucket per scheduled run. A replayed `repTransactionId` fires nothing. - Webhook only: it is not in `GET /buckets/:id/events`. The record is the refill's row in `GET /buckets/:id/replenishments`. - The notice *before* a scheduled discard is `bucket.unspent_expiring` (under "Threshold webhooks" below); its `expiring` has this `discarded`'s shape. Not counted: - a refill skipped whole by `OverflowReject` — it records 0 credited and discards nothing; - the balance left in a bucket that expires; - amounts requested for a dimension the bucket does not have. Treat the set of causes as open: ignore a cause you do not know. A scheduled refill that fires late (the scheduler process was down, or a tick was otherwise delayed past one or more scheduled firings) credits the missed doses in that one tick rather than only ever crediting one dose per tick regardless of how much time passed — e.g. a bucket on a 30s interval schedule that goes 10 minutes without a tick is credited 20 doses' worth when it next runs, not 1. This is capped (a bucket dormant far longer than any real outage doesn't credit unbounded doses) and still goes through the same carryover/overflow policy as an ordinary refill — `OverflowReject` still rejects the whole event, all-or-nothing, if the *scaled* amount would exceed `raMaximum`, exactly as it would for an ordinary one-dose refill. Replenishment-log entries for a caught-up refill carry `catch_up_doses > 1`; ordinary refills leave it null. **An `IntervalSecs` shorter than the scheduler's cycle is the same mechanism, every time.** The scheduler makes a pass, waits `hsSchedulerCycleSecs` seconds (reported by the unauthenticated `GET /health`; 30 today) and makes the next. A bucket is refilled at the first pass after it is due and its next due time is counted from that pass, not from the old due time. Any interval of one second or more is accepted, but one shorter than the cycle does not fire that often: once per pass the bucket gets, in one event, as many doses as whole intervals went by since the last pass. - every 5 s: 6 doses about every 30 s; - every 7 s: 4 doses about every 30 s (the 2 seconds left over are dropped, not carried to the next pass); - every 16 s to 29 s: 1 dose about every 30 s, the same as every 30 s. Because it is one event with the dose multiplied, the policies do not give what N-second firings would: `CarryoverNone` leaves `doses x amount` in the bucket after the pass rather than one amount, and `OverflowReject` skips the whole event when the multiplied dose does not fit, even if a single dose would have. If you need a rhythm faster than the cycle, set the interval to the cycle and multiply the amount yourself, so that the stored schedule says what happens. The same rounding applies above the cycle: an interval that is not a multiple of it fires at the first pass after it is due (every 45 s is about every 60 s). What a caught-up refill **discards** is computed on that one application too: the carryover rule runs once, on the balance found when the refill finally ran, and the overflow is that of the scaled dose. A use-it-or-lose-it bucket (`CarryoverNone`, maximum 100, dose 60) found holding 40 after three missed periods records `{"carryover": {"tokens": 40}, "overflow": {"tokens": 140}}` — one forfeit of 40, and 140 of the 240 turned away — not the four separate resets an on-time schedule would have recorded. Do not read a caught-up row's discard as per-period waste. #### Idempotent on-demand replenishment (`repTransactionId`) An on-demand `POST /buckets/:id/replenish` call can carry an optional `repTransactionId :: Text` — a caller-chosen idempotency key, not generated by buckette. Two replenish calls with the same `repTransactionId` apply at most once: the balance mutation only happens on the first call, and every later retry with that same id is a safe no-op. A replay answers 200 with `repAdded: {}`, `repDiscarded: {}` and `repForgiven: {}` and the bucket's *current* balance in `repNewBalance` — not a copy of the first call's response — and fires no event or webhook. So read "did my top-up apply" from the first response, or from `GET /buckets/:id/replenishments`, not from a replay's `repAdded`. This matters any time the caller triggering the replenish (a payment webhook handler, a cron job, a control-plane sweep) can't guarantee exactly-once delivery of its own — e.g. a webhook that might fire twice, or a caller that crashes after the replenish succeeds but before it records that fact locally and retries on its next pass. The id is **unique per tenant**, not scoped to one bucket: a second replenish on *another* bucket of the same tenant with an id already used is the same no-op. Another tenant's use of the same string is invisible and never collides. It is remembered for **seven days**: an id resubmitted more than seven days after its first use is applied again, so a caller that may retry later than that keeps its own record. Pick something that already uniquely identifies the real-world event (a payment provider's charge id, or a deterministic string you derive yourself, e.g. `"tenant-deletion-quota-release-"` for a one-off compensating credit tied to a specific tenant) rather than a random value per attempt, since a random value defeats the point — it would make every retry look like a brand-new event. The id is checked atomically with the mutation it guards, so it's safe even against concurrent duplicate calls, not just sequential retries. This is the same mechanism the "Credit-based billing" example below uses for Stripe webhook replenishment, and is the general answer whenever you need to call replenish from a system that doesn't share a transaction (or even a database) with buckette, and can't otherwise guarantee its own call happens exactly once. #### Why a credit happened (`repMetadata`) The same call takes an optional `repMetadata :: Value` — arbitrary JSON, same 1 KiB cap as consume's `crMetadata`. `repSource` is a low-cardinality label saying *what kind* of thing credited the bucket (`"stripe"`, `"control-plane:billing"`); `repMetadata` says *which* one — the charge id, the invoice number, the admin who clicked. Read it back from the `bucket.replenished` entry in `GET /buckets/:id/events`, which is also where the audit trail lives: the replenishment log (`GET /buckets/:id/replenishments`) records the amounts and the source, not this. It is spliced into the `bucket.replenished` webhook payload too, so a subscriber can correlate the notification with the payment that caused it without a lookup. #### Polling a balance (`rcSource`) Some buckets should track a number that lives **outside** buckette: a prepaid balance at a payment provider, a parts count in an inventory system, a quota left on an upstream API. Instead of a fixed dose, name an endpoint and buckette reads it on the bucket's schedule. `rcSource` on `ReplenishConfig` is `{"tag": "FixedAmounts"}` (the default, and what every existing config reads back as) or `{"tag": "PollEndpoint", "contents": {...}}`: ```json PUT /buckets/:id/replenish-config { "rcSchedule": {"tag": "IntervalSecs", "contents": 300}, "rcAmounts": {}, "rcCarryover": "CarryoverUnlimited", "rcCarryoverMax": null, "rcOverflow": "OverflowDiscard", "rcSource": {"tag": "PollEndpoint", "contents": { "psUrl": "https://billing.example.com/v1/prepaid/acct_42", "psMode": "PollSet", "psMapping": {"credits": {"pmPointer": "/balance/available"}}, "psAuth": {"secret": "billing-token"} }} } ``` - **Mapping.** `pmPointer` is an [RFC 6901](https://www.rfc-editor.org/rfc/rfc6901) JSON pointer into the response body; the value must be a JSON number or a string that parses as one (`"1234.50"`). `pmScale` (optional, positive) is multiplied in first, for cents to units. A dimension with no mapping is left alone. If *any* pointer fails to resolve, the whole poll fails: partial credits would make the log unreadable. There is no expression language on purpose; if you need arithmetic across fields, put a thin proxy in front of the source. - **`PollSet` vs `PollBump`.** Use `PollSet` when the endpoint reports *what is available* (a prepaid balance, a quota left): the fetched number is the target, and the credit is `max 0 (target - current)` per dimension, capped by `raMaximum` as usual. Use `PollBump` when it reports *what arrived* (a delivery, a top-up): the fetched number is a dose through the bucket's carryover and overflow policy. `PollSet` requires `CarryoverUnlimited`. **A poll never debits.** A `PollSet` target below the current balance credits 0 and records a `bucket.poll_below_current` event with both numbers, so you can see the drift without buckette ever lowering a balance outside `consume`. - **Schedule.** `rcSchedule` is required and at least **60 seconds** apart. A late tick polls once (a reading is a point in time, so missed slots do not multiply). - **Failure.** A failed poll (network, timeout, non-2xx, a redirect, a body over 64 KB, not JSON, a mapping error) credits **nothing**, never a stale value. The bucket's next attempt is pushed out by exponential backoff (`interval * 2^failures`, capped at 6 hours) and a `bucket.poll_failed` event and webhook fire on the fifth consecutive failure, then again each time the streak reaches a further power of two. `GET /buckets/:id/replenish-config` returns `{rcvConfig, rcvPollState}`; `pollState` has the streak, last outcome (a short label such as `http_status` or `timeout`) and last fetched value. - **Credentials.** Never put a token in the config. `PUT /secrets/:name` (`ScopeAdmin`, body `{"psrValue": "..."}`) stores one, encrypted at rest; `psAuth: {"secret": name}` sends it as `Authorization: Bearer`. Values are write-only: `GET /secrets` lists names and creation times, and a `PUT` on an existing name rotates it. The routes answer `503 secrets_not_configured` on an instance where stored secrets are not enabled. - **Egress.** The URL passes exactly what a webhook URL does (see "Outbound destination validation" below): `https` (unless the instance exempts the host), never a non-routable address, on the tenant's callback allowlist **and** covered by a verified destination. It is checked when you `PUT` and again at every poll, GET only, no redirects followed, 64 KB response cap. - **Idempotency.** Each poll credit is logged with `source: "poll"` and transaction id `poll::`, so one scheduled slot credits at most once. The `bucket.replenished` event's `details` carry `pollHost` (the host only, never the URL) and the raw `fetched` values. - **Cost.** Poll a **few top-level buckets** and split down to the children agents actually consume from; polling once per agent is the anti-pattern. A plan can cap external refreshes per tenant per hour: past the cap, polls wait for the next hour and record `bucket.poll_throttled`. ### Outbound destination validation buckette makes outbound HTTP requests on your behalf — webhook deliveries, per-request callbacks, and the `POST /webhooks/:id/test` probe — so every URL you name goes through two independent checks. They answer different questions and a URL has to pass both. `GET /help/webhook-validation` is the runtime version of this section. **1. Can buckette connect here?** `https` only, no redirects followed, and the host must resolve to a globally routable address: loopback, private (`10/8`, `172.16/12`, `192.168/16`, `fc00::/7`), link-local (`169.254/16` — the cloud instance-metadata endpoint — and `fe80::/10`), CGNAT and multicast are all refused, including their IPv6-mapped spellings. No tenant setting satisfies this check; it exists because a shared instance would otherwise let any admin-scoped key aim buckette's own network position at internal services. A literal IP is classified when you register the URL, a hostname when the delivery is actually made — that being the only moment its address is known. An instance can be set up to exempt named hosts; a shared one is not. **2. Are you entitled to deliver here?** Two controls, and a URL has to satisfy **both**. They are not alternatives — they answer different questions, for different beneficiaries: | control | who sets it | question | protects | |---|---|---|---| | callback allowlist | your admin, via `PUT /callback-allowlist` | where may buckette *ever* deliver for this tenant? | you, against exfiltration by your own lower-scoped keys | | verified destination | whoever operates the endpoint, via `POST /destinations` | did anyone there *agree* to receive this traffic? | buckette, against being an abuse relay | So the allowlist is the outer bound and a claim is the proof inside it. Neither widens the other: a claim on a non-allowlisted host authorizes nothing, and an allowlisted host with no claim authorizes nothing. **Setting up a webhook is therefore two steps, in this order** — allowlist the host, then claim the destination. `POST /destinations` refuses a claim outside the allowlist rather than accepting one that could never authorize anything. A claim comes in two kinds: | kind | how you prove it | what it authorizes | |---|---|---| | `url` | echo back a challenge buckette POSTs to it | that one exact URL | | `domain` | publish a TXT record under the domain | every URL under that domain | ### Claiming one URL (`kind: "url"`) ```json // POST /destinations {"cdrKind": "url", "cdrValue": "https://your-service/hooks/buckette"} ``` buckette immediately POSTs a challenge to that exact URL: ```json {"event": "verification.challenge", "challenge": "<64 hex chars>", "destination": "https://your-service/hooks/buckette", "tenant_id": "...", "timestamp": "..."} ``` with an `X-Buckette-Event: verification.challenge` header. Answer **HTTP 200 with the `challenge` value echoed anywhere in the first 4KiB** of the body — bare, as `{"challenge": "..."}`, or inside your own envelope — and the destination is verified. **You do not need the token in advance**: read it out of the request and echo it. That is what makes this work for a URL whose DNS you don't control (a Zapier/n8n hook, a tunnel endpoint), and it is why the echo is the mechanism rather than the 200: an internal admin port or a metadata endpoint accepts a POST just as happily, but only an endpoint built to receive this will hand the value back. A failed check is **not** an API error — the call returns 201 with `dstStatus: "claimed"` and the reason in `dstLastError`, since "your endpoint returned 500" is not the same kind of problem as "your request was malformed". Re-run it with `POST /destinations/:id/verify`, read the history with `GET /destinations/:id/checks`, and retract with `DELETE /destinations/:id` (reversible — re-claiming revives the same record with a fresh token). A URL claim authorizes exactly one URL after normalization (lowercased scheme and host, default port and fragment dropped, path and query kept byte-for-byte). **A sibling path is a different destination** and needs its own claim: a server is free to treat `/hook` and `/other` as unrelated, so granting both would grant more than you proved. ### Claiming a domain (`kind: "domain"`) ```json // POST /destinations {"cdrKind": "domain", "cdrValue": "hooks.example.com"} // -> {"dstStatus": "claimed", // "dstRecordName": "_buckette-challenge.hooks.example.com", // "dstRecordValue": "buckette-verification=<64 hex chars>", ...} ``` Publish that TXT record, then `POST /destinations/:id/verify`. Other vendors' tokens can share the same name — every TXT record there is scanned, so you don't have to clear it out. The token is stable for the life of the claim, so a re-check never asks you to re-publish. A verified domain authorizes the domain and every subdomain, at any path. **If your callback URLs vary per request** — the usual case for `acCallbackUrl`, where each outstanding request has its own resume URL — this is the kind you want; there is no finite set of URLs to claim one at a time. Claiming a subdomain directly narrows the grant, which is the right posture if you delegate subdomains away. Public suffixes (`com`, `co.uk`, …) are refused up front, since nobody can publish a TXT under them. ### Claims are re-checked, and can decay A claim is not proof-once-and-forever. buckette re-checks in the background — domains daily, URLs weekly — and a URL claim whose webhook has delivered successfully inside the window is skipped, since a real 200 is better evidence than a challenge. A verified claim that fails a re-check moves to `failing` and **keeps authorizing deliveries**; one transient DNS blip must not revoke a working integration. Only three consecutive failures (spanning at least 72 hours) demote it to `invalid`, which does stop authorizing. A single pass anywhere in that window restores `verified`. `dstStatus` and `GET /destinations/:id/checks` are where you see this; a manual `verify` never demotes a claim, only the background sweep does. **This is enforced at delivery time, not just when you register the URL.** Retracting a claim, narrowing the allowlist, or letting a claim decay stops deliveries for webhooks that already exist. `GET /webhooks` reports `whiDestinationStatus` per webhook (`ok` / `not_allowlisted` / `unproved` / `unenforced`) so a webhook that has gone quiet says why. ### Enforcement level **How strictly this is enforced is set per instance, not per tenant**, and since 2026-08-15 the level is **`strict` unless the instance says otherwise**: an unauthorized URL is rejected at registration and blocked at delivery. The other two levels are `warn`, which allows the URL and records what `strict` would have refused — a transition aid, not a steady state — and `off`, which skips the entitlement question entirely on an instance with a single tenant (`GET /webhooks` then reports `whiDestinationStatus: "unenforced"`). The scheme/address check above is never relaxed by any of these. **Webhooks and per-request callbacks are checked identically** — same two checks, same enforcement level, same exempt-host list, whether the URL is being named or delivered to. There is no case where one is accepted and the other refused for the same URL under the same tenant. The practical difference is not in the rules but in which kind of claim fits: a `url` claim covers one exact URL, so a caller whose callback URLs vary per request claims the **domain** instead. ### Threshold webhooks Attach a `ThresholdConfig` (`PUT /buckets/:id/threshold-config`) to get webhooks as a dimension's balance crosses levels. The route has no `GET`: read the configuration back from `GET /buckets/:id`, field `bucketThresholdConfig`. Levels are checked on the scheduler's 30 s tick, and a tick sends only the level a dimension is at, so a balance that falls past both levels between two ticks sends `bucket.critical_balance` alone. - `bucket.low_balance` / `bucket.critical_balance` — **predictive** warnings, fired when balance drops below a configured `tsWarning`/`tsCritical` level (absolute or percent-of-`raMaximum`). Only fire for `Locking` dimensions, since they anticipate a block that can only happen in `Locking` mode. - `bucket.overflow` / `bucket.depleted` — fired when balance is **already** out of bounds (`raCurrent > raMaximum`, or `raCurrent <= 0`). Fire for both `Locking` and `Reporting` dimensions — this is how you find out a `Reporting` dimension has gone negative or over cap, since nothing blocked it from getting there. A `MeteredOverage` dimension is `depleted` at its line (never without one). - `bucket.overage` — a `MeteredOverage` dimension went below zero (and is above its line). Fires once per dip: back at or above zero the level clears. `low`/`critical` apply to `MeteredOverage` as to `Locking`. - `bucket.overage_cleared` — the partner of `bucket.overage`: that dimension is back at zero or above (a top-up, a reset). Its `level` is the level the dimension is at now. - `bucket.balance_recovered` — a dimension that was `low`, `critical` or `depleted` is back to normal. The event that closes an alert opened by the three above (`previous_level` says which); `critical` to `low` fires nothing, only the return to normal does. A dimension only needs an entry in `ThresholdConfig` to be watched for `overflow`/`depleted`; adding `tsWarning`/`tsCritical` layers the predictive levels on top for `Locking` dimensions. Every one of these events carries, besides `dimension`, `level`, `amount` and `fraction`, the bucket's whole `balance` (`{"": }`) and `next_refill_at` (its next scheduled replenishment, `null` when none), read under the bucket's lock with the crossing. `bucket.replenished` carries the same two keys after the refill (from all three sources). Together they let a subscriber keep "available now" per dimension, and when it will grow, without polling `GET /buckets/:id`. The per-event shapes are in `GET /help/events`. ### The warning before a reset Thresholds watch a balance going down. The opposite waste is a balance that a scheduled replenishment is about to throw away: nothing carried over (`CarryoverNone`), only part of it (`CarryoverLimited`), or a dose that does not fit under `raMaximum` (`OverflowDiscard`). A bucket can warn about it in time to spend it: ``` PUT /buckets/:id/unspent-warning (ScopeAdmin) {"lead_seconds": 3600} ``` Off by default, per bucket. The response is the bucket, which shows the setting as `bucketUnspentWarning` (`null` when unset). `DELETE /buckets/:id/unspent-warning` removes it. `lead_seconds` is a positive number of seconds, at most 31622400 (366 days), else a 400 `invalid_unspent_warning`. Once the next scheduled run is no further away than the lead **and** would discard something from the balance as it is, the scheduler (30 s tick) fires one `bucket.unspent_expiring` webhook: ```json {"event": "bucket.unspent_expiring", "bucket_id": "...", "details": { "reset_at": "2026-10-14T00:00:00Z", "seconds_until_reset": 3590, "lead_seconds": 3600, "expiring": {"carryover": {"tokens": 40}}, "balance": {"tokens": 40}}} ``` - **One per bucket and per run**, with no minimum amount. It is not repeated as the run approaches; the following run gets its own. A bucket that enters the window with nothing to lose and is credited later is warned then. - **`expiring` is a forecast**, in the shape of `bucket.replenished`'s `discarded` (cause, then dimension): `carryover` is balance the reset forfeits, `overflow` is the part of the dose the maximum turns away. What is spent after the warning is not discarded, so the `discarded` of the `bucket.replenish_discarded` that follows is the figure of record (no such event when, in the end, nothing was discarded). - **Not sent** for a bucket with no schedule (the setting is accepted and waits for one), a polled bucket (`rcSource: PollEndpoint`), a run `OverflowReject` would skip whole, or a frozen, archived or deleted bucket. A split's child does not inherit the setting. - Webhook only: it is not in `GET /buckets/:id/events`. `GET /help/unspent-warning` and `GET /help/events` are the references. ### The warning before running out A threshold fires once the balance is already low. A bucket with a replenishment schedule can instead warn when, at the rate it is being spent, it will run out before its next refill: ``` PUT /buckets/:id/depletion-warning (ScopeAdmin) {"margin_seconds": 300} or {"margin_share": 0.1} optional: "window_seconds": 600 ``` Off by default, per bucket. The rate is what the bucket consumed over a trailing window (`window_seconds`, else a tenth of the period, at least 300 seconds), per dimension, divided by the window. Carried forward from what is available now, it gives a time each dimension reaches zero; when that is more than the margin before the next scheduled run (`margin_share` is a share of the period), the scheduler fires one `bucket.depletion_projected` webhook. Example: 100 units refilled hourly, spent at 2 a minute, is empty 10 minutes before the refill, so a 300-second margin warns. ```json {"event": "bucket.depletion_projected", "bucket_id": "...", "details": { "next_refill_at": "2026-11-16T13:00:00Z", "seconds_until_refill": 2990, "period_seconds": 3600, "window_seconds": 360, "margin_seconds": 300, "short": {"tokens": {"available": 80, "consumed_in_window": 12, "rate_per_second": 0.0333, "empty_at": "2026-11-16T12:50:10Z", "seconds_before_refill": 590}}}} ``` - **One per bucket and per run.** Changing the setting forgets which run was warned about. - `GET /buckets/:id/depletion-warning` (ScopeRead) answers the setting, the projection as it stands now (every dimension spent in the window, with `short` saying which would warn) and `warned_for`; `DELETE /buckets/:id/depletion-warning` removes the setting. A malformed setting is a 400 `invalid_depletion_warning`. - **Not sent** for a bucket with no schedule, a `Reporting` dimension, a dimension already at zero (that is the `depleted` threshold), or a frozen, archived or deleted bucket. Webhook only. `GET /help/depletion-warning` and `GET /help/events` are the references. ### Prometheus metrics export A tenant's plan can disable this export entirely (`metrics_enabled` in its plan/quota configuration, see the `tenants` help topic) — both routes below 403 in that case. `GET /buckets/metrics/prometheus/default?parent_id=&status=` formats your tenant's current bucket balances as Prometheus text exposition format, so you can point your own Prometheus at it and get dashboards/alerts for free instead of building threshold-webhook plumbing (above) for every case. It's authenticated the same way as every other bucket route (`Bearer` API key) and respects the calling key's bucket scope — a bucket-scoped key only ever exports its own subtree, so a shared instance never leaks one tenant's data to another. It's computed fresh on every scrape rather than accumulated in a counter, so the numbers are the bucket's actual balances at the time of the request. Filtering reuses `GET /buckets`'s `parent_id`/`status` query params, plus `dimension`/`dim_min`/`dim_max` (restrict to buckets whose named dimension's `raCurrent` falls within `[dim_min, dim_max]`) and `sort=dimension_asc` or `dimension_desc` (order by that dimension's `raCurrent` instead of `created_at desc`; requires `dimension` to also be set — buckets missing the named dimension are excluded by `dim_min`/`dim_max` and sort last). Unlike `GET /buckets`, there's no pagination — a scrape wants the whole filtered set in one response — but archived buckets are excluded by default (pass `?status=archived` to see them explicitly), and the export caps out at 10,000 buckets; past that it truncates and emits `buckette_export_truncated 1` so you have a visible signal to narrow the scrape with `?parent_id=` (or a `dim_min`/`dim_max` bound). `GET /buckets` itself pages (`?limit=`, default 50, capped at 200; `?offset=`) and reports the total row count matching every filter except limit/offset via an `X-Total-Count` response header — the body stays a bare JSON array either way, so existing callers that decode it directly don't need to change to keep working past 50 buckets, they just won't see the rest without paging. `?root_only=true` restricts to buckets with no parent — useful for walking a tenant's top-level buckets without paging past however many descendants sort ahead of them under the default `created_at desc` order. `GET /buckets` also takes `?q=` for text search, `?label=` for tag matching, and `?with_parents=true`/`?with_descendants=true` for ancestry context: - `q` matches with precedence, not union — the first tier with a hit wins: an exact `bucketId` match, then a case-insensitive substring match against any `buckette/*` metadata value (`budgetz/*` too, until 2026-11-10), then a substring match against any metadata value at all (string-valued only — a numeric or object field's stringified form doesn't count). An empty `q` matches everything; a non-empty `q` with no hit in any tier returns zero rows rather than falling back further. - `label` is exact membership in the `buckette/labels` metadata array (case-sensitive; `budgetz/labels` is read when a bucket has no `buckette/labels`), and combines with `q` conjunctively — a bucket must match both. - `with_parents`/`with_descendants` append each matched bucket's ancestors and/or descendants to the response as extra rows. This is context, not more matches: it doesn't affect `X-Total-Count` or pagination, which both still reflect only what `q`/ `label`/the other filters matched. `GET /buckets/labels` lists the labels to filter by, across every page: the distinct `buckette/labels` strings of every bucket `GET /buckets` matches with the same `q`, `status`, `used_within_hours` and `unused_for_hours` (it takes no `label`), plus those of the context rows `with_parents` / `with_descendants` add, each with the number of those buckets carrying it: ```json {"blrLabels": [{"blcLabel": "env:prod", "blcCount": 41}, {"blcLabel": "agent:triage", "blcCount": 3}], "blrTruncated": false, "blrLimit": 200} ``` Most common first, then by label. `limit` defaults to 200 and is at most 1000; `blrTruncated` says the least common labels were left out. `ScopeRead`; a bucket-scoped key sees the labels of its subtree only. `GET /buckets` also filters by last use. Use means a `bucket.consumed` event, the same thing `GET /buckets/recency` counts: - `used_within_hours=H` keeps buckets consumed from at least once in the last H hours. - `unused_for_hours=H` keeps buckets with no consume in the last H hours. A bucket never consumed from counts as unused. - Together they are a band: `?used_within_hours=168&unused_for_hours=24` is "used this week, but not in the last day". H is a whole number of hours from 1 to 8760 (365 days, the longest window `GET /buckets/recency` takes). A value outside that range, or `unused_for_hours` not below `used_within_hours`, is a `400` with `errCode` `invalid_last_use_filter`; it is never clamped. Both count in `X-Total-Count`, and `GET /buckets/export/csv` takes them too. Use is read from the event log, which is pruned to the tenant's history retention: past that horizon every bucket looks unused, which says something about the log, not about the bucket. Emitted gauges, labeled `bucket_id` and `dimension`: - `buckette_bucket_current` — `raCurrent` - `buckette_bucket_reserved` — `raReserved` - `buckette_bucket_maximum` — `raMaximum`, only emitted when set - `buckette_bucket_fraction_remaining` — `raCurrent / raMaximum`, 0-1, only emitted when `raMaximum` is set Two counters, same labels, all-time totals that only grow (so `increase()` over a window is the overage of that window): - `buckette_bucket_overage_total` — what was consumed below zero on a `MeteredOverage` dimension (`bsTotalOverageAllTime`) - `buckette_bucket_forgiven_total` — debt below zero that a reset wrote off (`bsTotalForgivenAllTime`) Both are emitted for every `MeteredOverage` dimension (at 0 until it first goes below zero) and for any other dimension that has a recorded total (one flipped to another mode since). An alert on a customer entering overage: `increase(buckette_bucket_overage_total[1h]) > 0`. Example alert rule, a bucket that's stayed under 10% for half an hour: ```yaml - alert: BucketteBucketLow expr: buckette_bucket_fraction_remaining < 0.1 for: 30m labels: severity: warning annotations: summary: "Bucket {{ $labels.bucket_id }} ({{ $labels.dimension }}) below 10%" ``` #### Unauthenticated secret-URL variant If your Prometheus setup can't send a custom `Authorization` header (or you just want a bookmarkable URL), generate a per-tenant shared secret and use: ``` GET /buckets/metrics/prometheus/secret-url/:tenantId/:token?parent_id=&status= ``` Same output as the `default` route above, but resolved by the secret in the URL instead of Bearer auth, and always tenant-wide (there's no bucket-scope narrower than "the whole tenant" to apply here — see below for why). Manage the secret with (ScopeAdmin, and **only an unscoped/tenant-root API key** — a bucket-scoped key is rejected with 403, even with `ScopeAdmin`, since the URL this secret unlocks always exports the *entire* tenant with no auth at all; letting a delegated sub-team key mint one would be a scope escalation the rest of the API never allows): - `POST /tenants/metrics-secret` — generate (or rotate) the secret. Returns `{"tmsrSecret": "bms_..."}` **once** — it's stored hashed, like an API key, and never shown again. Generating a new one immediately invalidates the old URL. - `GET /tenants/metrics-secret` — `{"tmssConfigured": bool, "tmssSetAt": timestamp | null}`. Status only, never the secret itself. - `DELETE /tenants/metrics-secret` — unset it; the secret-url route then 404s for this tenant until a new one is generated. The secret-url route itself returns the same `404` whether the tenant doesn't exist, has no secret configured, or the token is simply wrong — so it can't be used as an oracle to enumerate tenant ids or probe whether a tenant has the feature turned on. ### CSV export ``` GET /buckets/export/csv?subtree_id=&parent_id=&status=&dimension=&dim_min=&dim_max=&sort=&q=&label=&used_within_hours=&unused_for_hours= ``` The same filtered bucket set the Prometheus route above formats as metrics, rendered as a spreadsheet instead — for the case where somebody wants the estate in a pivot table rather than on a dashboard. Bearer-authenticated and bucket-scope-respecting like every other bucket route, and returned as `text/csv` with a `Content-Disposition` filename, so `curl -OJ` and a browser both save it rather than printing it. One row per bucket. The columns are: ``` bucket_id,parent_bucket_id,status,created_at,expires_at,.current,.maximum,.reserved,... ``` The dimension columns are the **union of every dimension appearing anywhere in the export**, sorted — buckets in one tenant don't share a dimension set, so a header derived from the first row would drop the others' values off the right-hand edge. A bucket that doesn't carry a dimension leaves those cells **empty, never zero**: absent and zero are different facts, and a zero there reads as a depleted budget to anything summing the column. `raUnit`/`raMode` are deliberately not columns — they're per-dimension configuration, constant across the file, and available from `GET /buckets`. **Formula injection.** A field that a spreadsheet would evaluate as a formula (it starts with `=`, `+`, `-`, `@`, a tab or a carriage return) is written with a leading `'`, so that it opens as text (OWASP's "CSV injection" guidance). A plain number is exempt, so a negative balance like `-12.5` stays a number. The only tenant-written text in this export is the dimension names in the header: a dimension called `=cost` gives the columns `'=cost.current`, `'=cost.maximum`, `'=cost.reserved`. Strip one leading `'` from a header field to get the dimension name back. **With the per-period ledger.** `?periods_window_days=N` adds the figures of `GET /buckets/periods` (below) for the exported buckets, over that window (same clamp, open periods included). It is opt-in so that the plain export's column positions never move. The header becomes: ``` bucket_id,parent_bucket_id,status,created_at,expires_at,periods_since,periods_until,periods, .current,.maximum,.reserved, .credited,.consumed,.shortfall,.shortfall_unkeyed,.overage,.forgiven,.discarded.carryover,.discarded.overflow,.low, .subtree.credited,.subtree.consumed,.subtree.shortfall,.subtree.shortfall_unkeyed,.subtree.overage,.subtree.forgiven,.subtree.discarded.carryover,.subtree.discarded.overflow,... ``` `periods_since`/`periods_until` are the window actually used and `periods` is the number of closed periods summed for that bucket. A bucket with nothing recorded for a dimension leaves the ledger cells empty; a cause that discarded nothing in a row that exists is `0`. Each discard cause is its own `.discarded.` column; treat the set of causes as open. Filters: everything the Prometheus export takes (`parent_id`, `status`, `dimension`, `dim_min`, `dim_max`, `sort`), plus `q`/`label` and `used_within_hours`/`unused_for_hours` from `GET /buckets`, plus one of its own: - **`subtree_id`** — one bucket *and all its descendants*. This is the "download this budget and everything carved out of it" case; `parent_id` is direct children only and excludes the named bucket itself. It **intersects** with the calling key's own bucket scope rather than replacing it, so naming a bucket outside your scope narrows the export to nothing — it can never widen it. Archived buckets are excluded unless you pass `?status=archived`, same as the Prometheus export. No pagination; the export caps at 10,000 buckets and sets `X-Buckette-Export-Truncated: 1` on the response when it hit that cap — narrow with `subtree_id`/`parent_id` if you see it. (The signal is a header rather than a row because a notice inside the body would corrupt the table, which is exactly what `buckette_export_truncated` can get away with and a CSV can't.) Unlike the two Prometheus routes, this one is **not** gated on the plan's `metrics_enabled` flag: it's a reformatting of `GET /buckets`, which every `ScopeRead` key already reaches. ### The per-period ledger Each bucket keeps a ledger per **period**: what was credited, consumed, refused (`shortfall`, exact, for consumes sent with a `crIdempotencyKey`; `shortfallUnkeyed`, an upper bound, for the others), discarded by a replenishment (by cause: `carryover`, `overflow`, and `expired`, the balance left when the bucket expired outright, booked on its last period; never sum across causes without meaning to), moved in from or out to another bucket (`movedIn` / `movedOut`), what was consumed below zero on a `MeteredOverage` dimension (`overage`, part of consumed), the debt a reset wrote off (`forgiven`), what the tree envelope kept out of the period's refill because the children still held it (`withheld`: not credited, not discarded), and the lowest available balance reached (`low`). A period is closed by a scheduled replenishment run; a bucket with no schedule gets one period per UTC calendar day, closed by the first write of a later day. Two reads: ``` GET /buckets/:id/periods?limit=&before=&subtree= GET /buckets/periods?window_days=&bucket_id=&dimension=&sort=&limit=&include_open= GET /buckets/period-series?granularity=&window_days=&bucket_id=&subtree=&dimension=&limit=&include_open=&group= ``` The first lists one bucket's periods, newest first, open one included (`GET /help/dashboards` has the fields). With `subtree=true` each of those periods also holds the flows of every bucket under it (a scheduled period of theirs counts where it closed, a day where it started; balances are left out, and a move between two of them is in both `dpMovedIn` and `dpMovedOut`): the record to size a parent whose children do the consuming. The second sums the periods of a window for every bucket the key reaches, **one row per bucket and dimension**, ordered and limited by the server: ```json { "lgRows": [ { "lrBucketId": "…", "lrParentId": null, "lrTitle": "team-a", "lrStatus": "Active", "lrDimension": "tokens", "lrPeriods": 6, "lrOpenPeriod": true, "lrFirstPeriodStart": "2026-10-06T00:00:00Z", "lrLow": 120, "lrOwn": {"lfCredited": 7000, "lfConsumed": 5200, "lfShortfall": 0, "lfShortfallUnkeyed": 40, "lfDiscarded": {"carryover": 1680}, "lfClasses": {"batch": {"cfConsumed": 3000, "cfShortfall": 0, "cfShortfallUnkeyed": 40}, "interactive": {"cfConsumed": 2000, "cfShortfall": 0, "cfShortfallUnkeyed": 0}}, "lfUnclassed": {"cfConsumed": 200, "cfShortfall": 0, "cfShortfallUnkeyed": 0}, "lfMovedIn": 0, "lfMovedOut": 2000}, "lrSubtree": {"lfCredited": 9000, "lfConsumed": 6100, "lfShortfall": 300, "lfShortfallUnkeyed": 40, "lfDiscarded": {"carryover": 1680}, "lfClasses": {"batch": {"cfConsumed": 3500, "cfShortfall": 300, "cfShortfallUnkeyed": 40}}, "lfUnclassed": {"cfConsumed": 2600, "cfShortfall": 0, "cfShortfallUnkeyed": 0}, "lfMovedIn": 2000, "lfMovedOut": 2000} } ], "lgTruncated": false, "lgSort": "discarded", "lgLimit": 100, "lgWindowDays": 7, "lgWindowLimitedBy": "default", "lgSince": "2026-10-06T12:00:00Z", "lgUntil": "2026-10-13T12:00:00Z", "lgIncludesOpen": true } ``` - **Per consume class.** Each dimension of a period (`dpClasses` / `dpUnclassed`) and each `lrOwn` / `lrSubtree` (`lfClasses` / `lfUnclassed`) splits consumed and shortfall by the class a consume was made as: its `crClass`, or else the bucket's default class (`GET /help/classes`). A class has `cfConsumed`, `cfShortfall` (exact), `cfShortfallUnkeyed` (upper bound) and `cfOverage` (its part of `overage`, on a `MeteredOverage` dimension). They are **parts** of the dimension's `consumed`, `shortfall`, `shortfallUnkeyed` and `overage`, never added to them (overage booked before 2026-10-17 is all unclassed); the unclassed remainder is what no class accounts for: consumes that named no class on a bucket with no default, and the commits of holds that carry no class (a hold keeps the class it was taken as, and its commit is booked under it; holds granted before this shipped commit as unclassed). Periods that were open when this shipped count a class only from then on; the rest of their consumed total reads as unclassed. Shortfall of a claim is not in the ledger, class or not. - `lrOwn` is the bucket alone; `lrSubtree` is the bucket plus every descendant. `lrLow` is the bucket's own (a balance has no subtree sum). - **A move is neither credited nor consumed.** Balance that goes from one bucket to another is booked on both: moved out of the bucket it left (a split's allocation on the parent, a reclaim on the bucket reclaimed), moved in on the one it reached (the split's child, which credits nothing for the balance it is born with; a reclaim's parent; the ancestor a deleted subtree rolls up to; a transfer commit's destination, whose source books it as consumed). So a period reconciles (opening, less consumed and moved out, plus moved in and what was credited after the opening dose, is the closing balance), and a subtree's `lfCredited` counts an allocation once; a move between two buckets of a subtree is in both its `lfMovedIn` and its `lfMovedOut`. A move out lowers `low` like any debit. Periods closed before 2026-10-17 have no moved figures, and children split off before then show their allocation as credited. - **Periods are counted whole.** A closed period counts when it *ended* after `lgSince`, so the earliest one may start before it (`lrFirstPeriodStart`). The open period counts unless `include_open=false`. - **The window actually used is in the answer.** `window_days` defaults to 7, is clamped to 1..365 and then to the tenant's history retention (`historyRetentionDays`): a closed period is readable while it ended within that window, and there is no separate limit on periods. `lgWindowLimitedBy` is `request`, `default`, `minimum`, `maximum` or `history_retention`. - `bucket_id` narrows to a bucket and its descendants (404 if the key cannot see it); `dimension` keeps one dimension. - `sort` (largest first): `credited`, `consumed`, `shortfall`, `shortfall_unkeyed`, `discarded` (default; summed across causes for the ordering only), `low`, and `subtree_credited`, `subtree_consumed`, `subtree_shortfall`, `subtree_shortfall_unkeyed`, `subtree_discarded`. `limit` defaults to 100, max 1000; `lgTruncated` says more matched. - To find allowance that went unused: `sort=discarded` ranks what replenishments forfeited, `sort=low` ranks the balance never touched. To find unmet demand: `sort=shortfall` or `sort=subtree_shortfall`. - Deleted buckets appear in no row and in no subtree sum. **As a time series.** `GET /buckets/period-series` returns the same ledger as points on a calendar axis: `srPoints`, oldest first, each `{"spStart": "2026-10-12T00:00:00Z", "spDimension": "tokens", "spCredited": 500, "spConsumed": 35}`, summed over the buckets named. `granularity` is `day` (default), `week` (from Monday) or `month`, all UTC. `bucket_id` can be repeated (up to 500) and none means every bucket the key reaches; `subtree=true` adds descendants, each counted once. **A closed period counts whole on the calendar bucket it closed in**, so a weekly schedule's period is one point, not seven; the open period counts on the bucket of `srUntil` (`include_open=false` leaves it out). The window and its clamp are the ledger's (`srWindowDays`, `srWindowLimitedBy`, `srSince`, `srUntil`), and the first week or month can be partial. `limit` (default 1000, max 5000) keeps the most recent points (`srTruncated`). An id the key cannot see matches nothing. **One series per bucket.** `group=bucket` returns a series for each matched bucket instead of their sum, under the same window, `bucket_id`, `subtree`, `dimension` and `include_open` rules. Each point adds `spBucketId` and `spClasses`: `{"spStart": "…", "spDimension": "tokens", "spCredited": 0, "spConsumed": 35, "spBucketId": "…", "spClasses": {"batch": 20}}`. A point holds that bucket's **own** figures, so a parent's point leaves out its children's and the points of a subtree add up with each bucket counted once. `spClasses` is the part of `spConsumed` made as each consume class (non-zero only); the rest was made with no class, and credited has no class. Points come oldest first, then by bucket and dimension; `srGroup` is `"bucket"` and `srBucketCount` says how many buckets matched. At most 500 buckets: more is a 400 `too_many_buckets`, refused before any figure is read, so name fewer buckets, drop `subtree` or use a narrower key. `limit` defaults to 20000, its maximum, and keeps the most recent points. **Summed per value of a metadata key.** `group=metadata:` (for example `group=metadata:team`, percent-encoded) sums the matched buckets per value of one bucket metadata key, under the same window, `bucket_id`, `subtree`, `dimension` and `include_open` rules. Each bucket's own figures count under its own value. Each point adds `spGroupKind`: `value` with `spGroup` the key's value, `none` for the buckets without the key (always shown), or `other` for every value past the 20 that consumed the most in the window: `{"spStart": "…", "spDimension": "tokens", "spCredited": 0, "spConsumed": 35, "spGroup": "search", "spGroupKind": "value"}`. `srGroup` is `"metadata"`, `srGroupKey` the key and `srGroupValues` how many distinct values had a figure. A key under the reserved `buckette/` prefix is also read under its older spelling. Its cost is the sum's, so there is no bucket bound beyond `bucket_id`'s; `limit` is as for `group=bucket`. **Pacing within the open period.** The ledger says how much the open period has consumed so far, not when. For a burndown to the next reset, ``` GET /buckets/pacing?bucket_id=&dimension=&slice_minutes=&periods_back= ``` returns, for each named bucket (`bucket_id` repeated, 1 to 100), what it consumed in each slice of its open period, per consume class and dimension: `prBuckets`, each with `pbPeriodStart`, `pbNextReset` (null without a schedule), `pbPeriod` (the open period as `GET /buckets/:id/periods` shows it), `pbCurrent` and `pbAvailable` (the balance now, and less what is held), `pbClassConfig` (the classes and their floors), and `pbSlices`, each `{psStart, psClass, psConsumed}` (`psClass` is `""` for a consume made with no class). Slices are `pbSliceSeconds` wide (`slice_minutes`, default 60, clamped to 5..1440, widened so that a period has at most 500) and start at `pbSlicesFrom`: the period start, or the history-retention cutoff when that is later, because slices are read from the event log, which retention prunes. A bucket the key cannot see is listed in `prNotFound`, not a 404. The balance at a slice's end is the opening balance less what was consumed up to it, plus what was credited (which `pbPeriod` totals and no slice carries); projecting it to the reset is yours to do. `periods_back=1` reads the last closed period instead (2 the one before, up to 366), to compare a period with the previous one: each entry then has `pbPeriodEnd`, `pbNextReset` is that end, `pbCurrent`/`pbAvailable` are the closing balance and the slices stop at the end. A bucket with fewer closed periods on record (or one past the history retention) has `pbPeriodStart` null. **Consumption per session, model or worktree.** Put the attribution in each consume's `crMetadata` (or each commit's `crqMetadata`), for example `{"session": "s-42", "model": "opus", "worktree": "pool-1"}`, and read it back grouped by one of those keys: ``` GET /buckets/:id/consume-breakdown?key=session&dimension=usd&periods_back=&window_days=&subtree=&limit= ``` `brGroups` has one `{bgValue, bgConsumes, bgConsumed}` per value of the key (a string as it is, a number or a boolean as its JSON text): the first `limit` values (default 50, at most 500), ranked by the amount in `dimension` when it is given (which also narrows every figure to it), else by number of consumes. `brOther` sums the values past the limit, `brUnattributed` the consumes that did not carry the key (or carried an object, array or null under it), and `brDistinctValues` counts the values. The window is a period, as for pacing (`periods_back`, 0 the open one by default), or the last `window_days` days (1 to 366), not both; it starts no earlier than the history-retention cutoff (`brSince`), since the figures are read from the event log. `subtree=true` adds the consumes of the buckets under this one. Any key works, nothing is declared first; the read costs about half a second per 100 000 consumes in the window, so ask for a period or a few days rather than a year of a busy bucket. A busy bucket can declare up to 4 keys in its metadata, `"buckette/breakdown-keys": ["session", "model"]`. The scheduler then rolls its consumes per hour and per day by those keys, and the whole hours and days of a window (within the last 366 days and the history retention) are read from that roll-up instead, with the same figures; `brRolledSince` and `brRolledUntil` say which stretch (null when none). It covers the hours rolled after the declaration, with `subtree=true` only when every bucket of the subtree declares the key, and an hour in which the key had more than 1000 distinct values is read from the event log. Nothing changes on the consume path. **The tree as an index.** To group these figures by subtree yourself, `GET /buckets/tree-index` returns every live bucket the key reaches in one answer, without its history: `tiBuckets`, each with `tieId`, `tieParentId`, `tieAncestors` (root first, parent last), `tieDepth` (0 at the top level), `tieTitle`, `tieLabels` and `tieMetadata`. A bucket is in the subtree of `s` when `tieId == s` or `s` is in `tieAncestors`, so no chain has to be rebuilt. `scope_root=` narrows to one subtree (404 when the key cannot see it), and `balances=true` adds `tieResources`. Buckets come shallowest first; at most 5000 (`tiLimit`), and `tiTruncated` says the deepest were left out. A bucket-scoped key's `tieAncestors` stop at its scope root. --- ## Integration modes ### 1. Workflow control (gating mode) Use `Locking` dimensions and `Strict`/`Wait`/`Async` consume calls to make buckette the enforcement point for an agent's resource limits. Typical flow for an agent run with a token budget: 1. `POST /buckets/:parentId/split` to carve a bounded child bucket for this run (e.g. `{"tokens": 20000}`), so the run can't touch the parent's full balance and its usage is independently queryable/archivable. Give it a title (and ideally labels) in `srMetadata`, as in the rule under "Bucket" above. 2. Before each LLM call, `POST /buckets/:childId/consume` with the estimated token cost, `"crMode": {"tag": "Strict"}`. On `ConsumeShortfall`, stop the run (or fall back to a cheaper model, or `Wait`/`Async` if the budget is expected to refill soon). 3. `POST /buckets/:childId/reclaim` with `{"rrMode": "ReclaimAll", "rrCascade": true}` when the run ends, to return unused tokens to the parent. For concurrency limits (e.g. "at most 5 tool calls in flight"), model concurrency as a dimension (`raMaximum: 5`, `raUnit: "slots"`) and use `reserve`/release-on-completion instead of `consume`, since a slot is held for the duration of work rather than spent. For a caller that wants to queue rather than fail on shortfall, use `"crMode": {"tag": "Async", "contents": {"acMaxDelaySecs": 3600, "acAutoConsume": true}}`: the initial call fails fast into a `ConsumePending` state, and either the scheduler auto-consumes once resources free up (`acAutoConsume: true`, echoed as `coAutoConsume`, fires `bucket.consumed`) or the caller polls/is notified via `bucket.resources_available` and re-consumes explicitly. ### 2. Reporting / observability mode Use `Reporting` dimensions when you want buckette to be a ledger, not a gate — e.g. tracking total spend for dashboards or billing without ever blocking a call because of it. 1. Create (or add a dimension to) a bucket with `raMode: "Reporting"` for the metric you want to track, optionally with `raMaximum` set to whatever ceiling should trigger an `overflow` alert. 2. Call `consume` on every use exactly as you would for a `Locking` dimension — the call always succeeds in full, so you don't need shortfall handling for this dimension. 3. Read `GET /buckets/:id/stats` or subscribe to `bucket.overflow` / `bucket.depleted` to monitor the running total out-of-band, or read `GET /buckets/:id/events` for a full audit trail. **Paging the event log.** `GET /buckets/:id/events` returns newest first, `limit` up to 200. To read further back, pass the last event's `erCursor` as `before`: `GET /buckets/:id/events?limit=200&before=` returns the events older than that one, and `event_type` still narrows. Stop when a page comes back shorter than `limit`. Each page costs what the first one does; `offset` still works but makes the server walk every event it skips, so use the cursor past the first few pages. Events one transaction wrote share an `erOccurredAt` and come in a fixed order, so pages neither repeat nor skip one. A malformed cursor is `400` with code `invalid_cursor`. **Reporting reads may lag.** `GET /buckets/flows`, `GET /buckets/recency`, `GET /buckets/consume-shortfalls`, `GET /buckets/shortfall-ranking`, `GET /buckets/claim-value`, the ledger reads (the closed periods of `GET /buckets/:id/periods`, `GET /buckets/periods`, `GET /buckets/period-series`), `GET /buckets/pacing`, `GET /buckets/:id/consume-breakdown`, `GET /buckets/tree-index`, the CSV and Prometheus exports and `GET /tenants/me/usage` are answered from a reporting connection that an instance may point at a read replica. They can then be behind the latest writes by the replication delay: normally under a second, up to a few minutes while the replica finishes a long report. A consume you just made may not be in them yet. Draw dashboards from them; decide from `GET /buckets/:id` or a `consume`'s own answer, which are always current. ### 3. Mixed mode (lock one dimension, report another) The common real-world case: enforce a hard cap on one dimension while tracking a related metric purely for visibility. Example — a bucket with: ```json { "cbrResources": { "usd": {"raCurrent": 50, "raMaximum": 50, "raReserved": 0, "raUnit": "usd", "raMode": "Locking"}, "tokens_reported": {"raCurrent": 0, "raMaximum": null,"raReserved": 0, "raUnit": "tok", "raMode": "Reporting"} } } ``` A single `consume` call deducts both dimensions atomically: ```json {"crAmounts": {"usd": 0.42, "tokens_reported": 1500}, "crMode": {"tag": "Strict"}} ``` `usd` blocks the run once the $50 cap is hit; `tokens_reported` keeps accumulating indefinitely (even past any informal expectation you might set via `raMaximum`) purely so you can see total token usage in stats/events without it ever being the reason a call gets rejected. ### 4. Drop-in packages for agent frameworks If the agent runs on LangChain / LangGraph, CrewAI, LlamaIndex or AG2 (AutoGen), you may not need to write the gating calls above yourself. Four small Python packages hook into the framework's own instrumentation point and do it for you: your agent gets a bucket, not your whole tenant's key. | Package | Framework | Meters | How it hooks in | |---|---|---|---| | `buckette-langchain` | LangChain, LangGraph | LLM tokens, tool calls | a callback handler, plus `graph_run(...)`, which splits a titled child per run and reclaims it at the end | | `buckette-crewai` | CrewAI | LLM tokens | CrewAI's global before/after LLM-call hooks | | `buckette-llamaindex` | LlamaIndex | LLM tokens, retriever calls | an instrumentation event handler | | `buckette-autogen` | AG2 (AutoGen) | LLM tokens | a middleware around every LLM call | They behave the same way: - **Before a call**, they read the bucket and refuse the call when a watched dimension is empty or the bucket is not active. The framework sees a `BudgetExceeded` exception, so the model is never called. LlamaIndex is the exception: it drops what its event handlers raise. There the package records the refusal, and its `check()`, which you call between steps, raises it. - **After a call**, they consume the token count the provider reported, in `Partial` mode. The call that overspends drains the bucket to zero instead of failing halfway. - **A metering outage never stops a run.** A run is stopped only by an answer that says to stop: a depleted or inactive bucket, a refused key, or a tenant on hold (`TenantOnHold`). - **Each run can get its own bucket.** A run gets a titled child bucket (`child_bucket`, or `graph_run` in the LangChain package), and a key confined to the pool can split and reclaim children inside it. - **Receipts can be checked.** Each package reads the signed receipt off a consume and verifies it (see "Trusted-third-party receipts"). None of them reserves ahead of a call. So two callers sharing one bucket can each pass the check and together overspend by up to one call each; give each run or agent its own child bucket for a hard cap. The packages are not on a public package index yet: to use one, write to hello@buckette.co. --- ## Example use cases **Per-agent token budget with sub-agent delegation** Parent bucket holds the org's total token allowance (`Locking`). Each top-level agent run splits off a child bucket; each sub-agent it spawns splits a grandchild from that. Consume against the leaf bucket for every LLM call. Reclaim on completion at every level, so unused budget flows back up the tree. `Strict` mode means a sub-agent that exhausts its allocation fails fast rather than silently overspending its parent's budget. Pair each split with a bucket-scoped API key (`cakreBucketId` set to the new child) handed to that sub-agent, so it can only ever act within its own allocation — never see or touch its parent's or siblings' budgets — and reclaiming the child on completion automatically deactivates that key too. **Per-tenant API rate limiting with reporting** One dimension `requests` (`Locking`, `raMaximum` = plan limit, replenished every `IntervalSecs`) gates the rate limit. A second dimension `requests_total` (`Reporting`, no maximum) accumulates lifetime usage for billing/analytics, unaffected by the periodic replenishment resetting the `requests` dimension. **Cost tracking without enforcement (dashboards only)** A bucket per user with a single `Reporting` dimension `usd_spent` (`raMaximum` set to an expected soft ceiling). Every LLM call consumes against it; nothing blocks. Subscribe to `bucket.overflow` to alert ops when a user's spend exceeds the expected ceiling, without affecting that user's ability to keep working. **Credit-based billing with event-driven top-ups** `credits` dimension, `Locking`, no periodic schedule — only replenished via `POST /buckets/:id/replenish` triggered by a payment webhook (`repSource: "stripe"`, `repTransactionId` for idempotency, `repMetadata` carrying the charge id so the event log reconciles against the provider's). Consume calls use `Strict` so work stops immediately when credits run out, resuming as soon as the next payment webhook replenishes the bucket. **Multi-mailbox email dispatch (claims)** One bucket per mailbox (`emails`, `Locking`, replenished on the provider's rate-limit interval) plus one bucket per campaign (`emails`, `Locking`, the campaign's total send quota). Each send is one `POST /claims`: `FirstOf PickRoundRobin` across the mailbox buckets picks a mailbox with credit while spreading sends evenly instead of hammering whichever mailbox sorts first, or — when the mailbox is already chosen — `AllOf` over [that mailbox, the campaign] makes sure a send debits both limits together or not at all. Sends that can't go out now are queued with `Async` mode and per-campaign `clrPriority`, and the scheduler dispatches them fairly as mailbox credit replenishes. **Proving consumption to an external biller or auditor** An agent draws down a `credits` bucket for work done on behalf of an external customer whose own billing system needs proof — not just a webhook it has to trust — that the credits were actually spent. The customer's system generates a nonce per billable event and passes it through to your agent; your agent sets `crNonce` to that value on the `consume` call and returns the resulting `coReceipt` to the customer, who verifies it against your tenant's public key on their own, with no additional API access to your system. Same pattern for a reservation a third-party worker should finalize itself: set `rrvNonce` on `reserve`, hand the resulting `rsCommitToken` to that worker so it can call `.../commit` directly. Same pattern again when the billable event spans several buckets: set `clrNonce` on a `POST /claims` call and return the resulting `cloReceipt`, which attests every `ClaimGrant` the claim produced (whichever bucket(s) actually paid). **Monthly allowance per customer under one shared cap** A parent bucket holds the monthly cap you pay for (`tokens`, `Locking`; a `usd` `Reporting` dimension beside it), with a `Monthly` schedule, `CarryoverNone` and the tree envelope (`rcEnvelope: {"teScope": "EnvelopeSubtree"}`). Each customer is a split with its allowance (the child carries the parent's `Reporting` `usd` at `0` without naming it), and a `Monthly` schedule of its own a few minutes before the parent's: a child does not inherit the parent's schedule (its `POST /buckets/:id/eta` answers `EtaUnknown NoSchedule`), and its refill is credited to it directly, not taken from the parent. The parent's run then credits the cap minus what the customers hold, so the tree totals the cap while the allowances add up to at most the cap. Each customer gets a key scoped to its bucket with an expiry (`cakreExpiresInMinutes`; the API's default is none). When the allowances add up to more than the cap, the children get no schedule and are topped up from the parent with `POST /transfers` after its monthly run, and a parent that cannot cover a top-up answers `TransferShortfall`. `GET /help/how-to-per-customer-allowance` has the calls in order. **Reserved capacity for in-flight work** A `concurrency` dimension (`raMaximum: N`, `raUnit: "slots"`). Before dispatching a tool call, `reserve` one slot; release it (or consume it, if "slot-uses" should count against a separate budget) when the call completes. This prevents overcommitting concurrent work without needing to know the call's duration in advance. For a worked, step-by-step walkthrough (endpoints in call order, not just the shape) of four of these, see `GET /help/how-to-fleet-management` (splitting a shared multi-dimensional pool into per-agent buckets plus delegated keys), `GET /help/how-to-per-customer-allowance` (a monthly allowance per customer under one shared monthly cap), `GET /help/how-to-cushion-reservation` (holding back a staggered, expiring safety margin near the end of a budget period), and `GET /help/how-to-monitor-then-gate` (checking availability before acting, then letting Wait/Async or the ETA endpoint do the retrying). `GET /help` lists every such recipe as it's added — this document isn't the only place to look. Asked for a dashboard? This API serves the numbers one is drawn from, and `GET /help/dashboards` says which route answers which question. On the hosted service, check first whether you need to build one at all: the Console has dashboards built in and calls them **Monitors** (named pages of widgets over one tenant's buckets). They are managed through the account API the Console itself uses, not through this one; `GET /help/monitors` there has the routes. --- ## Practical notes for agents wiring this in - Always check the response tag on `consume`/`reserve` outcomes (`ConsumeSuccess` / `ConsumeShortfall` / `ConsumePending`) rather than assuming success — even `Partial` mode returns `coConsumed` that may be less than requested. - `crMetadata`/`srMetadata`/`clrMetadata`/`repMetadata` accept arbitrary JSON — attach a request ID, model name, or trace ID here so `GET /buckets/:id/events` doubles as an audit log you can correlate with your own logs. It also rides along on the `bucket.consumed`/`claim.granted` webhook and per-request callback payload for that event, so a subscriber can match an incoming notification back to the request that caused it without a separate lookup. This survives an `Async` consume/claim that doesn't resolve until the scheduler's tick, too — the metadata is persisted with the pending intent/claim and only surfaces once it actually resolves. A reservation's commit takes `crqMetadata`, the same field, written into its `bucket.consumed` event-log record and carried on the `bucket.reservation_committed` webhook. A reservation takes `rrvMetadata` too (what the hold is for): kept on the hold (`rvMetadata`) and written as `metadata` on its `bucket.reserved`, `bucket.reserve_pending`, `bucket.reserve_shortfall` and expiry events, and as `reservation_metadata` on its commit's `bucket.consumed` record. - When a claim is worth something to you, say so in `clrValue` (or `clrrValue` on a claim reservation): `{"revenue": 120.5, "customers": 1}`, kinds and units of your own, 1 to 16 kinds, a number up to 1e15 with at most 12 decimals. Leave it out when you don't know: absent is "unvalued", not zero. buckette records it on the claim (`ciValue`) and as `value` on every event the claim writes, refusals (`bucket.claim_shortfall`) included, and never acts on it: the queue still orders by `clrPriority`, then arrival. Don't encode value in `clrPriority`; it holds no unit, no vector and no absence. - To read that value back, `GET /buckets/claim-value?window_days=N` (`ScopeRead`, a reporting read; `bucket_id` narrows to a subtree, `limit` is the per-kind cut of the ranking, default 20, at most 200). Over the window (the ledger reads' window: default 7 days, at most 365, capped by history retention) it decides each claim's outcome from the lines it wrote: `granted` (consumed, held or notified, nothing short), `partial` (both), `refused` (`bucket.claim_shortfall` only) or `expired`. It answers claims per outcome with the unvalued ones apart (`cvOutcomes`), each kind's value per outcome (`cvKinds`), the amounts consumed and short behind each kind per dimension (`cvAmounts`; `cvaKind: null` is the unvalued claims, and a claim naming two kinds counts under both), and the most valuable refused or expired claims per kind (`cvTopRefused`, with their buckets and shortfall). Pending and cancelled claims are not counted. - Prefer one bucket dimension per thing you might independently need to cap, alert on, or report — don't overload a single dimension's unit to mean two different things. - If you're unsure whether a metric should gate or just report, default to `Reporting` first and promote to `Locking` once you're confident about the right cap — moving a dimension from `Reporting` to `Locking` (or back) is a one-field change, not a migration. - Only set `crNonce`/`rrvNonce` when an actual external relying party gave you a nonce to embed — don't invent one yourself. The nonce is what lets that party tie the proof back to *their* specific transaction; a self-generated nonce defeats the point and just adds signing overhead. - **Every error is one JSON shape, sent as `application/json`**: `{"errCode": ..., "errMessage": ..., "errDetails": ...}`. Switch on `errCode`, relay `errMessage`, and read `errDetails` for the specifics (`errDetails` is `null` when there are none). The one exception is a path that does not exist, which is an empty `404` for an API client. Refusals whose real question is "what now?" put where to look in `errDetails`: `see`, a list of paths on this instance, and `accountGuide`, a URL that explains where accounts and keys are managed, when the instance is configured with one (absent otherwise): - `401 missing_credential` (no `Authorization: Bearer` header, or an empty one) and `401 invalid_api_key` (unknown, deactivated or expired key) carry `WWW-Authenticate: Bearer` and `errDetails: {"see": ["/help/authentication", "/docs/llm.md"], "accountGuide": "https://..."}`. A key is never obtained from this API on its own: it comes from whoever provisioned the tenant, which is what those pages and the account guide explain. - `429 rate_limited`: the key's or the tenant's rate limit; wait and retry. - `503 duty_unattended` on an async consume, reserve or claim (`Async` mode): the instance found, in the database, that no instance of this service runs the background duty that would complete the request (`errDetails.duty`, `queues`), so the request is refused rather than queued where nothing drains it. An operator's matter: the message says what to start. `Wait` and immediate modes need no sweep and are not refused. - `401 invalid_commit_token`: a commit token that does not verify, for whatever reason; it says no more on purpose. - `404 not_found` from `GET /help/` or `GET /docs/`: the name does not exist; `errDetails` has `see: ["/help"]` and the names that do exist (`topics`, or `docs`). - **Two request-level limits will refuse your call rather than degrade it**, so handle them explicitly rather than retrying blindly: - A request body over **2MB** gets `413 request_body_too_large` (the default; an instance can be set to a different limit). This is separate from — and much larger than — the per-field metadata caps, so hitting it usually means a resource map or metadata blob that has grown unintentionally rather than a legitimately large call. Note the rejection is decided from `Content-Length` *before* the body is read, so for a body far over the limit the connection is closed while you're still uploading and you'll see a connection reset rather than the 413 — treat a reset on a large POST as this limit, not as a transport fault worth retrying. When the 413 does reach you it carries `Connection: close`. - **A refusal does not cost you the connection.** A call refused before its body is looked at (`401`, `403`, `429`, an unknown path, a wrong method or content type) is answered once the body has arrived, and the connection serves your next request, so keep it rather than reconnecting after an error. The one exception is a refused call whose unread body is over **64KB**: the body is not read, the response carries `Connection: close`, and the next request needs a new connection. - `GET /buckets/:id/descendants` and `GET /buckets/:id/tree` take no `limit`/`offset` and refuse with `400 invalid_operation` past **5000 descendants**, rather than returning a truncated subtree — a silently-missing branch would be indistinguishable from a deleted one. Walk `GET /buckets?parent_id=` level by level for anything larger. `GET /buckets/:id/ancestors` has no such cap. - **Three refusals are about the tenant, not your call**, and retrying does not help; relay the message to whoever manages the account instead: - `403 tenant_on_hold` on every request: the tenant is on hold. The message starts with `Tenant is on hold:` and says why and who can lift it; `errDetails.reason` is `overdue_invoice` (an owner of the account pays the overdue invoice in the Console), `no_slot` (the tenant is not covered by a paid slot), `email_unreachable` (an owner confirms a working email address), `account_suspended` (the operator suspended the account), `moving` (the tenant is being moved to another instance; retry in a few minutes, at the same address), `idle` (the tenant was not used for a long time and is to be deleted; the refused request counts as a use, so the hold lifts within a few minutes: retry then), or `null` when the hold was set without a reason. - `410 tenant_moved` on every request: the tenant now lives on another instance and the one you reached no longer serves it. Retry at the address you were given for the tenant; if that still leads here, ask whoever manages the tenant for its current address. - `403 quota_exceeded` on `POST /buckets` or a split, with `errDetails: {"limit": "buckets", "max": N, "reason": ...}`: the tenant is at its bucket limit. `reason` says what set it: `plan`, `spend_cap` (an owner of the account can raise the spend cap), `overdue_invoice` (the limit is held at what the tenant has until an overdue invoice is paid; existing buckets keep working), or `null`. The code is the same `quota_exceeded` as the other plan limits, so match on `errDetails.limit`/`reason`, not on the message. - A `Wait`-mode consume can legitimately hold the connection for up to its `wcMaxDelaySecs` (capped at 300s), so set your own client timeout above whatever you ask for. The server abandons a request only well past that ceiling, and answers `503 request_timeout` if it ever does. - Calling buckette directly from a browser (rather than through a backend you control) needs an allowed CORS origin, or the browser blocks the response. Put your page's origin on `PUT /cors-allowed-origins` (per-tenant, `ScopeAdmin`, no operator involvement needed on a shared instance) — see `GET /help/cors-allowed-origins`. --- ## Appendix: a note on names The product was called budgetz before 2026-10, and some names you will meet on the wire still say so, on purpose, because they are stored in integrations and in bucket metadata: the `budgetz/` metadata key prefix is the one you will meet most. Metric families are `buckette_*` since 2026-10-05 (a hard rename: the `budgetz_*` names are gone, so update a scrape's dashboards and alert rules). The DNS verification record is `_buckette-challenge.` with the value `buckette-verification=`; a record already published under the old name still verifies. Headers were renamed to `X-Buckette-*`. **The old `X-Budgetz-*` header names were retired on 2026-11-10.** A request that carries `X-Budgetz-Commit-Token` without `X-Buckette-Commit-Token` is answered `400` with the error code `retired_header`, whose `details` name the old header (`header`) and the one to send instead (`use`). Webhook deliveries, verification challenges and the CSV export carry only the `X-Buckette-*` names: send `X-Buckette-Commit-Token`; verify `X-Buckette-Signature` in a webhook receiver (a normal delivery has no event header: read the `event` field of the body, and see `GET /help/events` for every event and its payload); read `X-Buckette-Export-Truncated` on the CSV export. The values and the signature format are unchanged, only the names moved.