ADR-164 — Configurable key pools: named pools attach at every cascade level over a default, with a forfait-first fallback strategy; an explicit credential always wins
- Status: Accepted — the operator decided it on 2026-11-08 (three arbitrations: full cascade, BYO users, one big-bang PR; re-precised the same day — free keys are opt-in, confidentiality is not negotiable, an explicitly configured key always takes precedence, the fallback policy is finely configurable)
- Amends: ADR-131 — §5's lending ban
- Date: 2026-11-08
- Deciders: jo (architecture, the four laws), Claude (exploration, design, adversarial review)
- Relates to: ADR-131 (the gateway credential; §5's lending ban is amended by this ADR, dated below) · ADR-121 (the fallback door, the trigger vocabulary, the platform ceiling) · ADR-161 (one resolver; pool grants ride their slot's channel) · ADR-163 (the scope-doc + elected reconciler template) · ADR-154/ADR-155 (the CAPACITY pools — a different "pool"; see Terminology)
- Serves: #3114, under epic #2000; relates to #2005, #2906 (the per-credential default-model seat this ADR's entry overrides sit above), #2972 (the reservation-level pool opt-in this ADR composes with)
Context
iterion.cloud serves its products through gateway keys (the PLIAGE LiteLLM → Scaleway lane, deepseek today) — the durable, rational destination for product runs. In R&D and pilot work a different need exists: pools of keys. An operator pushes subscription forfaits pulled from local agent configs (two Anthropic seats, a Codex seat, a z.ai, a Moonshot, an OpenCode Go Plus) so collaborators get free capacity; an org (sdpc) gets a run pool whose strategy spends the free forfait capacity FIRST and lands on the paid gateway key LAST — a run never fails while any entry can serve, and the switches handle periodic provider resets, manual resets and fortuitous ones (auth failures, reconnects).
The machinery half-exists: pkg/credpool already mutualises lent subscriptions (Pool / Pledge / Broker / Lease / ledgers / cooldowns from ErrRateLimited.ResetAt), but one pool per org, consulted only for a run with no credential of its own, and no gateway keys. The routing cascade (llmroute, ADR-121) and the credential audience chain (OrderedAPIKeyCandidates) resolve configuration through global → org → team → bot → bot-in-team → binding. This ADR generalises the existing pool — it does not invent a third pool concept.
The four laws (non-negotiable, each pinned by test)
- An explicit credential always beats a pool entry. A repo webhook pin, a team key, an org key, a personal key: once an explicit tier sealed a slot, no pool entry may take or move it — the pool fills only EMPTY slots (per-slot gate after tiers 1–4). The honorabilite scenario (sovereign
llm_fallback=none+ exclusive repo pin + an attachment naming a pool that HOLDS gateway keys) resolves bit-for-bit as today, zeroopenai_compatiblerungs composed. - Zero pool without an explicit opt-in. Without an attachment at the level considered, no pool path beyond the legacy donation walk (byte-identical). Opt-in runs from instance to binding (the provisioning records'
pool:block, validated at record-write time);Enabled: falseis a resolved-disabled answer that BLOCKS inheritance at that level (nearest-wins means nearest also blocks); detach deletes and the level inherits again. - Sovereignty is inviolable.
llm_fallback=noneteams and runner-pool teams skip every shared tier — an attachment included (inert, with a named warning); the repo pin on the team's litellm deepseek key stays exclusive and wins its slot before any pool consideration. - The fallback policy is finely configurable and switchable. Each attachment carries
Enabled, the strategy (mode: priority — explicit order, forfaits before metered keys at equal priority — or least_consumed;margin_pct*float64, nil = 85% — refuse-only stays expressible;triggers: the llmroute subset, platform-ceiling-narrowed, frozen effective;reset_hold: stay switched until a manual reset), and borrower-side draw caps (MaxRunsPerDay,MaxUSDPerDay) enforced in the ledger's atomic reserve on theatt:row. The credential preview is the before-the-fact proof, walking the same plan with the same margin constructor.
Decision
- Generalise
pkg/credpoolinto named, multi-owner pools — do not add a third pool concept. A pool carries an owner (org / user / platform — the zero values keep every legacy row an org-owned audience pool) and a visibility:audienceanswers the legacy walk (whole-bundle tier, door probe),privateanswers NOTHING without an attachment — the attachment is the consent. A user pool carries no OrgID (the Audience org-implicit rule must never silently open a private pool); private is user-only. Pool writes go through Patch (theApiKeyPatchdiscipline). - The entry is a Pledge; the lender identity is the owner trick. A pool entry is a
Pledgewhose UserID is the lender: the pushing user (BYO),OrgTierOwnerKey(org)(operator-pushed into an org pool),PlatformOwnerKey(instance pool) — the org-tier sentinel; the OAuth refresh worker, fingerprint and reconnect flows all reuse. Operator-pushed forfaits are ordinary sealedOAuthRecords under the owner key; operator-pushed gateway keys are ordinaryApiKeyrows in a reserved scope, read byGetForLend— the row's TENANCY is the lend boundary, never re-scoped cross-tenant. Entries carry the route binding (Backend,Model— an override ABOVE #2906's future per-credential default-model seat, never a parallel seat; a gateway entry REQUIRES the verbatim model id), a priority, andLendScope. - The attachment cascade rides the price-feed template.
pool_attachments: one document per scope (platform,org:<id>,team:<id>,bot:<team>/<bot>), CAS on updated_at (loud 409), memory+mongo twins. The binding level rides the provisioning records as apool:block — validated at record-write time (the writer must own the pool or the audience must admit the scope; MachineLanes consent is that block, owner pool / org admin only); surfaces without a validated write surface (trigger subscriptions, webhook configs) keep the fail-closed launch refusal. The fold (resolveRunPoolAttachment, the routing fold's sibling) resolves nearest-wins with the platform floor, refuses the launch naming the level on a read failure, an unreadable block, an unknown trigger or a vanished pool, and FREEZES{pool, scope, strategy, limits}onto the run doc; the resume replays it — the pool and strategy freeze, the ENTRY choice re-resolves per attempt (the broker's supersede machinery arbitrates per-attempt leases inside the same frozen pool). - The attached pool tier is attachment-aware and per-slot. Without an attachment the empty-bundle gate is byte-identical. With one, the tier loops the slots the pool can serve that tiers 1–4 left empty — one grant per slot, forfaits before metered keys,
res.grantscarrying every sealed grant whileres.grantstays the whole-bundle semantics' answer. The margin skip fires at the ONE eligibility site live and preview share: an OAuth-shaped entry whose freshest account reading sits at or past the margin (or rejected) with a future reset is skipped PER CANDIDATE (the next entry serves), the skip arming the durable retry at its reset instant. Reactive shapes (plain keys, gateway keys, the facade providers) gate on their provider cooldown alone — and the preview says "reactive — no provider telemetry" about them instead of promising a margin that would never fire. - ADR-131 §5 amended (dated, appended there): pools may lend gateway keys, through the attachment, as the PAIR. The runtime half shipped with this ADR: a gateway entry seals as key + canonical URL through the one chokepoint (
setAPIKey), the AAD binding the entry's own URL, the endpoint-aware fingerprint riding the bundle; a gateway grant without its URL is refused and released.openai_compatiblestays OUT ofDefaultPairOrderandKnownRoutingProviders— it enters the pool wants only through the attachment (poolGatewayWants), and the DOOR's by-name refusal stays (the pool tier is the only gateway lending path). The four tests pinning the ban (TestDefaultPairOrderCoversEverySealableSlot, itspair_order_refusal_warning_test.gotwin,TestWantForSlot_totalOverTheVocabulary,TestGatewayPairStaysOutOfTheWhitelistUntilTheReplayWarningLands, the lendability/provider-coverage refusals) all still pass UNCHANGED — they pin the legacy half, byte for byte; the attached half is pinned by the new attached-tier suite. The e2e matrix line "nopooluntil the pool door exists" is retired — the door exists since #2210, and there is still nopool:PAIR (entries ride the existing slots). - Entry rungs compose through the existing fallback machinery. A sealed entry carrying a route binding lands one rung (Provider = the SLOT the grant sealed, On = the frozen triggers, Metered on paid entries) after the operator's chain and the policy ladder — the run's fallback chain literally ends at the paid gateway key. A binding-less grant composes nothing; an empty frozen trigger list composes no rungs (the M4 round-trip lesson). No new credroute channel: a pool grant rides its slot's channel with the
PoolSourcedprovenance stamp; the #2645 N-pools guard keeps refusing pool-run content on the server-env aux surfaces. - Resets. Periodic: the provider's own
ResetAt→CooldownUntil→ automatic re-ranking (existed). Manual: the entry reset route clears the cooldown AND forgets the readings the margin skip acted on (DeleteByFingerprint, the documented escape hatch). Fortuitous: consecutive auth failures →HealthAuthFailed, reconnect flows clear (existed).reset_holdis attempt-scoped: the publisher writes a held bit when a switch fires, and the resume re-acquires the entry it last sealed instead of re-ranking, until a manual reset. - The signal reconciler is elected.
pool-signal-synccampaigns under a lease (the price-feed sweep's sibling, 5-minute tick): it refreshes the ATTACHED pools' OAuth entries' usage readings so the launch-path margin predicate pays no probe latency — probing only the shapes that carry proactive signal (claude_code today), leaving the reactive ones honest. Never an every-replica loop; theleasedNetsregistry enforces the registration. - BYO is complete. Every user creates pools, pushes entries (the bulk-import lane seals a local agent's credentials blob verbatim under the pool's lender key — never logged, never returned), attaches and detaches. A shape with no funding lane (an own-config-only harness, ADR-161 decision 5) imports INERT with a named reason — warn-not-reject, never a silent loss. "Pools proposed by default on some bots" is a V2 outlook: a studio SUGGESTION at opt-in time, never an implicit attachment.
- Cloud twin in the same change. The stores, the fold, the walk, the rungs, the reconciler, the routes, the CLI (
iterion remote pools) and the studio sections ship together; a replica deployment converges like one process. Composition with #2972 (ADR-155 u5's reservation-levelPoolEligibleopt-in, default OFF): the reservation gate answers "may this launch draw from pools at all" (capacity posture, upstream); the attachment answers "WHICH pool serves it, under what strategy". When #2972 lands, both gates compose — neither replaces the other.
Terminology — three "pools", one repository
- Credential pool (
pkg/credpool) — the mutualised subscriptions this ADR generalises (now: named, multi-owner, attachable, mixed forfait+gateway). - Runner pool (ADR-154,
RunnerPool, queue v23) — the sovereign EXECUTION pool boundary: a namespace + an enforced proxy. Unrelated to key pools except by the word. - Reserved capacity (ADR-155, #2968–2975) — durable launch capacity.
PoolEligiblethere composes with attachments per Decision 10.
Consequences
- An operator can onboard collaborators in one command: create a pool, import the forfaits, attach at the instance level as the deployment default; every team inherits and may override or detach. sdpc attaches at its org level with forfaits prioritised ahead of the paid gateway entries; runs deplete the free dose first and land on deepseek last.
- The margin is only real for Anthropic-shaped signals today; codex, zai, moonshot and opencode have no window telemetry, and the strategy degrades per shape — the UI says "reactive" where a margin would lie. #3032 (an exhausted chain classified AUTH_FAILED never auto-resumes) remains the generic gap it was, not absorbed here.
- The pool-signal reconciler is scoped to ATTACHED pools; org-tier and platform-tier readings keep the launch-path probe as their only warmth.
- The frozen snapshot carries scope + draw limits so the
att:row enforces exactly what the scope's record said at launch; a resume replays the frozen pool even after a detach — a detach mid-run never strands the resume. - Known limits, filed: the binding-level
pool:block's write-time decoder (the fold consumeshigherlayers today; the schedule/forge-integration write surfaces are where it lands); the per-credential default-model seat is #2906's (entry overrides sit above it today); cached-input pricing for gateway entries rides ADR-163's feed gap (#3103).
Alternatives rejected
- A new
key_poolsentity beside credpool — a third pool concept duplicating audience, limits, leases, cooldowns and metering; the Pool already carried the explicit ID "a deployment can run several without a schema change". - Pool membership as
llmroute.Policyfields — config is not a credential inventory; pair_order's REPLACES semantics are built for route fields, and a reconciler + orgsweep need scope docs to walk. - A
pool:<name>pair slot — retired by ADR-121 question 1 (a pool pair names no family) and the F2 lesson: an unenumerated slot vanishes from every launch the moment the default answered. Entries ride the existing slots. - An eighth credential tier between Org and Pool — duplicates the pool tier's acquisition/seal/metering path for no new semantics; the attachment-aware gate plus the per-slot loop is the same walk, better placed.
- Visible-set filter feeding the BYOK tier — pool entries are pledges/OAuth records, not ApiKey rows visible to the team walk; the audience gates would be bypassed.
- Every-replica signal refresh — the
startOAuthForfaitRefreshprecedent exists for boot-phase sweep reasons; a readings poller copying it would probe providers once per replica. Elected, or not at all. door: offon the attachment — the door is governed by the scope's own routePolicy triggers; a second dial would duplicate a duty.- MachineLanes as an attachment field — the binding-level
pool:block IS the machine-lane consent (its write-time validation carries the authority); a boolean on the attachment duplicated a consent the record already expresses.
Watch
- The margin's honesty: only Anthropic-shaped entries carry proactive signal today; new provider usage endpoints are adapters on the pricefeed
sources.goregistry pattern, never engine ifs. - The att: draw caps' estimates: the dollar figures stay ESTIMATES on subscriptions (the credpool doctrine) — never summed as invoices.
- #2972's landing: compose
PoolEligiblewith attachments exactly as Decision 10 states, and re-run the attached-tier suite against the reservation gate. - #2699's landing: the pools' pod-env model dials migrate to team/binding DB routing policies — the
pool:block is precisely that seat.
Amendment — 2026-11-09 (#3122): the binding block reaches the forge integration
The "Known limits" line above named the binding-level pool: decoder as pending. It lands on both records that own a validated write surface:
- One shape, one decoder, one consent check.
credpool.Bindingis the record-carried block (the schedule'sPoolBindingis now its alias);decodePoolBlockdecodes STRICTLY (a camelCase dial refuses) under the routing block's three-way rule (absent keeps,nullclears, an object replaces), andvalidatePoolBindingWritechecks shape, triggers, the pool's existence and enablement, and its consent (an org pool of the team's org, a user pool whose audience admits it — never a private pool, never the platform's instance pool). - The forge integration (repo-bots enable/PATCH) carries the block on the record AND on the webhook config it provisions — the enforcement half the webhook lane folds as its
binding:webhooklayer — and projects it onto its scheduled rows with a provenance flag (PoolFromIntegration, the twin ofRoutingFromIntegration): a projected block follows every integration write, an operator's own row block survives. A pair diverged between the two stores refuses a silent re-provision (the deterministic class the org-approval arm consumes). - Org approval. A spoken block parks (null included — the block moves which credentials fund the repo's unattended runs), the parked record replays it, and the apply RE-VALIDATES its consent: a pool disabled or narrowed while the request waited is refused (409), never granted by the approval.
- Unchanged posture: trigger subscriptions and hand-written webhook configs have no pool field (the webhook CRUD request carries none); their launches read the stored scopes only.
reset_hold's runtime half (same date, #3122)
Decision 7's held bit lands on the LEASE, not the run doc — the lease is already the per-attempt record of which entry served, and the manual reset needs one store to clear:
- A seal-time switch marks the lease it opens
Held: the broker's ranking walk holds the entry that serves after a candidate at least as well ranked declined (ranked ahead of it and refused, or filtered out — margin, cooldown, health — with an equal or better priority), or that re-serves the run's held entry. The strategy's first choice is never held. - The resume's walk (the same
acquireFromAttachedPools) reads the run's newest held lease of the kind (HeldPledge, closed leases included) and ranks that entry first when it is eligible; ineligible, the ordinary ranking serves. - The entry reset route lifts every hold naming the entry (
LeaseStore.ClearHeld, memory + Mongo twins); the write surfaces accept the dial. - Scope, stated: a switch made IN-RUN by the entry rungs does not hold — the in-run chain restarts from its top on every attempt.
- With it, the attached walk's takeover is per resolution: its FIRST acquisition supersedes what the run's previous attempt left open (a dead pod's leases no longer hold the donors' slots until the TTL), every later slot is that grant's sibling.
The first local review round on #3123 (same date)
- Consent asks only of a block that draws: an opt-out block (
enabled: false) grants nothing — it stops the fold at its level whatever the named pool's state or owner — so it writes with a valid shape alone; that is how a repo stays out of the platform's attached pool. A user pool's audience may name a team outside any org. - Every lane that launches for an integration folds its block: the direct webhook lane, the board and pipeline card lanes (only for a bot the integration runs, while it is enabled — a card's bot is member-writable), and the webhook-source credential preview. The signal reconciler warms a pool an integration binds, and a pool still drawn by an enabled binding block refuses deletion (409), like an attached one.
- A request that binds a live shared pool is reviewed under the
shared_credentialsapproval scope even when the team funds its own runs: those runs are the pool's. - An attempt's report settles exactly its own leases: the leases one resolution opens share an attempt id, and the report books each its fingerprint slice in whatever state it is (open, or superseded by the next attempt's takeover) — never a lease of another attempt of the same run. A lease returned unused settles nothing, and its attempt's siblings still settle by their shared attempt id — the report never reaches past it to an older attempt's lease.
- reset_hold's switch is an exhaustion: margin, cooldown, health or an exhausted allowance of an entry ranked at least as well — never a paused, bot-filtered, out-of-hours or busy one, nor a store error; the run's NEWEST lease of the kind decides what it holds.
The second and third local review rounds on #3123 (same date)
- A coarse report is booked conservatively: when the report carries no per-credential split, every lease of the attempt books the whole attempt and takes its condition — a donor's cap bites early rather than never, and a failing credential is parked whichever slot it served. Only the borrower's
att:draw row books the attempt once, on a lease of the attempt that served. - reset_hold's exhaustion is real spend: a runs-per-day ceiling always counts; a $ ceiling counts only when the spend is real — with runs in flight the ceiling can be met by allowance merely promised to them, which is busy, like a full concurrency slot set.
- The self-funded exemption reads the effective block: the one the repo's runs fold after the request — the spoken block, or the integration's stored one when the request says nothing (an add-bots enable, a bots-only PATCH, an unreadable integration counting as drawing), and the managed webhook config's own block on a CRUD patch. A schedule write binding a live pool is reviewed the same way; a schedule has no parking lane, so an org that would review it refuses it (409) — an org admin binds it, or the binding rides an integration through the repo-bots API.
- A card lane always folds an integration's opt-out block, whatever the integration's state or the card's bot — it grants nothing; an enabled block still speaks only for the bots the integration runs, while it is enabled.
Amendment — 2026-11-10 (#3147): the follow-ups of the closing review round
- A report settles on the lease it finds. A report decides on a snapshot of the attempt's leases, and a lease can move before its CAS lands. A lost CAS re-reads the lease and settles on what it became: a close lost to the run's resume superseding the lease is still the attempt's own report and books through the stamp; a stamp lost to a takeover that did not happen (the lease reopened) closes it. The
att:carrier closed by the sweeper between the snapshot and its CAS hands the row to the next bookable lease. An interim report's carrier is the first lease it charges (it closes nothing), so a lease a racing final already closed never swallows the interim'satt:share. - An interim report on a superseded lease spends without settling: it charges the lease and leaves the stamp to the attempt's final report — and the supersede undoable, so a refused resume's rollback reopens the lease for the attempt that goes on.
AddCostlands on an open or superseded lease, never on one reported, released or abandoned (memory and Mongo twins alike). - The attempt id travels with the run message. Every pool acquisition carries an attempt id (the legacy pool tier and the fallback door too); the publication stamps it (
pool_attempt_id) and the runner reports throughReportAttemptID, which settles exactly that attempt's leases. The publication instant pins by ORDER and could pin a successor's lease when a publication was floored past the next acquisition; it remains the pin of a message older than the field. - A captured release covers the attempt:
CaptureReleasepins the newest open lease and its open side-by-side siblings (same attempt id), never another attempt's open lease. Released leases give their run units back even when an earlier delivery's interim charged them (the spend stays booked) — a known gap, #3151: another run can take a refunded unit before the parked run's resume (a one-run-a-day entry then serves two runs that day), and a hold the run earned is forgotten across the release. The fix needs an attempt-level "ran" fact and a close outcome that reads as served; two review rounds showed a per-lease guess is wrong both ways. - reset_hold reads a spent $ ceiling under the own-unit exemption: the run's own earlier unit is no runs/day exhaustion, but a $ ceiling the ledger shows spent still is, whichever of the late report and the resume landed first.
- A schedule PATCH recognises an echo before validating a write: an echo of the stored block writes nothing — even when its pool was disabled since — and a block's triggers compare as a set. A default written (
mode: priority,triggers: [usage_window],margin_pct: 85) is not an echo of the absent dial: the absent one follows the default, the written one pins it. - The binding-block walks page through all teams (
identity.AllTeams): the signal sweep and the pool DELETE guard read every page, over a total order (created_at, then id — the paged identity lists' tiebreak), with consecutive pages overlapping by half a page, so a team deleted mid-walk shifts no live one out of reach unless more than that many go between two reads. - The webhook-source credential preview folds the config's routing block as the webhook lane's launch does, and refuses a caller-supplied run level that launch never folds.
- An unattached level answers
attached: falseonGET …/pool-attachment(200), so the studio offers the attach form there; a 404 now means only that the server lacks the feature, and a store error answers 503 instead of reading as "nothing attached".
Amendment — 2026-11-18: the identity of an api_key entry carries its key
Decision 2's "the entry is a Pledge; the lender identity is the owner trick" holds; the pledge's identity now names the credential on both shapes. The identity of an api_key entry is (lender, source, ref, key_id); two keys of one provider are two entries. The identity is the Mongo _id of cred_pledges (lender|api_key|ref|key_id, four segments), so the three-segment shape put a donor's two Anthropic keys on one _id and the second write silently replaced the first — half the donation lost, and the broker nothing to fail over to when the first key cooled, failed authentication or met its ceiling.
oauth keeps the three-segment identity (lender, source, ref) because the OAuth store holds one connection per kind — the rank chain is the provider-side fallback of that one connection, and only the primary is lendable, so a subscription can never meet a second connection of its kind that would collide. Its ids are unchanged byte for byte; the change's blast radius is the api_key pledges only.
The migration ships in the same change as the identity, never after it: a boot backfill in credpool.EnsureSchema rewrites the inherited three-segment api_key ids, idempotently — leases (closed ones included), the ledger rows' id prefix, then the pledge document LAST — and a backfill error aborts the boot. Without it, a write missing the old document would insert a second pledge for the same key, and the same key could be leased twice, each grant with its own concurrency slot and ceiling, while the lender's ledger stopped seeing its own spend.
