# Spending and rate limits

This guide covers two limits on a harness's model calls. The first is **what a run may
spend**: a number of tokens, a number of calls or an amount of money, counted from the run's
journal and enforced by the Governor. The second is **how fast calls are made**: how many may
be in flight at once and how many may start in a period, shared by every run that calls the
same vendor account. At the end you have a run that stops, resumable, once it has reached an
allowance you set, and one throttle that every model of an account shares.

- **You will be able to:** price model calls with your own prices, run an agent or a whole
  workflow under an allowance, resume it under a larger one in another process, read what a
  recorded run spent, put a shared throttle in front of every model of an account, back off
  together when a vendor asks to wait, and write and check a throttle of your own.
- **Read first:** [The Governor](../concepts/governor.md), [Humans and
  interruption](../concepts/human-in-the-loop.md#step-4-stopping-a-run-in-the-middle) (what
  `interrupted` and `resumed` do to the reference agent), [Workflows](../concepts/workflows.md)
  and [Using a vendor model](vendors.md) (models, usage, `ModelFailure` and `Retry`).
- **Time:** about 30 minutes.

## Where this fits

In the [big picture](../quickstart.md#the-big-picture), an actor asks for a model call, the
**Governor** hands the request to the **model fulfiller**, the fulfiller calls a **Model**,
and the answer comes back as a `model_replied` (or `model_failed`) event that the Governor
writes to the **journal** before the actor handles it. The two limits sit at two places on
that path:

```mermaid
flowchart LR
    actor["Actor"]
    governor["Governor<br/>allowance=Allowance(...)"]
    fulfiller["ModelFulfiller"]
    throttled["ThrottledModel"]
    throttle["Throttle<br/>one per vendor account"]
    model["Model<br/>(an adapter)"]
    journal[("Journal<br/>usage and model<br/>of every call")]
    actor -- "invoke_model" --> governor
    governor --> fulfiller --> throttled
    throttled -- "acquire / release" --> throttle
    throttled --> model
    governor -- "model_replied" --> journal
    journal -- "Spend: what was spent" --> governor
    governor -- "interrupted, once the<br/>allowance is reached" --> actor
```

- The **allowance** is the Governor's. It reads what was spent from the journal (the run's
  **tally**) and, when a run has **reached its allowance**, meaning its tally is at or above
  one of the allowance's thresholds, hands the actor `interrupted` instead of starting more
  work. The run is not killed and nothing is raised.
- The **throttle** is in front of the model. A `ThrottledModel` is itself a Model, so no
  fulfiller or actor knows it is there; it only decides *when* each call may start.

The two are independent: use either, or both.

## Part 1: what a run may spend

### How it fits together

The journal records the usage a model reports to the Governor. `model_replied` carries the
model's [token counts](vendors.md#what-a-call-cost-usage), and `model_failed` includes them
when the failure provides them. Both name the model when known. A `ModelFulfiller` records
each attempt it gave up on in the answer's `"retries"` list, with its own usage and model
when known. The recorded tally survives a crash, a move to another process, or a
[fork](forking-a-run.md). SDK retries and attempts inside a
[`FallbackModel`](vendors.md#retries-and-fallback-models) can produce additional provider
charges because the fulfiller sees the result of the wrapper call as one attempt.

Three classes in `gvn.runtime.spending` each own one thing:

- `Rates`: what tokens cost, per model. The prices are yours to supply; gvn ships none.
- `Spend`: the tally of one run. It is shown a run's events and counts the model calls they
  record: calls, tokens and, with rates, cost.
- `Allowance`: the token, call, or cost thresholds at which a `Spend` prompts an interruption.

`Governor(allowance=...)` applies an allowance to every run it drives. Reaching it is
delivered to the actor as `interrupted`, the input every state of the reference agent
already routes: the agent suspends with everything it has and resumes on `resumed`. Under a
Governor with a larger allowance, in this process or any other, the run then carries on.

### Step 1: prices

`Rates` maps a model's name to its prices. The numbers here are made up for this example:
1.0 per thousand input tokens and 5.0 per thousand output tokens, in no currency in
particular (gvn only multiplies):

```python
from gvn.runtime.spending import Rates, Unpriced

PRICES = Rates({"example-small": {"input": 1.0, "output": 5.0}}, per=1000)

one_call = {"input_tokens": 600, "output_tokens": 40}
print(PRICES.cost(one_call, "example-small"))  # 0.8
print(PRICES.cost(one_call, "example-small-2026-10-01"))  # 0.8
try:
    PRICES.cost(one_call, "example-large")
except Unpriced as error:
    print(error)  # no price for model 'example-large'; priced: ['example-small']
```

- Each model's prices are a mapping with `"input"` and `"output"`, and optionally
  `"cache_read"` and `"cache_write"`, which default to the `"input"` price. Each is the price
  of `per` tokens; `per` defaults to 1,000,000.
- A call is priced as uncached input (`input_tokens - cache_read_tokens -
  cache_write_tokens`) at the input price, plus cache reads, cache writes and output at
  theirs.
- Which price applies to a call: the key equal to the model's name; else the longest key the
  name starts with, so a dated id a vendor reports (`example-small-2026-10-01`) is priced as
  the model asked for (`example-small`); else the `None` key, if you gave one, which prices
  every call nothing else matches; else `Unpriced`.

### Step 2: a run under an allowance

The agent below looks something up, and its scripted model reports 600 input and 40 output
tokens for each call that asks for the search and 700 and 60 for the answer, all from
`example-small`. The policy `Allow` clears every call. `governor_over` builds a Governor
over a journal, with a script and an allowance:

```python
import asyncio
from collections.abc import Callable

from gvn.harness.agent import VERDICTS, Agent
from gvn.harness.events import Event
from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Exchange, Journal, Output, Reply
from gvn.harness.tools import Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor, Result
from gvn.runtime.spending import Allowance
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel, StubTool


class Allow(Decision):
    def outcomes(self) -> Alphabet:
        return VERDICTS

    def judge(self, consultation: object) -> Symbol:
        return VERDICTS.named("cleared")


def looks_up(number: int) -> Reply:
    lookup = ToolCall(call_id=f"c{number}", name="search", arguments={"query": "Moore"})
    message = Message.assistant(text="", calls=[lookup])
    return Reply(message=message, input_tokens=600, output_tokens=40, model="example-small")


def answers(text: str) -> Reply:
    message = Message.assistant(text=text)
    return Reply(message=message, input_tokens=700, output_tokens=60, model="example-small")


search = StubTool(name="search", arguments=Record({"query": Text()}), result={"hits": 3})
toolbox = Toolbox(tools=[search])


def governor_over(journal: Journal, script: list[Reply], allowance: Allowance, output: Output) -> Governor:
    return Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=ScriptedModel(script=script), toolbox=toolbox),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=Allow()),
        },
        journal=journal,
        output=output,
        clock=ManualClock(),
        allowance=allowance,
    )


journal = MemoryJournal()
seen = RecordingOutput()
tight = governor_over(
    journal=journal,
    script=[looks_up(1), looks_up(2), answers("never")],
    allowance=Allowance(cost=1.5, rates=PRICES),
    output=seen,
)
helper = Agent(name="helper", instructions="Be brief.", tools=[search], turns=9)
result = asyncio.run(tight.deliver(actor=helper, event=Event("started", payload={"prompt": "Look up Moore."})))
print(result)  # Result('waiting', overspent='cost: 1.6 spent of 1.5 allowed')
print(helper.state())  # State('suspended')
print([record["event"]["name"] for record in asyncio.run(journal.read("helper"))])
# ['started', 'model_replied', 'cleared', 'tools_returned', 'model_replied', 'interrupted']
```

The first call cost 0.8 and left the run under its allowance, so the search ran and the
model was asked again. The second call brought the run to 1.6, at or above the 1.5 allowed.
Its reply asked for a second search, but before the Governor started that work (here, the
policy check), it handed the agent `interrupted` instead. The agent went to `suspended`, the
call returned `waiting`, and `result.overspent()` names the limit that was reached and both
figures.

An `Allowance` takes one or more interruption thresholds:

- `tokens`: recorded input and output tokens, including cached tokens;
- `calls`: recorded model calls, including retried attempts;
- `cost`: recorded usage priced in the currency of `rates`, which is required for this threshold.

The Governor checks for a tally at or above the threshold before it starts more work.
`rates` can also be given without `cost` to report prices. See
[Runtime guarantees](../reference/runtime-guarantees.md#spending) for billing and custom actors.

The `waiting` and `finished` signals of a run under an allowance carry `"spent"`, the
tally's figures (with `"cost"` when the allowance has rates), and `"overspent"` when the run
has reached its allowance (its tally is at or above one of the allowance's thresholds), so
an [output](observability.md) can show both live:

```python
last = seen.signals()[-1]
print(last.kind(), last.data()["spent"])
# waiting {'input_tokens': 1200, 'output_tokens': 80, 'cache_read_tokens': 0, 'cache_write_tokens': 0, 'calls': 2, 'cost': 1.6}
print(last.data()["overspent"])  # cost: 1.6 spent of 1.5 allowed
```

### Step 3: resume under a larger allowance

The run is suspended, with its conversation and everything it has done kept in the journal.
To let it finish, resume it under a Governor with a larger allowance. Here that happens as it
would in another process: the agent is rebuilt from the journal with `Recovery`, and a new
Governor delivers `resumed`:

```python
from gvn.runtime.recovery import Recovery

larger = governor_over(
    journal=journal,
    script=[answers("Moore machines: three hits.")],
    allowance=Allowance(cost=5.0, rates=PRICES),
    output=RecordingOutput(),
)


async def resume_elsewhere() -> Result:
    actor = await Recovery(journal).recover("helper", Agent)
    return await larger.deliver(actor=actor, event=Event("resumed"))


done = asyncio.run(resume_elsewhere())
print(done.status(), done.overspent(), done.outcome().payload()["text"])
# finished None Moore machines: three hits.
```

Nothing about the spend is stored anywhere but the journal. Each call that drives a run
(`deliver`, `answer`, `resume`, `wake`) builds the run's tally from its journal when it
begins and adds each event it takes. So the tally is the same in any process and after a
crash, and resuming under the *same* allowance interrupts the run again before the model is
asked.

### When the allowance is checked

- **Before work starts.** Each time the Governor's loop goes round, before it starts
  anything, it asks whether the run has reached its allowance and wants work the Governor
  would itself start or keep running. If so, it cancels and awaits the work in flight and
  hands the actor `interrupted`, journaled and signalled like an interruption from a caller.
- **Once per driving call.** What the actor does with `interrupted` is its own declared
  behaviour: the reference agent suspends; another actor may ask for more work, compensation
  say, and that work then runs. The Governor does not interrupt it again in the same call.
- **The journal is the source of the tally.** A reply can take the tally past the threshold.
  A provider can bill work that never made it into the journal, such as a call that was
  cancelled or lost to a crash. A custom actor can also start new work after it handles
  `interrupted`, because the Governor delivers the allowance interruption once per drive.
- **Waiting spends nothing.** A run that only waits for a person or for a time is not
  interrupted until it wants work.
- **Every call is priced.** Under an allowance with rates, a model call that no price
  applies to raises `Unpriced` from the driving call: after its event was journaled, or, for
  a record already in the journal, as the call begins. Give a
  `None` key in `Rates` to price every model you did not name.

### A whole workflow under one allowance

The allowance belongs to the run, and a [workflow](../concepts/workflows.md)'s children are
part of its run. So one allowance covers the workflow and every actor inside it, at any
depth, whatever its class: the tally counts every model call the journal records.

Reaching the allowance is delivered as `interrupted`, so a run under an allowance must take
that input. Under an allowance the Governor asks `actor.interruptible()` before it drives
anything, and refuses an actor that does not take it. An agent does. A workflow can handle
`interrupted` in its own machine or relay it to its active children. This example uses
`Plan(..., relay=["interrupted", "resumed"])` so one `resumed` can continue the suspended
children. `Brief` below is a two-stage workflow: a
researcher agent, then a writer agent that writes up the researcher's note. Its model is a
`FunctionModel`, a fake whose reply is a function of the question; `note` wraps the prompt
in `note<...>` and reports 500 input and 50 output tokens:

```python
from gvn.harness.workflow import Host, Memo, Plan, Report, Workflow
from gvn.kernel.blueprint import MooreBlueprint
from gvn.testing.fakes import FunctionModel

BRIEF_MACHINE = (
    MooreBlueprint(name="brief")
    .inputs("started", "researched", "research_failed", "written", "write_failed")
    .outputs("idle", "research", "write", "done", "failed")
    .state(name="idle", output="idle")
    .state(name="researching", output="research")
    .state(name="writing", output="write")
    .state(name="done", output="done", final=True)
    .state(name="failed", output="failed", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="researching")
    .branch(
        source="researching",
        outcomes=Alphabet.of("researched", "research_failed"),
        routes={"researched": "writing", "research_failed": "failed"},
    )
    .branch(
        source="writing",
        outcomes=Alphabet.of("written", "write_failed"),
        routes={"written": "done", "write_failed": "failed"},
    )
    .otherwise_stay()
    .build()
)


def stage(role: str, prompt: Callable[[Memo], str], reached: str, missed: str) -> Host:
    return Host(
        actor_class=Agent,
        make=lambda name, memo: Agent(name=name, instructions=f"You {role}.", turns=3),
        start=lambda memo: Event("started", payload={"prompt": prompt(memo)}),
        routes={"completed": reached, "failed": missed, "overflowed": missed},
    )


STAGES = {
    "researching": stage("research", lambda memo: memo.input()["topic"], "researched", "research_failed"),
    "writing": stage(
        "write", lambda memo: memo.results("researching")[0].payload()["text"], "written", "write_failed"
    ),
}


class Brief(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return Plan(definition=BRIEF_MACHINE, stages=STAGES, relay=["interrupted", "resumed"])


def note(exchange: Exchange) -> Reply:
    message = Message.assistant(text=f"note<{exchange.messages()[0].text()}>")
    return Reply(message=message, input_tokens=500, output_tokens=50, model="example-small")


def workflow_governor(journal: Journal, allowance: Allowance) -> Governor:
    return Governor(
        fulfillers={"invoke_model": ModelFulfiller(model=FunctionModel(respond=note), toolbox=Toolbox())},
        journal=journal,
        output=RecordingOutput(),
        clock=ManualClock(),
        allowance=allowance,
    )


briefs = MemoryJournal()
started = Event("started", payload={"topic": "Moore machines"})
held = asyncio.run(workflow_governor(briefs, Allowance(calls=1)).deliver(actor=Brief(name="brief"), event=started))
print(held)  # Result('waiting', overspent='calls: 1 made of 1 allowed')
print([(record["event"]["name"], record["event"]["to"]) for record in asyncio.run(briefs.read("brief"))])
# [('started', None), ('model_replied', 'brief/researching.1'), ('interrupted', None)]
```

The researcher's call used up the one call allowed. When the writer wanted the model, the
workflow was handed `interrupted`, and it relayed it to the writer, which suspended. One
`resumed`, under a larger allowance, carries the whole tree on:

```python
async def resume_brief() -> Result:
    workflow = await Recovery(briefs).recover("brief", Brief)
    return await workflow_governor(briefs, Allowance(calls=10)).deliver(actor=workflow, event=Event("resumed"))


finished = asyncio.run(resume_brief())
print(Report(outcome=finished.outcome()).results("writing")[0].payload()["text"])
# note<note<Moore machines>>
```

A workflow that neither declares nor relays `interrupted` is refused with `Unfulfillable`
before the Governor journals or signals anything:

```python
from gvn.runtime.governor import Unfulfillable


class Unrelayed(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return Plan(definition=BRIEF_MACHINE, stages=STAGES)


print(Brief(name="brief").interruptible(), Unrelayed(name="brief").interruptible())  # True False
try:
    asyncio.run(workflow_governor(MemoryJournal(), Allowance(calls=1)).deliver(actor=Unrelayed(name="brief"), event=started))
except Unfulfillable as error:
    print(error)
# actor 'brief' cannot be driven under an allowance: a run under an allowance must take 'interrupted' (reaching the allowance is delivered as 'interrupted'), and this actor does not; a Workflow takes it when its Plan lists it in relay
```

An actor class of your own says whether it takes `interrupted` with `interruptible()`; the
default answers from its machine's inputs.

### Reading what a recorded run spent

`Spend` is the one object that counts spend. `Replay(journal).recorded(run_id, actor_class)`
reads a recorded run back as a `Trace`, one frame per event, and `Trace.usage()` totals its
tokens and calls ([Replay and evaluation](replay-and-evaluation.md#step-3-what-the-runs-cost)
covers both); `Trace.usage()` is computed with a `Spend`, so the two always agree. Show a
`Spend` every event of a recorded run, with your rates, to price the run after the fact:

```python
from gvn.runtime.replay import Replay
from gvn.runtime.spending import Spend

trace = asyncio.run(Replay(journal).recorded("helper", Agent))
spend = Spend(PRICES)
for frame in trace:
    spend.count(frame.event())
print(spend)  # Spend(calls=3, tokens=2040, cost=2.6)
print(spend.usage() == trace.usage(), spend.by_model() == trace.usage_by_model())  # True True
```

`calls()`, `tokens()` and `cost()` give the three figures an allowance limits; `usage()` and
`by_model()` the totals in the shape of `Trace.usage()` and `Trace.usage_by_model()`.
`Spend()` without rates counts tokens and calls, and its `cost()` is None. With rates,
`count` raises `Unpriced` for a call no price applies to, and counts nothing of that event.

## Part 2: how fast calls are made

### How it fits together

A vendor account can limit concurrent calls and starts per period. Within one process,
give its model adapters the same throttle. To enforce a limit across processes, implement
the `Throttle` port over shared storage, as shown in [Step 3](#step-3-a-throttle-of-your-own).

A **throttle** is the `Throttle` port (`gvn.harness.ports.Throttle`). It decides only *when*
a call may start; it never refuses one. It has three methods:

- `async acquire()`: returns once one more call may start under the limit. A caller that
  returns from it must call `release` exactly once when its call has ended, however it
  ended. A wait that is cancelled holds nothing.
- `release()`: the call admitted by one earlier `acquire` has ended. It is synchronous, does
  no I/O and never blocks.
- `hold_off(seconds)`: the service asked its callers to wait that long (a `retry-after`):
  admit nothing new before that much time has passed. A later, shorter request never
  shortens a longer one in force.

`gvn.runtime.throttles` holds the in-process throttles and the one way they are applied:

- `ConcurrencyThrottle(limit)`: at most `limit` calls at once, admitted in the order they
  asked. `hold_off` does nothing: a count of calls at once has no notion of time.
- `RateThrottle(calls, per, clock)`: at most `calls` calls started in any window of `per`
  seconds, exactly over every window, sleeping on the `Clock` it is given.
- `Throttles([...])`: several throttles as one; a call starts when every one admits it.
  Put the concurrency limit first, so a call waits for its slot before it takes a place in
  the rate window.
- `ThrottledModel(model, throttle)`: a Model whose every call acquires the throttle first
  and releases it when the call has ended.

Waiting for a throttle adds no journal event. A [deadline](../concepts/time.md) can still
fire while a call waits and change how the run proceeds.

### Step 1: one throttle for an account

Here an account allows two calls at once and three started per minute. Two models, a large
one and a small one, share it. The clock is a `ManualClock`, so time moves only when the
example moves it:

```python
from gvn.harness.ports import ModelFailure, Quiet
from gvn.runtime.throttles import ConcurrencyThrottle, RateThrottle, ThrottledModel, Throttles

clock = ManualClock()
account = Throttles([ConcurrencyThrottle(2), RateThrottle(3, 60.0, clock)])
large = ThrottledModel(
    ScriptedModel(script=[Reply(Message.assistant(f"large {n}")) for n in range(2)], name="example-large"),
    account,
)
small = ThrottledModel(
    ScriptedModel(script=[Reply(Message.assistant(f"small {n}")) for n in range(2)], name="example-small"),
    account,
)
question = Exchange(instructions="Be brief.", messages=[Message.user("Hello.")])


async def four_calls() -> list[str]:
    calls = [asyncio.ensure_future(model.generate(question, Quiet())) for model in (large, small, large, small)]
    await clock.sleeping(1)  # until the fourth call sleeps on the clock
    print([call.done() for call in calls], clock.earliest())  # [True, True, True, False] 60.0
    clock.advance(60.0)
    replies = await asyncio.gather(*calls)
    return [reply.message().text() for reply in replies]


print(asyncio.run(four_calls()))  # ['large 0', 'small 0', 'large 1', 'small 1']
print(large.name(), large.throttle() is small.throttle())  # example-large True
```

The first three calls started at once (these fakes answer at once, so no more than two were
ever in flight). The fourth waited until the first left the one-minute window, at 60
seconds: it was the small model's call, and the large model had made two of the three, but
the limit is the account's, not each model's.

A throttled model is a Model, and its `name()`, `provider()` and `context_window()` are the
model's. So it goes wherever a Model goes: into a `ModelFulfiller`, as a
[model per role](vendors.md#a-model-per-role), as a member of a `FallbackModel`, or into a
domain harness, and no fulfiller or actor knows it is there. With vendor adapters, every
model object of one account gets the same throttle:

```python
# not runnable: needs a vendor SDK client and model ids from your configuration.
account = Throttles([ConcurrencyThrottle(50), RateThrottle(2000, 60.0, clock)])
main = ThrottledModel(AnthropicModel(client=client, model=MAIN_MODEL_ID), account)
summariser = ThrottledModel(AnthropicModel(client=client, model=SMALL_MODEL_ID), account)
fulfiller = ModelFulfiller(model=main, toolbox=toolbox, roles={"summariser": summariser})
```

The limits are the numbers your account allows; the ones above are placeholders. Give one
`Governor`, or every Governor in the process, models built over the same throttle, and the
limit holds across every actor and run they drive.

Each attempt is throttled by itself: a `Retry` on the `ModelFulfiller` calls the model again
for each attempt, and a `FallbackModel` over throttled models throttles each member under
its own throttle.

### Step 2: when a vendor asks to wait

When a vendor answers with a `ModelFailure` that carries `retry_after()`, `ThrottledModel`
tells its throttle (`hold_off`) before it passes the failure on. So every caller that shares
the throttle waits, not only the one that was told: many runs back off together instead of
each finding the limit for itself.

```python
told = ManualClock()
shared = RateThrottle(100, 60.0, told)
busy = ThrottledModel(ScriptedModel(script=[ModelFailure("slow down", retryable=True, retry_after=30.0)]), shared)
other = ThrottledModel(ScriptedModel(script=[Reply(Message.assistant("ok"))]), shared)


async def backing_off() -> str:
    try:
        await busy.generate(question, Quiet())
    except ModelFailure as failure:
        print(failure.reason(), failure.retry_after())  # slow down 30.0
    waiting = asyncio.ensure_future(other.generate(question, Quiet()))
    await told.sleeping(1)
    print(waiting.done(), told.earliest())  # False 30.0
    told.advance(30.0)
    return (await waiting).message().text()


print(asyncio.run(backing_off()))  # ok
```

The failure itself passes through unchanged, so the fulfiller's `Retry`, if it has one,
still decides whether to try again ([retries and fallback
models](vendors.md#retries-and-fallback-models)); its next attempt waits on the throttle
like every other call.

### Step 3: a throttle of your own

The in-process throttles hold a limit across everything in one process. To hold one across
several processes, keep the limit in a store they all reach, and implement the port over
it. Here an in-memory stand-in plays that store, so the example runs; in a deployment its
two methods are queries to the shared store. Each slot is a token: `acquire` takes one,
waiting until one is free, and `release` gives it back.

`release` is synchronous and does no I/O, so it hands the give-back to a task on the running
loop:

```python
from gvn.harness.ports import Throttle


class SlotStore:
    """Stands in for a store every process reaches: a set of free slots."""

    def __init__(self, slots: int) -> None:
        self._free = asyncio.Queue()
        for slot in range(slots):
            self._free.put_nowait(slot)

    async def take(self) -> int:
        return await self._free.get()

    async def give_back(self, slot: int) -> None:
        self._free.put_nowait(slot)


class SharedSlots(Throttle):
    def __init__(self, store: SlotStore) -> None:
        self._store = store
        self._held = []
        self._returning = set()

    async def acquire(self) -> None:
        self._held.append(await self._store.take())

    def release(self) -> None:
        slot = self._held.pop()
        returning = asyncio.get_running_loop().create_task(self._store.give_back(slot))
        self._returning.add(returning)
        returning.add_done_callback(self._returning.discard)
```

A cancelled `acquire` must hold nothing: here a cancelled `take` takes no slot. `hold_off`
keeps the port's default, which checks its argument and does nothing more, as fits a limit
on calls at once; a rate limit shared by several processes keeps its "admit nothing before"
time in the store as well, so that one vendor's `retry-after` holds every process back.

`ThrottleContract` (in `gvn.testing.contracts`) is the test suite every throttle passes.
Subclass it in a pytest module with a `make_throttle()` that returns a fresh throttle
admitting at least two calls at once, or call its tests directly:

```python
from gvn.testing.contracts import ThrottleContract


class SharedSlotsContract(ThrottleContract):
    def make_throttle(self) -> Throttle:
        return SharedSlots(SlotStore(slots=2))


suite = SharedSlotsContract()
names = [name for name in dir(suite) if name.startswith("test_")]
for name in names:
    getattr(suite, name)()
print(f"{len(names)} throttle contract tests passed")  # 8 throttle contract tests passed
```

Then use it as any throttle: `ThrottledModel(model, SharedSlots(store))`.

## Recap

- `Spend` tallies recorded model usage, and `Rates` estimates the cost from your prices.
  `Allowance` sets the token, call, and cost thresholds for interruption.
- `Governor(allowance=...)` hands a run that has reached its allowance `interrupted` before
  more work starts. The reference agent suspends with everything it has; `resumed` under a
  larger allowance carries it on, in any process. `Result.overspent()` and the `"spent"` and
  `"overspent"` of the `waiting` and `finished` signals say what was spent.
- One allowance covers the workflow and its children. The workflow must declare or relay
  `interrupted`. Relay `resumed` as well to carry on with suspended children.
- A `Throttle` decides when a call may start. `ConcurrencyThrottle`, `RateThrottle` and
  `Throttles` hold a limit across everything that shares them, and `ThrottledModel` applies
  one to a Model by composition. Give every model object of one account the same throttle.
- A vendor's `retry_after` is told to the throttle, so everyone sharing it backs off.
- A throttle of your own, over a store several processes share, implements the port and
  passes `ThrottleContract`.

## Next

Choose by what you need now:

- **Spending watched live.** [Logs, traces and streams](observability.md) sends a run's
  calls, and what they spend, to your logs and traces as they happen.
- **Limits across several processes.** [Running as a service](running-as-a-service.md)
  shares runs between processes, where a run interrupted in one is resumed in another.
- **What recorded runs cost.**
  [Replay and evaluation](replay-and-evaluation.md#what-the-runs-cost) totals the usage of
  finished runs.
