> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cowboy.inc/llms.txt
> Use this file to discover all available pages before exploring further.

# Cip 39 room session accounting

# CIP-39 extension: native room sessions and accounting

> [!NOTE]
>
> **Cowboy Cloud and Cowboy Chain.** This CIP specifies the Cowboy protocol. Cowboy Cloud runs on this protocol today. Cowboy Chain, a public network on the same protocol, is under consideration for a future release. Where the two differ, this CIP says so.

This is the native-room extension of CIP-39 §11.1. It assigns client tags 4,
7, 8 and 9 and server tag 9 under wire version 2. Client tags 5/6 and server
tags 7/8 remain reserved for Package R. Implementations MUST NOT reassign them.
Canonical encodings, strict signatures, decode bounds and TLS dialing follow
CIP-39. Unknown tags MUST be rejected. Deploy the supporting broker before
enabling runner recovery with these frames; an unsupported old peer is not
permission to infer settlement or bill from absence of redelivery.

> [!NOTE]
>
> The [neocloud C2 amendment](neocloud-operator-economics.md#c2-escrow-provenance-and-refunds)
> adds actor-then-owner room escrow with immutable funding provenance from
> C2's height; legacy sessions without provenance always refund their bound
> actor. [G1](neocloud-operator-economics.md#g1-cordon-and-force-end) adds a
> separate gated operator force-end that preserves accepted earnings, refunds
> unresolved/unused budget and refuses later reports. Below those heights,
> existing funding and settlement remain unchanged.

## Original execution scope

The canonical structure is:

```text theme={"system"}
RoomSessionProofV2 {
  version: u8 = 2,
  chain_instance_id: Bytes32,
  stream_id: Bytes32,
  room_id: Bytes32,
  seat_id: Bytes32,
  job_id: Bytes32,
  native_session_id: Bytes32,
  assignment_height: u64,
  access: RoomSessionAccessV2,
  holder_signing_key: SigningPublicKey,
  expires_at_ms: u64,
  finalized_state_proof: Bytes,
  runner_delegation_signature: [u8; 65],
}

RoomSessionAccessV2 =
  1 Messages | 2 Control | 3 InboxConsume |
  4 InboxAppend { target_seat_id: Bytes32 }
```

The proof MUST authenticate the exact room and seat, native parent job,
assignment, pinned admission and native session under the release's trusted
finality checkpoint. Native execution authority at that proof height MUST
bind the job, session, assigned runner, actor and seat. InboxAppend additionally
requires the target seat. The broker derives the permitted verbs and exact
lane/group scope from these records; requester-supplied CBQS scopes are not
authority. Chain instance, stream, room, seat, job and session identities and
the assignment height MUST match the authenticated records and broker view.

The runner delegation is a recoverable secp256k1 signature over Keccak-256 of:

```text theme={"system"}
"cbqs/room-session-delegation/v2" ||
canonical(version, chain_instance_id, stream_id, room_id, seat_id, job_id,
          native_session_id, assignment_height, access, holder_signing_key,
          expires_at_ms) || Keccak256(finalized_state_proof)
```

The recovered signer MUST be the assigned runner's authenticated registry key.
`room_session_grant_id` is Keccak-256 of those signing bytes. It is distinct
from the ordinary stream-grant id. The signature and variable proof length
prefix are not part of this preimage.

OpenRoomSession (tag 4) uses normal session challenge/holder completion and
fresh execution authority. It can issue only the proof-derived room scopes.
An original proof accepted for accounting MUST NOT restore execution authority.

Bytes use the canonical u32 length prefix. The proof payload bound is
`5_242_880 - 378 = 5_242_502` bytes, accounting for the largest fixed frame:
the 2-byte frame header, 32-byte request id and all proof fields, including
InboxAppend's target seat. Every access variant MUST fit the same existing
5 MiB wire/WebSocket ceiling; decoders enforce the payload bound before allocation.

## Two-phase settlement read

GetRoomGroupProgress (tag 8) MUST carry InboxConsume access. Before expensive
proof work, the broker checks runtime activation, provider/stream identity,
snapshot currency and the applicable read serviceability. This is an
accounting read, not a new execution session or lease; suspended writes do not
by themselves invalidate earned accounting evidence.

The broker authenticates the original execution scope and delegation, then
returns the existing SessionChallenge frame. Its `session_id` field is a
random accounting `read_id`, not an installed session. Each connection permits
at most one unexpired accounting challenge; its expiry is bounded by the
runner delegation and ordinary session-handshake deadline. Only the verified
scope/binding and challenge are retained, not the large proof payload. The
ordinary CompleteSession path MUST NOT consume this challenge.

CompleteRoomGroupProgress (tag 9) supplies the read id, a fresh finalized
session-only proof, and holder signature. The holder signs Keccak-256 of:

```text theme={"system"}
"cbqs/room-group-progress/v2" || complete_request_id ||
room_session_grant_id || read_id || challenge || Keccak256(session_state_proof)
```

The broker verifies strict Ed25519 holder possession, challenge identity and
expiry. The session proof MUST use the trusted chain instance/checkpoint,
satisfy current proof freshness and not precede the original scope proof. Its
immutable native session binding MUST exactly match the original binding.
The native session MUST still be eligible for reporting under its execution
or finalization window and MUST NOT have finalized billing already.

For this accounting read only, the original scope proof may be older than the
ordinary execution proof age. Future-skew limits still apply. Seat revocation
or consumer transfer does not erase the original assigned runner's earned
accounting scope; current billing eligibility is proved separately. No message,
secret, execution session, subscription or new lease is returned or created.

The broker responds with server tag 9 and:

```text theme={"system"}
RoomGroupProgressV2 {
  version: u8 = 2,
  chain_instance_id: Bytes32,
  stream_id: Bytes32,
  lane_id: u64,
  group_id: u64,
  settled_through: u64,
}
```

Both proof-carrying phases are independently bounded by the existing frame
ceiling. The fresh proof uses the same conservative payload bound. The holder
signature is 64 bytes. Errors preserve the normal CBQS code/message/details.

## Durable terminal evidence and runner recovery

`settled_through` is the group's persisted terminal prefix, as in CIP-39 §9.2.
Terminal includes ACK, rejection and terminal expiry. It is not an ACK-only
watermark and does not prove execution occurred. The broker MUST NOT answer
from an unpersisted in-memory transition. A failed progress write MUST remain
retryable without losing its cycles/leases or spinning without delay.
Deleting a group MUST preserve its final durable accounting evidence, scoped
to the same chain instance, stream, lane and non-reusable group id; it MUST NOT
restore a deleted group's execution capability.

Before ACK I/O, the runner durably retains its verified execution result and
signed cumulative native report, original inbox sequence and original broker
scope/proof. A known ACK or DeliveryTerminal response can settle the local
report. After an ambiguous ACK or restart, only an explicit durable terminal
prefix covering the original sequence permits same-session recovery submission.
A quiet connection, lost process ownership or no redelivery is not evidence.
Unavailable/unsettled evidence preserves the report and normal sealed-result
redelivery recovery; it MUST NOT repeat cognition or charge another execution.

Terminal evidence alone MUST NOT authorize a report for unexecuted work. The
verified retained execution result and native signed usage remain prerequisites;
consensus enforces billing identity, nonce, usage, budget and reporting window.
Already-earned usage can be reported after DeliveryTerminal without an ACK.
During successor-session redelivery, confirming the original session's earned
report may precede the successor's ACK: finalizing the original session cannot
close the successor's ACK authority. Original billing confirmation and delivery
settlement remain independent durable receipts, preventing duplicate billing.

## Height-gated native session lifecycle

This section amends the chain's native route sessions, including room seat
sessions; these remain jobs, not CIP-10 workloads. Each feature below has its
own per-network gate under [CIP-50](https://docs.cowboy.inc/cips/cip-50-network-activation.md). All gates
land `NOT_SCHEDULED`. Before each height, preserve that feature's existing
behavior and bytes. Added session fields are optional, absent from old rows
and omitted when absent; update the strict shared record and its metered
shadow decoder/encoder together, with old-row byte goldens. Do not change the
immutable `SessionBindingV1` or existing signed expiry preimages.
Before E1/F activate, ship the updated strict shared decoder to chain/native
proof verification, harness-serve's production native-authority verifier,
cbqsd room-session authority and wake lifecycle, runner-node transport and
room consumer, and CLI room session/trace readers. Update their constructors
and composed fixtures in the same schema change. The lenient cbqsd
confirmation projection still needs a compatibility check. A field's absence
must retain its old shape and checksum charge; in particular, a present
principal adds one address on decode and two checksum passes on encode,
while an absent principal adds neither.

### E1: final report starts closing

At and after `ROUTE_SESSION_FINAL_REPORT_CLOSE_ACTIVATION_HEIGHT`, an accepted final cumulative report MUST start
closing at its execution height, including when budget/request/token caps
are not exhausted. Use the existing close transition: `closed_at` is the
lesser of touch height and signed `expires_at`; `reconcile_until` is
`closed_at + DISPUTE_WINDOW_BLOCKS`. Stop execution authority and retire the
live seat index in the same atomic transition. Release the runner job slot
once, while keeping reconciliation capacity, earned accounting and unused
escrow under the existing settlement rules. A final report does not mean
immediate settlement or permission to bill unexecuted work.

A session already carrying `final_seen` at E1's height MUST start closing on
its next authenticated explicit touch: a repeated final report or a close
by its actor or admitted relayer. Exact report retries retain nonce/billing
idempotence but MUST still perform this pending close transition once.
Only at/after E1 does the exact-report-retry branch perform this additional
transition; reserve and charge its complete added read/decode/write work
before doing it. Below E1 the existing early return remains byte-identical.
A pre-E1 final-seen session that nobody touches still follows today's expiry
close and reconciliation, with financial eligibility bounded by
`expires_at + DISPUTE_WINDOW_BLOCKS` (then the existing bounded service delay).
It is not rediscoverable through the already-retired live seat index.
No activation scan is required. Below E1's height, an early final report keeps
the existing close-on-expiry-or-exhaustion behavior.

The new optional field `close_cause: Option<SessionCloseCauseV1>` is appended
after `last_report`, followed by F's `counted_principal: Option<Address>`.
Both use `#[serde(default, skip_serializing_if = "Option::is_none")]`.
The confirmed suffix then appends
`funding_provenance: Option<SessionFundingProvenanceV1>` followed by
`force_ended: Option<bool>`, using the same default/skip-None rule. Their own
C2 and G1 force-end gates control presence; force\_ended emits only Some(true).
The [C2 provenance schema](neocloud-operator-economics.md#c2-escrow-provenance-and-refunds)
defines the strict nested fields and order.
`SessionCloseCauseV1` uses the default PascalCase enum serialization, like
`SessionPhaseV1`; do not apply `rename_all`. E1 allocates
`ExplicitClose`, `FinalReport`, `Expired` and `ResourceExhausted`;
E3 additionally enables `RunnerRelease`. The G1 extension is `OperatorForceEnd`,
using the same default PascalCase serialization under its own force-end gate
and E1's height-selected cause rule.

From E1, every first close transition MUST record its cause. While
`phase == Open`, `close_cause` MUST be `None`. Below E1 the field MUST be
omitted, including on explicit close, expiry and exhaustion. E3's
`RunnerRelease` cause additionally requires E3; CIP-50 pins E1 before E3.
Record the cause of the **first** close, never its later financial outcome.
If several predicates hold on that transition, precedence is: `Expired` when
the touch height is at/after signed expiry; otherwise the explicit operation
(`ExplicitClose` or, under E3, `RunnerRelease`, or, under G1's
`ROUTE_SESSION_FORCE_END_ACTIVATION_HEIGHT`, `OperatorForceEnd`);
otherwise `FinalReport`
(including the next-touch close of a previously final-seen open session);
otherwise `ResourceExhausted`. Final therefore wins over exhaustion on the
same report. Every post-close accounting/report/idempotent-close transition
MUST preserve `prior.close_cause == next.close_cause`, including absence on
a historical closed row; late final reports cannot overwrite it. Open rows and
historical rows already closed without a cause retain absence; do not
backfill them on settlement. A pre-height open first closed by an explicit
touch after E1 can acquire its first cause. Test every overlap and absent
legacy field. Keep the existing `NativeSessionClosing` topic and session-id
payload unchanged; an optional richer event uses the separately allocated
`NativeSessionCloseCauseRecorded` topic under E1.

### E2: lifetime ceiling

At and after `ROUTE_SESSION_LIFETIME_CEILING_ACTIVATION_HEIGHT`, the governance parameter
`cip15.session.lifetime_ceiling_blocks` is a positive block count,
with compiled default **86,400 blocks**
(`DEFAULT_ROUTE_SESSION_LIFETIME_CEILING_BLOCKS`). The path constant is
`ROUTE_SESSION_LIFETIME_CEILING_BLOCKS_GOV_PARAM`. An unset parameter uses that default;
no genesis seed is required. Its allowlist is inactive below E2's height at
both proposal submission and enactment. Operators MUST leave the parameter at its compiled default until the
network's post-cut Tier-0 governance drill succeeds. This is an operator
rollout rule; the chain does not track drill completion as an authorization
predicate.

Admission MUST refuse an open when `expires_at - admission_height` exceeds
that ceiling, independently of the route's positive `lifetime_blocks` bound.
The open MUST also have a positive remaining lifetime. Refuse, never silently
rewrite signed expiry or project a different timeout. This is an admission
check, not a restriction on historical codec decoding. The refusal is
`InvalidData` with `route.session_lifetime_over_ceiling` when A's
reason contract is active. It is terminal for those signed bytes and means
**re-clamp and re-sign**; it is not a retry of the unchanged open.

On every wake, before signing and deriving the session id, the waker MUST
clamp the template expiry to the authorized wake height plus the minimum of
the route lifetime and the current chain ceiling. Below E2, clamp only to the
route lifetime. Preserve an earlier template expiry. Read the current
parameter even if the route declaration is cached; a lowered ceiling must
shorten new sessions without stopping the room. If a signed open crosses the
height or a parameter decrease and is refused, refresh chain state, rebuild
the expiry/session id and re-sign. Existing sessions retain their signed
expiry; there is no retroactive clamp or epoch sweep.

### E3: runner release

At and after `RUNNER_ASSIGNMENT_RELEASE_ACTIVATION_HEIGHT`, `ReleaseRouteSession` (`SYS_RELEASE_ROUTE_SESSION = 26`)
introduces a runner-signed native session release with ordered payload
`{ session_id: [u8; 32], job_id: [u8; 32], assignment_epoch: u64 }`.
Its complete instruction is 74 bytes. See
[CIP-10's E3 wire contract](https://docs.cowboy.inc/cips/cip-10-runner-containers.md#e3-wire-and-assignment-binding)
for fixed binary/JSON encodings. It carries no reason or assignment hash.
The merged E3 release handler binds these identifiers,
checks first-close eligibility and publishes the transition and release event
atomically. Scheduling requires both E1 and D1 first, as pinned by
[CIP-50](https://docs.cowboy.inc/cips/cip-50-network-activation.md).

Authorize through the runner account's current signing policy and normal
transaction chain-id/nonce replay protection. Refuse unless `session_id`
resolves to the pinned session, `job_id == binding.job_id`,
`sender == binding.runner`, and `assignment_epoch == binding.assignment_epoch`.
A wrong signer is `Unauthorized` (1211); stale/mismatched identifiers or epoch
are `InvalidData` (1213). The epoch is committed native session state, not
CIP-11's connection-bound transport hash or connection identity. Release
never requires the metering key to sign.

Acceptance additionally requires `closed_at.is_none()` and a nonterminal
session. Otherwise refuse with `InvalidData` (**1213**), even when all pinned
identities match. Every accepted release performs the session's first close,
records its cause using E1's precedence and emits `NativeSessionRunnerReleased`
exactly once. A repeat is refused, so no repeated decrement or refund occurs.

It MUST close execution and release the runner job slot atomically,
preserving admitted identity, signed cumulative usage and the reconciliation
window. Earned usage remains payable; unused escrow is refunded under the
settlement rule in force for that session. A legacy session with no funding
provenance refunds its actor. A repeated release is refused before any
counter decrement or refund.

The same E3 gate introduces task `DeclineAssignment`; its full authorization,
redraw and bounded decline policy are specified in
[CIP-10 §16.1](https://docs.cowboy.inc/cips/cip-10-runner-containers.md#161-assignment-decline).
Both new instructions are refused below E3 in block scanning and every
execution entry, including actor calls, governance and timers. When D is
active, every release uses D's assignment marker; never infer a class from
the release height. Every accepted runner release emits
`NativeSessionRunnerReleased` with the bound identities and resulting close
cause under E1's precedence. The operation enables `RunnerRelease` as a
cause but does not overwrite an existing cause or outrank expiry. Its topic constant is
`TOPIC_NATIVE_SESSION_RUNNER_RELEASED`; never change the existing closing
fence event's payload to carry this data. A repeated release is refused and
emits no duplicate runner-release event.

### F: per-owner concurrent-session cap

At and after `ROUTE_SESSION_OWNER_CAP_ACTIVATION_HEIGHT`, admission also enforces the positive governance
parameter `cip15.session.max_concurrent_per_owner`, compiled default **32**
(`DEFAULT_ROUTE_SESSION_MAX_CONCURRENT_PER_OWNER`), with path constant
`ROUTE_SESSION_MAX_CONCURRENT_PER_OWNER_GOV_PARAM`.
Its allowlist is gated at submission and enactment; unset means the compiled
default. Operators MUST leave that default until the network's Tier-0
governance drill has passed; the chain has no drill-completion predicate. This capacity limit supplements per-actor and per-route
sponsorship limits and is independent of fee-payer/allowance rules.

The counted principal is the seat actor's **CIP-37 `ActorOwner.owner()`**,
resolved at SessionOpen from that actor's protected
`ACTOR_OWNER_STATE_KEY = b"__cowboy/actor_owner"` row. Require
`record.actor() == resolved.actor`, `record.owner() != resolved.actor`, and
an owner outside the protocol's system-actor set. Missing/malformed ownership,
a self-owner or system owner is `InvalidData` (**1213**), with
`site=route.session_authority_invalid` under A. Apply the same resolution to
non-room route sessions; a missing room locator is not an exemption.
Neither `RoomAuthorityV1.owner`, a `FallbackToOwnerBalance` entitlement, the
waker signer nor the escrow-funding waterfall supplies F's principal.

Any account may open sessions on a public non-room route. From F's height,
they count against the funding owner's cap: the route actor's
`ActorOwner.owner()` resolved above, regardless of the initiating account.
Operators SHOULD keep a public route's `max_active_sessions` well below that
owner cap, or place room seats under a separate owner, to preserve room capacity.

Normal genesis construction seeds an ActorOwner for every genesis actor;
post-genesis deployment initializes it and child deployment inherits the
protocol owner. Thus no actor from those normal paths lacks a record at the
baseline. Ordinary wallet accounts are not actors and have no such row;
legacy/imported actors predating ownership seeding, or missing/malformed
state, cannot bypass the refusal. F performs no ownership backfill.

Every new session from F's height MUST record `counted_principal` once and
reserve an owner-keyed counter under Job Dispatcher `0x02`, keyed by
`b"route_sponsor_owner:v1:" || chain_id[u64 BE] || counted_principal[20]`.
The value is a fixed-width big-endian u64 active-session count: absent means
zero, and terminal release deletes the row when it reaches zero. Test
`current >= cap` before incrementing to avoid an overflow replacing the quota
refusal at the maximum value. Validate
and reserve with checked arithmetic in the same atomic admission plan as
the actor/route counters and escrow. All post-open transitions MUST enforce
`prior.counted_principal == next.counted_principal`; never re-resolve it on
release or ownership transfer. Missing principal remains absent indefinitely
on legacy sessions. Charge additional reads/decodes before work. Refusal
leaves counters and escrow unchanged.

F's terminal decrement also runs during block-start reconciliation. Gate an
increase of `BLOCK_START_SESSION_RECONCILE_MAX_ITEM_UNITS` (baseline 26) and
its derived item margin/reserve and session-maintenance envelope so the
persisted principal's counter read/write is prepaid and fits the item
maximum. Pre-F maxima and absent-principal release costs stay unchanged;
this is not permission to borrow an unrelated pass's floor.

Count open **and reconciling** sessions. Decrement the recorded principal
exactly once on terminal session-slot release (`session_slot_released`), not
on runner job-slot release or removal from the live seat index. Ownership
changes cannot redirect the decrement. Lowering a cap below occupancy blocks
new admissions until occupancy falls; it does not forcibly close sessions.
An otherwise admissible open at the cap uses A's retryable quota refusal
with `retry_after` indicating release.

Sessions opened before F's height form a **fixed legacy group**: no counted
principal, never counted, and release paths tolerate its absence indefinitely.
No new session can join that group from F's height. Thus occupancy for an
owner is at most its cap plus its remaining legacy sessions; the cap is exact
once that group terminally settles. F and E2 may share a height but need not;
a legacy session can have an expiry beyond E2's ceiling and no finite new
ceiling may be assumed for its drain.

A read-only, paginated query after F's height MUST report the network's
remaining nonterminal legacy group, including reconciling sessions and the
query's chain height, so operators can track it to zero. It MUST NOT create
a block-start or epoch sweep. Owners may explicitly close stragglers;
operator force-end is available only under its own separately specified gate.

## Structured admission refusal contract (A)

This is the shared native route-admission and CIP-10 workload-registry
refusal contract. Existing `StructuredError` contains `code`, `what`, `why`
and ordered string-pair `context` in consensus bytes; the registry derives
`category`, `slug`, `fix` and `docs_url` from the code. Machine classification
MUST use the code and allocated `context["site"]` reason, not prose or an overridden
`fix`. The top-level registry slug is distinct from a refusal's `site` reason slug.

At and after `ROUTE_REFUSAL_CONTRACT_ACTIVATION_HEIGHT`, quota refusals MUST use the fresh code
`ROUTE_QUOTA_EXCEEDED = 1064` (canonical slug `E1064`, category `runner`)
with exactly these ordered string-pair context entries:
`[("site", reason), ("retry_after", hint)]`. Tagged 1213 refusals carry exactly
`[("site", reason)]`; `site` is the closed-list reason. `retry_after` is either the canonical decimal absolute
height of the **first block of the next fixed window**, or exactly
`on_release` for occupancy/reserved-value quotas. It is not a wall-clock
interval. Receipts, RPC and every classifier MUST share this representation.
Do not reuse the retired 1062 or 1063 allocations. A retry budget and delayed,
jittered backoff still apply; no retry guarantee implies eventual capacity.

Other route-admission and workload-registry `InvalidData` refusals retain
code **1213** and gain a reason from the following closed list, using the new tagged families
`RouteAdmissionInvalidDataSite` and `WorkloadRegistryInvalidDataSite`. The logical
reason identities below are allocations, not arbitrary user-provided text.
No producer may invent a reason string or derive one from an exception.

| Refusal | `context["site"]` | Code / client action |
| - | - | - |
| Admission-count window full | `route.admissions_window_exhausted` | 1064; retry at next window |
| Admitted-value window full | `route.admitted_value_window_exhausted` | 1064; retry at next window |
| Actor/route active jobs full | `route.active_jobs_exhausted` | 1064; `on_release` |
| Actor/route active sessions full | `route.active_sessions_exhausted` | 1064; `on_release` |
| Aggregate reserved value full | `route.reserved_value_exhausted` | 1064; `on_release` |
| Owner concurrent sessions full | `route.owner_sessions_exhausted` | 1064; `on_release` (F also active) |
| This block's selection budget exhausted | `route.selection_budget_exhausted` | 1005; retry next block |
| Metering-key version pending | `route.metering_key_pending` | 1213; retry after key progress |
| Workload claim held | `workload.claim_held` | 1213; retry after claim progress |
| Previous attempt draining/live | `workload.still_draining` | 1213; retry after drain |
| Workload generation changed | `workload.generation_conflict` | 1213; refresh generation, rebuild and re-sign |
| Image tombstone grace not elapsed | `workload.image_tombstone_grace` | 1213; retry once reapable |
| Workload count limit reached | `workload.workload_limit_reached` | 1213; retry after deregistration |
| Image volume slots full | `workload.image_volume_slots_exhausted` | 1213; retry after reap |
| Image locators full | `workload.image_locators_exhausted` | 1213; retry after reap |
| Lifecycle expiry/reap calendar full | `route.lifecycle_calendar_full` | 1213; retry after drain or re-sign another expiry |
| Lifecycle cursor not caught up | `route.lifecycle_drain_stalled` | 1213; retry after drain catches up |
| Workload resource-policy epoch changed | `workload.resource_policy_epoch_conflict` | 1213; refresh epoch, rebuild and re-sign |
| E2 ceiling exceeded | `route.session_lifetime_over_ceiling` | 1213; terminal for these bytes, re-clamp and re-sign |
| One request cannot fit its quota | `route.quota_request_impossible` | 1213; terminal, change request/policy |
| Invalid Begin lease/attempt/deadline/recipient data | `workload.attempt_lease_invalid` | 1213; terminal, distinct from a draining predecessor |

The selection-budget refusal at the baseline is `OutOfAccesses`, not 1213;
A tags that specific refusal with `site=route.selection_budget_exhausted`
and preserves code **1005** (`OUT_OF_CYCLES` / access-exhaustion family). Its context order is `[("used", decimal_used), ("limit", decimal_limit),
("site", "route.selection_budget_exhausted")]`, preserving the existing
used/limit values and prose. Other
transaction/child access exhaustion does not acquire that site. Existing static lane-fit code
1061 and its `err_slug` remain terminal. The separate invalid committee-size
check uses `route.selection_input_invalid`, not the retryable site.

For multiple quota failures use a fixed order: admission count, admitted
value, active jobs, active sessions, reserved value; apply actor checks before
route checks, then the owner check. Test static impossibility before temporary
occupancy. No generic quota fallback is allocated or emitted: temporary
occupancy uses its specific E1064 site, while static impossibility uses
1213 with `route.quota_request_impossible`.
`ContainerRegistryError::WorkloadLimitReached` remains **1213** with
`site=workload.workload_limit_reached`, retryable after workload deregistration;
it does not become E1064 just because its check concerns occupancy.

All other A-tagged 1213 reasons are terminal for the signed request and MUST
come from these exhaustive family whitelists together with the
[gated neocloud sites in neocloud-operator-economics.md](neocloud-operator-economics.md#refusal-sites),
each emitted only from its own gate's height. A producer uses the reason for
its validated record/check, preserving that producer's site through callers;
it MUST NOT collapse a storage/infrastructure fault into a data reason.

Route terminal sites:

```text theme={"system"}
route.actor_missing
route.actor_unavailable
route.assignment_record_invalid
route.attachment_invalid
route.commitment_invalid
route.commitment_number_invalid
route.committee_state_invalid
route.descriptor_binding_invalid
route.descriptor_expired
route.escrow_amount_invalid
route.hire_binding_invalid
route.hire_record_invalid
route.issuance_invalid
route.job_spec_invalid
route.job_spec_projection_invalid
route.job_spec_readback_invalid
route.lifecycle_record_invalid
route.lifecycle_reservation_conflict
route.lifecycle_slot_input_invalid
route.lifecycle_timing_invalid
route.metering_input_invalid
route.metering_metadata_invalid
route.metering_version_invalid
route.native_dispatch_invalid
route.native_job_already_exists
route.native_record_invalid
route.prefix_input_invalid
route.prefix_record_invalid
route.receipt_invalid
route.registration_patch_invalid
route.registration_record_invalid
route.relay_map_invalid
route.release_key_input_invalid
route.release_key_record_invalid
route.replay_nonce_conflict
route.revocation_record_invalid
route.route_kind_or_price_invalid
route.route_missing
route.routes_table_invalid
route.routes_table_missing
route.runner_index_invalid
route.selection_state_invalid
route.session_accounting_invalid
route.session_authority_invalid
route.session_binding_invalid
route.session_control_invalid
route.session_encoding_invalid
route.session_expiry_overflow
route.session_fit_invalid
route.session_limits_invalid
route.session_maintenance_invalid
route.session_open_invalid
route.session_queue_invalid
route.session_receipt_invalid
route.session_record_invalid
route.session_report_invalid
route.session_schedule_invalid
route.session_transition_invalid
route.settlement_split_invalid
route.small_record_invalid
route.sponsor_usage_invalid
route.sponsorship_invalid
route.sponsorship_missing
route.terminal_input_invalid
route.terminal_pricing_invalid
route.terminal_record_invalid
```

Workload terminal sites:

```text theme={"system"}
workload.class_limits_invalid
workload.class_name_invalid
workload.class_scratch_too_small
workload.composed_reference_in_use
workload.image_already_registered
workload.image_name_example
workload.image_name_invalid
workload.image_name_not_controller
workload.image_not_publisher
workload.image_not_registered
workload.image_volume_unusable
workload.invalid_image
workload.invalid_record
workload.invalid_settlement
workload.name_empty
workload.name_not_utf8
workload.name_too_long
workload.resource_policy_invalid
workload.serialize
workload.settlement_record_invalid
workload.workload_already_exists
workload.workload_not_found
workload.workload_owner_unauthorized
workload.workload_reference_in_use
workload.workload_reporter_unauthorized
```

A constraint that can never be met is terminal even when reached through a
quota check: e.g. one request exceeds the entire window's admitted-value
limit. Exhaustion of a shared selection budget is temporary; a single
request larger than the whole lane is terminal. For metering keys, verify identity/version, timestamps and ACL first; then a pending
version is retryable **even if wrap\_epoch is absent**, as pending versions
normally have no wrap epoch. Only a non-pending missing wrap epoch is
terminal. Wrong version, future timestamps, missing key and denied actor/TEE policy remain
terminal; distinguish a transient image
state from an invalid image. Existing non-1213 errors (such as authorization,
balance and already named route-cap errors) retain their existing contract
unless this section expressly changes their classification.

The route-side scope includes the explicitly identified native dispatcher,
hire binding, runner-index and lifecycle/timing/slot-planning producers
reached by native route admission. Shared helper code MUST acquire these
sites only for that native origin at/after A. Ordinary JobSubmit and
Container-only dispatcher class/compute-lock paths keep their old errors and
contexts. Workload scope includes SetWorkloadResourcePolicy's stored-policy
validation and signed update: generation/reporter conflicts refresh the
workload, expected-policy-epoch conflicts refresh that epoch, and malformed
owner/Stopped-state/chain/resource bindings use
`workload.resource_policy_invalid` (terminal). All remain in the single
allocated workload 1213 family.

The lifecycle planner's combined chosen-slot test MUST split its predicates:
`expiry_ordinal <= cursor` is `route.lifecycle_timing_invalid` (terminal).
The Reap-slot predicate
`reap_ordinal.checked_sub(cursor).is_none_or(|distance| distance > index_window)`
is `route.lifecycle_drain_stalled` (retryable), matching the earlier
cursor-window catch-up refusal. This is the split at baseline
`lifecycle.rs:721–722`: a chosen Reap slot can spill past the admissible
window even when its initial due bucket fits. Failure to find a free
Expiry/Reap slot remains the distinct `route.lifecycle_calendar_full` refusal.

Shared active-write-prefix overlap/capacity refusals, a full selected-runner
index and lower otherwise unclassified shared readers deliberately retain
bare 1213. Bounded-retry-then-terminal treatment for those bare codes is
permitted only when the node publishes A's gate as active, under the client
rule below. They MUST NOT be relabeled
as permanently malformed records by a catch-all native adapter. Preserve
producer provenance; no generic shared InvalidData or local storage failure
is globally converted into a route/workload site. At the native RecordError
boundary, `JobSpecRoot`, `JobSpecDecode`, `JobRunners` and `Pinned` use
`route.native_record_invalid`; `SessionEncoding` and `SessionInvariant` use
`route.session_record_invalid`; `Overflow` retains `GasOverflow`. Pure
session-transition predicates use `route.session_transition_invalid`.
These choices do not retag ordinary/global callers.

Before A's height, all affected sites MUST preserve their old **code, what,
why and ordered context**, including bare 1213. `what` and `why`, like code
and context, are committed receipt bytes; adding a site cannot silently
change their below-height text. At/after it, the new code and reasons are committed in
receipts. Other features keep their own gates: E2's reason is emitted only
when both A and E2 are active; new F checks do not run before F.

The bounded retry and terminal policy applies to the gated refusal forms:
code 1064, a 1213 carrying a `route.*` or `workload.*` site, and code 1005
with `site=route.selection_budget_exhausted`. Named temporary reasons retry
according to the table; named terminal reasons stop unchanged submission.
On a network where A's refusal-contract gate is dormant, an untagged legacy
code MUST keep each client's historical retry, finality and error handling.
A client MAY apply the tagged-form policy to a bare 1213 only if that node
has published the refusal-contract gate as active. The same client release
MUST select this behavior per network, including for a transaction crossing
the height. Unknown reasons do not authorize an unbounded retry loop.

Existing ownership anchors are
CIP-37 owner loading,
`decode_owner` / `load_owner`,
deployment,
`protocol_owner`, and
genesis ownership seeding,
`ActorOwner::initialize` for each initial actor. They supply the source of F's
principal; the new counter/immutable-field rules are the gated amendment.

The waker, Rust client, CLI, dashboard, wallet and Python client MUST share
these classifications. Before rebuilding after an ambiguous `mempool_rejected`
or `added: 0`, reconcile hash, receipt and nonce: the original may already be
queued. HTTP admission `Retry-After` and a shared TypeScript submission helper
are separate client/transport work; they do not replace the committed
`retry_after` contract.

## Native transition anchors and conformance

Existing behavior was checked at core
`734db73a7c712d0efa2d0fa16f17ca891d5a5879`:

* Session transitions, `apply_report`, `close`, `release_job_slot`, `release_session_slot`: final reports currently set `final_seen` but only expiry or exhausted caps close early; reconciliation precedes terminal session release.
* Session terminal application, `retire_live_room_seat_index`, and accounting, `plan`: slot releases and actor refunds are already idempotent transition deltas.
* Lifetime policy, `SessionLimits`, and waker expiry, `session_expires_at`: positive route lifetime with an off-chain route clamp, without a protocol ceiling.
* Sponsorship ledger, `SponsorUsage::reserve`, `plan_session_metered`, and metering-key admission, `metering_version`: quotas and pending keys currently collapse to `InvalidData`.
* Structured mapping, existing `InvalidDataSite`/`CbssInvalidDataSite`, workload mapping, `map_container_registry_err`, and consensus error projection, `Write for StructuredError`.

Implementations MUST test each gate below/at/above its height and with work
crossing it: duplicate final after E1; lowered ceiling and pre-height signed
open; F legacy opens in the last pre-height block, long-lived legacy sessions,
reconciling occupancy and ownership changes; repeated release/refund; transient
versus impossible quota refusals; old-record byte roundtrips. Client tests
MUST exercise a dormant and active network using the same client release,
preserving historical handling of untagged legacy codes on the dormant network
and allowing tagged-form treatment of bare 1213 only after the node publishes
the refusal-contract gate as active.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.