# Family-locked routing (/docs/family-lock)



At session start the runtime locks one `ProviderFamily` and one
`Transport`. The lock freezes four properties for the session's
lifetime — the tokenizer, the prompt-cache key, the tool-call
dialect, and the refusal pattern. When a provider call fails, the
cascade walks the next rung in the same family; it never silently
widens to another. A model no family derives from keeps the model it
was served: it is retried on itself, never switched to another
family's model. The legacy cross-family fallback for those models is
an opt-in, deprecated, and removed in `1.0.0`.

**Subpath:** `@pleach/core`

The `(ProviderFamily × CallClass)` resolution matrix is **host-supplied**.
`@pleach/core` reaches it through the `AgentAdapter.resolveModel<C>()` seam, so you
wire your own model map without forking the package. The in-family cascade
(`pickNextInFamily`) and the family-exhausted terminal live in the package; the
lookup table doesn't.

## Why the lock matters: provenance [#why-the-lock-matters-provenance]

The model that answers a session can change for ordinary reasons: a transient
provider failure triggers a failover, or a migration moves you between providers.
An audit-bound deployment then has to answer two questions about every turn: which
provider and model produced it, and when and why the session changed.

Family-lock constrains what can change without a record. Within a session the
family is pinned, and a transient failure falls back in-family only
(`claude-opus` to `claude-sonnet`). The fallback is recorded as a `fallbackStep`
row with `inFamily: true` and the originating and attempted models. A real
provider change is never a silent widen: an explicit `sessions.updateProviderModel`
re-locks the session, persisting the new provider and model as a new session
version. Every
`AuditableCall` row carries the `provider` and `transport` that ran, so "which
model produced this answer" is a ledger query.

**Example: which model wrote the reply shown at 14:02.** A provider outage hits
mid-session and the cascade falls back within the family. A reviewer asks which
model produced the reply the user saw at 14:02, and whether the session changed
family.

1. Find the turn's call rows by session and time, using `getSession` or
   `streamByTimeRange` ([Auditable call row](/docs/auditable-call-row#joinability)).
2. Read `modelCall.servedModel` on the row that produced the reply. It names
   the model that ran, beside `call.provider` and `call.transport`.
3. Read the turn's `fallbackStep` row. `originalModel` and `attemptModel`
   show the rung change, `inFamily: true` confirms it stayed in the family, and
   `reason` says why.
4. Compare `requestedFamily` on the turn's `familyLock` rows before and after
   the outage. It is the same family, so the session never changed family.

The rows show which model served the reply and why the rung changed. They don't
show that the two models behave alike, so a threshold tuned on the first
model still needs your own check.

Other tools can switch models mid-thread too. The difference is whether the switch
leaves a durable, queryable record for an auditor. A UI model label or a local
tool's per-message field isn't a typed row in your own database, hash-chained,
tenant-scoped and joinable to the session's audit trail.

## Why the lock matters: comparability [#why-the-lock-matters-comparability]

A model's numeric outputs are calibrated to that model. A confidence score, a
classifier threshold, a relevance cutoff — each one is tuned against a single
model's behaviour, and the same prompt against a different model returns numbers
on a different scale.

Swap the model and the threshold still evaluates. It stops meaning what it was set
to mean. Nothing raises, nothing retries, and the decision downstream reads exactly
as it did the day before.

The lock doesn't make those numbers comparable.
[What locks at session start](#what-locks-at-session-start) freezes the tokenizer,
the prompt-cache key, the tool-call dialect and the refusal pattern — not the
calibration. An in-family rung change still moves the model, and `claude-opus` to
`claude-sonnet` is a different calibration. The cascade does exactly that on a
provider failure.

What the lock buys is that the move is bounded to one family and lands as a row. A
`fallbackStep` carries `originalModel`, `attemptModel` and `inFamily: true`, and
the per-call row carries `modelCall.servedModel` beside `decision.requestedModel`.
The turn where a threshold's basis changed is a ledger query, not something you
infer from drifting outcomes weeks later. If a threshold is load-bearing, alert on
that disagreement rather than on the error rate.

## The routing cluster [#the-routing-cluster]

Family-lock is one of three concepts that decide how a call reaches a model,
alongside [CallClass](/docs/call-classes) (what kind of call this is) and
[Seam](/docs/seams) (the per-class entry point). See
[Concept clusters → Routing](/docs/concept-clusters#routing-cluster) for the
triplet. The [Model resolution matrix](/docs/model-resolution-matrix) is the table
the seam consults, and [Providers](/docs/providers) covers wiring a real SDK.

## What locks at session start [#what-locks-at-session-start]

| Lock              | What it freezes                                                   |
| ----------------- | ----------------------------------------------------------------- |
| Tokenizer         | Per-family token-count semantics                                  |
| Prompt-cache key  | Provider-side prompt cache identity                               |
| Tool-call dialect | Schema shape the provider accepts (OpenAI vs Anthropic vs Google) |
| Refusal pattern   | The shape and language of provider-side refusals                  |

Each matters for a reason. The tokenizer sets token counts, so cost and
context-window fit. The prompt-cache key sets which calls share a provider-side
cache hit. The tool-call dialect decides whether a tool-loop turn parses at all:
Anthropic's `input_schema` and OpenAI's `function.parameters` aren't
interchangeable mid-session. The refusal pattern decides whether a retry loop
stops on "I can't help with that" or retries it forever.

The lock holds for the session's lifetime unless you explicitly re-lock it.
`sessions.updateProviderModel` re-locks the session and saves the new provider and
model as a new session version; nothing widens silently mid-turn. See
[Session lifecycle](/docs/session-lifecycle) for what carries across.

## The family-strict cascade [#the-family-strict-cascade]

**One column, top to bottom. No arrow leaves the locked family.**

<Mermaid
  chart="flowchart TD
    Start[pickNextInFamily] --> R1[locked-family rung 1]
    R1 -.->|fail| R2[locked-family rung 2]
    R2 -.->|fail| R3[locked-family rung 3]
    R3 -.->|fail| FE[family-exhausted]
    FE --> Stop[runtime surfaces state to consumer]
    Other[other family column]
    FE -.-x Other"
/>

The cascade is one function: `pickNextInFamily(family, currentModel, triedSet)`.
It walks the locked family's column in the
[model resolution matrix](/docs/model-resolution-matrix), taking the next rung in
the same family. The matrix's per-family ladders set the order.

When every in-family rung has been tried, the runtime records a
family-exhausted delivery outcome. The turn is served and billed as a
notice rather than counted as an error, and the call row says the cascade
ran out and in which family. The
[auditable call row](/docs/auditable-call-row) gives the fields, and the
event log carries the cascade-exhausted error code
([`5008`](/docs/error-codes)). The consumer
(UI, orchestrator or host) then picks a different family explicitly. There
is no silent cross-family widening.

Example: a session locked to `anthropic` on `synthesize` starts at the
`(anthropic, synthesize)` cell. The first call fails with a provider-side 529, and
the cascade calls `pickNextInFamily("anthropic", "claude-sonnet-4-6", new Set([...]))`
for the next rung. A `fallbackStep` row lands with `inFamily: true` and the new
`attemptModel`. When the column runs out, the runtime records the `family-exhausted`
delivery outcome and stops. No row crosses into `(openai, synthesize)`.

The cascade is strict because a tool-call dialect that worked on Anthropic would
fail mid-session if the cascade widened to OpenAI. The lock prevents that schema
drift and makes any family change visible to the host.

### Circuit breakers reset per session [#circuit-breakers-reset-per-session]

A new user turn clears only its own session's model circuits and
last-resort cooldown. `SessionRuntime` doesn't reset the whole process
at turn start. One user's new message therefore can't reopen a breaker
another user's turn just tripped.

The runtime builds the turn's session identity (`chatId`, `userId`,
`guestId`, `isGuest`, and `provenGuestId` when set) and calls three
optional functions on your `orchestrator.providers.*` modules:
`modelAvailabilityChecker.clearChat(session)`,
`modelCircuitBreaker.clearChat(session)` and
`clearSessionLastResortCooldown(session)`. A module that exports none of
them gets no reset. Its entries expire on their own cooldowns.

`provenGuestId` is a guest id your server verified. Set it on
`SessionRuntimeConfig` or `OrchestratorConfig`, and never from a browser.
A guest's routing state then keys on that guest, the way a signed-in
user's keys on `userId`. `@pleach/core/runtime` exports the types
`HostSessionRoutingModules`, `SessionRoutingIdentity`,
`SessionRoutingCircuitBreaker` and `SessionRoutingAvailabilityChecker`, so
the compiler checks your modules against this contract.

## Provider families [#provider-families]

```typescript
type ProviderFamily =
  | "anthropic"
  | "deepseek"
  | "google"
  | "mistral"
  | "moonshot"
  | "openai"
  | "qwen"
  | "thinkingmachines"
  | "xai"
```

`ALL_PROVIDER_FAMILIES` exports the same members as a frozen array.

The union is closed in the substrate matrix; adding a family means a new minor
release. A BYOK slug, a gateway alias or an unrecognized model id derives no
family; see [Models no family derives from](#models-no-family-derives-from).

## Transports [#transports]

```typescript
type Transport =
  | "native"
  | "openrouter"
  | "byok-native"
  | "byok-openrouter"
```

Transport is per-session, locked alongside family. `native` calls the provider SDK
directly. `openrouter` routes through OpenRouter, useful for evaluation and for
families without a native transport. `byok-native` and `byok-openrouter` use
customer-supplied credentials instead of the deployment's. See
[Providers](/docs/providers) for per-transport wiring.

Transports don't escalate silently mid-session. A session on `anthropic` +
`byok-native` that exhausts the user's key records a `providerCascade` row with
`outcome.status: "exhausted"`, not a silent flip to the deployment's credentials.

## Models no family derives from [#models-no-family-derives-from]

A BYOK slug, a gateway alias or an unrecognized model id derives no
`ProviderFamily`. With no family column to walk, the runtime keeps the served
model. This holds on every runtime, not only on `createPleachRuntime({ provider, model })`:

* **Recoveries.** The provider-error cascade and the synthesis recovery end the
  turn on the served model with neutral copy ("This runtime does not switch
  models"). They no longer switch to a hardcoded model of another family.
* **Guard retries.** When the hallucinated-tool or repetition guard fires, the
  runtime re-streams the same model, at most `sameModelRetryCap` times per turn
  (default `3`; set it on `createPleachRuntime`). Every retry is a billed call.
  Once the budget is spent, the turn delivers the model's real last answer, with a
  note after a hallucinated-tool retry.
* **Run identity.** The `llm.turn` row's `run.model_pivot` reads `"none"`. It
  follows the session's current model: switching to a matrix model with
  `sessions.updateProviderModel` restores the in-family cascade and drops the
  stamp. A `createPleachRuntime({ provider, model })` runtime on such a model pins
  it, so it keeps `"none"` for its whole life.

Matrix-resolved sessions are unchanged and stay family-strict.

### The deprecated legacy fallback [#the-deprecated-legacy-fallback]

`legacyNonMatrixFallback: true`, on `SessionRuntimeConfig` or
`createPleachRuntime`, restores the old cross-family picks for a model no family
derives from. It is deprecated and removed, with the legacy cross-family arms, in
`1.0.0`. It travels through the runtime scope, so it needs `AsyncLocalStorage`
(Node, Edge); elsewhere it has no effect. It never applies to a matrix model or to
a helper-loader failure.

```typescript
import { createPleachRuntime } from "@pleach/core";

const runtime = createPleachRuntime({
  provider,
  model: "my-gateway/alias",
  sameModelRetryCap: 2,          // integer >= 0; 0 = never retry
  // legacyNonMatrixFallback: true, // deprecated: restores cross-family picks
});
```

### Helper-loader failure [#helper-loader-failure]

The cascades read the model-family helpers through the host module loader. These
helpers used to fail by moving every session to `claude-sonnet-4-6`, whatever its
family. Now no session switches model when they fail to load:

* Guard retries re-stream the served model from the same per-turn
  `sameModelRetryCap` budget, for every family, including a matrix-resolved session.
* Once the budget is spent, or on a recovery terminal, the turn ends on neutral
  copy saying model fallback was unavailable. It isn't reported as a family exhaustion.
* A retry-exhaustion record for this case carries the cause
  `"helper-loader-failure"`. A consumer that switches exhaustively over causes
  should handle it.

See [Providers](/docs/providers) for the BYOK wiring and
[Env vars](/docs/env-vars) for the credential surface.

## Host-internal planner calls [#host-internal-planner-calls]

The family lock governs the conversation's seam calls: `synthesize`, `converse`,
`reasoning` and `utility`, which reach a model through the
[provider seam](/docs/seams). A host can also make internal model calls that never
pass through the seam. Those sit outside the lock by construction, and the clearest
case is the planner cold-start.

The [`anchor-plan`](/docs/plans) stage generates the turn's plan, and a host may
run that on its own configured planner model. That model is pinned by host config,
so the call consults no `(family x callClass)` cell and walks no in-family cascade.

It still writes a ledger row, identified by `stage: "anchor-plan"`,
`callClass: "utility"` and `payload.kind: "planGeneration"`. It has no
`fallbackStep`, no `family-exhausted` state and no cross-family `providerCascade`,
because the planner model was never a matrix candidate.

This is a documented exception, not a leak. On a matrix-resolved session, the only
row whose family differs from the locked family should be this planner cold-start.
Any other non-locked-family row is the leak signal. Alert on everything except the
`anchor-plan` / `utility` planner row.

## On the audit row [#on-the-audit-row]

Every `AuditableCall.call` carries `provider: ProviderFamily` and
`transport: Transport` — what actually ran, after resolution. Three
typed payload slots track family decisions:

| Slot              | When it lands                                                                                                                                              |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `familyLock`      | At the resolution boundary; carries `resolverPath`, `requestedFamily`, `familyMismatch`, `byokActive`                                                      |
| `fallbackStep`    | After each in-family rung attempt; carries `originalModel`, `attemptModel`, `inFamily: true`, `attemptIndex`                                               |
| `providerCascade` | At each cascade attempt: a decision-node throw or retry, a provider-exhausted arm, or an external trigger (stream error, max retries, timeout, user abort) |

`providerCascade.source` records which code path wrote the row: `graph` for the
decision-node sites, `imperative-carve-out` for the older imperative callback. Both
are live, and the graph sites emit on healthy fleets, so a `providerCascade` row is
not by itself a lock leak. The row carries `providerFrom`, `providerTo` and
`attemptN`, and nothing on it alone says whether a pivot crossed families.
Don't alert on the slot's presence or on `source`. See
[Auditable call row](/docs/auditable-call-row#typed-payload-slots) for the field shapes.

### Per-call rows [#per-call-rows]

Alongside those decision rows, every provider dispatch writes its own per-call row
(`modelCall`), including retries and both synthesize calls. On the standard
providers a sub-agent's retries get their own rows too. See
[Model resolution matrix → per-call rows](/docs/model-resolution-matrix#per-call-rows)
for how the two kinds of row split cost so each dispatch is billed once.

A per-call row's `call.provider` is attributed in this order, and a family is never guessed:

1. The family of the model that served, when the served id has a `<family>/`
   prefix. A cross-family serve is reported, not hidden behind the lock.
2. The family the dispatch site resolved, or the session's *observed* lock. A
   defaulted family never counts: `AgentAdapter.getObservedSessionFamily()` returns
   `null` while `getSessionFamily()` only reports the default.
3. The requested model's `<family>/` prefix.
4. The placeholder `"unresolved"` (exported from `@pleach/core/audit`).

Per-call rows are where a lock leak shows first: a `call.provider` that differs
from the session's locked family means a different family served the call. Exclude
`"unresolved"` rows from that alert; they mean the family couldn't be attributed.

## In the fingerprint [#in-the-fingerprint]

`family` and `transport` are part of the fingerprint cache key. Calls with the same
prompt and tools but a different family or transport never share a cache entry,
because tokenizer, tool dialect, provider-side cache key and wire shape differ.

See [Fingerprint](/docs/fingerprint#whats-in-the-key) for the full
cache-key shape and the metadata fields the key deliberately
excludes.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Model resolution matrix" href="/docs/model-resolution-matrix" description="The (family x callClass) cells and the per-family rung ladders the cascade walks." />

  <Card title="Seams" href="/docs/seams" description="The per-call-class entry point that calls into family resolution and dispatches the observer ladder." />

  <Card title="Call classes" href="/docs/call-classes" description="The four-class taxonomy that pairs with family to key the matrix." />

  <Card title="Providers" href="/docs/providers" description="The transport layer beneath the lock — native, openrouter, byok-native, byok-openrouter." />
</Cards>
