# Flow control

> Scopes, limit keys, concurrency and rate rules, how 429 differs from 202, and the diagnostics endpoints.

Source: https://cairnflow.dev/docs/reference/flow-control

Concurrency limits are the one valve that closes before money leaves the account. When every
running invocation calls a paid model or API, a traffic spike does not make the system slower; it
makes the bill bigger. Flow control lets you cap how much runs at once, per customer or per plan.

## Two entry points

| Path | Behaviour |
|---|---|
| `POST /invoke/...` | Subject to no limit other than the node's turn capacity (`--max-concurrent-turns`). |
| `POST /scope/{scope}/invoke/...` | Everything this invocation touches lives **in the scope**, and the scope's rules apply. |

A scope is not a label for counting: it is **part of identity**.

| Thing | Without scope | In scope `bob` |
|---|---|---|
| Virtual object `Cart/a` | one instance | a **different** instance, with its own state and queue |
| `Idempotency-Key: k` | deduplicated globally | deduplicated **within `bob`** |
| Promise `(service, key, name)` | one promise | a separate promise |

So `/invoke/Cart/add?key=u1` and `/scope/bob/invoke/Cart/add?key=u1` address two different objects.
They do not see each other's state and do not lock each other.

Scope names use `[a-zA-Z0-9_.-]`, are not empty and are at most 36 bytes; anything else is `400`.
Calls made from inside a scoped invocation stay in its scope, which also decides which range runs
them.

## Limit keys

`?limit-key=l1` or `?limit-key=l1/l2` (or the `x-cairn-limit-key` header) splits a scope's budget
further, for example per user inside a customer's scope.

- **A limit key requires a scope.** On the unscoped path it is `400`: with no scope there is no
  counter to attach it to, and silently ignoring it would let you believe a limit is in place.
- **A limit key is not part of identity.** Two calls with the same target, scope and object key but
  different limit keys reach the **same** virtual object. The limit key only affects queueing.

```sh
curl -X POST "$CAIRNFLOW_SERVER/scope/acme/invoke/Agent/run?limit-key=user-42" \
  -H "Authorization: Bearer $CAIRNFLOW_TOKEN" -d '{"prompt":"..."}'
```

## The rule book

Rules are cluster-wide and managed with a `cluster-admin` key (a `provision` key can manage the
per-tenant rate rows only). Counters are per tenant: a rule
`acme` with concurrency 10 gives **each** tenant's scope `acme` its own 10 slots.

| Method and path | Purpose |
|---|---|
| `GET /rules` | The whole rule book with its `version`: pattern rules and per-tenant rate rows. |
| `POST /rules` | Add or update a pattern rule. Idempotent and merging. |
| `POST /rules` with `{"tenant": ...}` | Rate limit for a whole tenant. |
| `DELETE /rules/{pattern}` | Remove a pattern rule. `404` if absent. |
| `DELETE /rules?tenant=<t>` | Remove a tenant's rate row. `404` if absent. |

```json
{ "pattern": "acme/growth", "concurrency": 5, "rate": 50, "burst": 100, "description": "growth plan", "disabled": false }
```

- A field you leave out is **not touched**. `null` on `concurrency`, `rate` or `burst` removes that
  limit, so the next less specific rule applies; `"unlimited"` sets no limit explicitly.
- `pattern` is `comp`, `comp/comp` or `comp/comp/comp`, where each part is a value or `*`. The first
  part matches the scope, the next ones the limit key levels.
- **The most specific rule wins**, from the scope down: `checkout/premium` beats `checkout/*`, which
  beats `*/premium`, which beats `*/*`. A rule applies only to counters at its own depth: `scope/l1`
  limits the first limit-key level, not the scope.
- Each property has its own winner: the concurrency of a counter comes from the most specific rule
  that **sets** `concurrency`, and its rate from the most specific rule that sets `rate`.
- `disabled: true` keeps the rule but removes it from matching. Disabling a specific rule can let a
  broader `*` rule win, which **loosens** the limit rather than removing it.

:::caution
**`*` is not a shared pool.** `{"pattern": "*", "concurrency": 1000}` gives **each** scope its own
budget of 1000; two scopes can run 2000 invocations at once under that rule. Every API response
involving `*` repeats this in a `warning` field.
:::

The node that writes a rule change notifies the other nodes, which re-read the rule book right
away; each node also re-reads it every 30 seconds in case a notice was missed. Compare `version` in
`/rules` with `rulesVersion` in `/scheduler` to see whether a node has picked a change up.

### Rate limits

`rate` is in **compute units per second**, the same unit as `cu` in `GET /metering`. A turn costs its
durable steps plus one unit per started 100 ms of run time. One unit is taken before a turn and the
rest after it; the bucket may go negative, and the next turn waits until it is positive again.
`burst` (default: equal to `rate`) is the most units that can accumulate.

- **Per tenant** (`{"tenant": "acme", "rate": 50, "burst": 100}`): the rate is split evenly across
  the nodes that currently lead at least one range, so the total never exceeds `rate`. If load
  concentrates on one node, the tenant gets less than `rate`.
- **Per pattern**: like concurrency, every matching `(tenant, counter)` has its own bucket.
- Only turns are rate-limited; creating an invocation is not.

## `429` versus `202`

| Situation | Answer | Why |
|---|---|---|
| Waiting for the exclusive lock of a virtual object | `202 waiting` | Normal serialisation, not a limit. |
| Scope or limit key out of concurrency budget | `429` with `status: "throttled"` and `Retry-After` | The tenant hit its cap. |
| Tenant or counter out of rate tokens | `429` with `status: "throttled"`, `Retry-After` = when the bucket refills | Same, for rate limits. |
| Waited longer than `--queue-wait-ms` (default 10 s) for a slot | `429` with `status: "throttled"` | The invocation stays queued. |
| Range overloaded: compaction behind | `429` with `code: "range_overloaded"`, **no `id`** | Nothing was created. |
| Node is not the leader | `503` with `leader` | Go to another node, do not wait. |
| Range being split or merged, or without a leader yet | `503` without `leader` | Wait a moment and retry the same node. |

A `throttled` answer is **not a refusal**: the invocation was accepted, is durable, is queued, and
will run. The body carries its `id`, so you can look it up or attach. `Retry-After` (seconds) says
when to check back.

`range_overloaded` is different: nothing exists yet, and resending after `Retry-After` is safe and
expected. Only new work is refused, only on the invoke routes, with a probability that grows with
the range's backlog and never reaches 100 percent. Everything already running (completions,
timers, retries, signals, attach, calls between invocations) continues, since draining it is what
lets the range recover.

`503` is never used for limits, because it already means "not the leader" and clients handle the
two differently.

## Diagnostics

| Method and path | Answers |
|---|---|
| `GET /limits` | Which counters are in use, their limit, what is left, and which rule won. |
| `GET /vqueues` | Which queues have work, how much is waiting, and what blocks it. |
| `GET /scheduler` | Queue depth, slots in use, locks held, the `rulesVersion` in effect, and per-tenant rate buckets (`rate`, `burst`, `balance`; negative means debt). |

All three are `cluster-admin` and describe only the **ranges led by the node you ask**. Ask each
node, or use `cairn limits`, `cairn vqueues` and `cairn scheduler` against each one.

Two things to keep in mind when reading them:

- `GET /limits` lists only counters that are **not zero**. To see the limit of a scope that is idle,
  read `/rules`.
- Per-queue statistics are kept in memory and reset when a range changes leader.

Metrics: `cairnflow_flow_granted_total`, `cairnflow_flow_wait_ms_total` (divide by `granted` for the
average wait), `cairnflow_flow_blocked_total{resource="lock|concurrency|turns"}`,
`cairnflow_flow_throttled_total` and `cairnflow_invoke_throttled_total`. Labels carry the kind of
resource, never scope names.

## Limits to know

A scope belongs to **one range**, and a range is a single writer committing through object
storage. The effective concurrency of one scope is therefore bounded by what one range on one node
can sustain, whatever its rule says: `concurrency: 10000` on one scope does not give you 10 000.

Think about scope cardinality up front. One scope per large customer works well; one scope per
request does not.
