> ## 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-27: Actor fork() — Self-Cloning Primitive

> A runtime syscall that lets an on-chain actor clone its code and state into a new actor at a deterministic address, with the forking actor recorded as the child's parent.

> [!NOTE]
>
> **Status:** Draft\\
>
> **Type:** Standards Track\\
>
> **Category:** Runtime / SDK\\
>
> **Created:** 2026-05-22\\
>
> **Requires:** CIP-1 (Actor Message Scheduler), CIP-3 (Fee Model — amended: fork schedule + fee denomination), CIP-4 §12 (State Rent and storage limits), CIP-6 (Python SDK & Actor API), CIP-26 (Account Libraries — amended: fork pin initialization), CIP-29 (On-Chain Event Hooks — amended: `subscribe_event` emitter-existence guard, §3.2 class-B residue), CIP-30 (Per-Actor Storage Root)\\

> [!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.

## Background

Actor swarms and other multi-actor systems need actors to create children at runtime. `DeployActor` accepts an actor as the deploy sender, gated by `exec.spawn`. The deployer must reference a `code_hash` published off chain first, because an on-chain actor has no filesystem.

## Goal

This proposal defines `fork()`, a runtime syscall that creates an actor from the executing actor's code. Full mode copies its storage byte for byte. Clean mode starts with empty application state. The child gets a fresh deterministic address, an explicitly designated or defaulted owner, and a manifest validated for inheritance. Its parent is the forking actor.

## 1. Abstract

`fork()` follows Unix `fork(2)`. An actor can fork only itself. The call synchronously returns the child's address within the same handler, so the parent can use the child immediately.

`fork()` uses the parent's code, already content-addressed on chain, with no off-chain dependency. The existing fresh-actor deployment path remains available (`DeployActor`, CIP-6 §6.3).

## 2. Motivation

Cowboy actors currently use this deployment path:

1. A transaction or a manifest-`exec.spawn`-entitled actor uses `DeployActor` to deploy supplied code bytes.
2. No other deployment path exists.

`fork()` lets an actor create children from its own validated, content-addressed code. A coordinator can create workers, a template can create instances, or a game `City` can create units without an off-chain step.

### 2.1 `fork` is not `spawn`

`fork` and `spawn`/`DeployActor` have these behaviors:

| | `spawn` / `DeployActor` | `fork` |
| - | - | - |
| Child code | supplied by caller (a `code_hash`) | the caller's own code |
| Child state | empty; `init` constructs it | full mode: exact copy; clean mode: empty, `on_fork_clean` constructs it |
| `init` runs? | yes | no — `on_fork`/`on_fork_clean` takes its place |
| Off-chain dependency | yes (code must be pre-published) | none |

`spawn` means *fresh process from a definition* (cf. Erlang). `fork` means *copy of the caller* (cf. Unix). They are kept as distinct verbs.

## 3. Specification

The coordinated fork ABI in this draft, including clean mode,
callback-existence checks, callback dispatch, the CodeMeta carrier, birth-only
receipt-key enforcement, the residue census/purge and its write-time guards, is **not
shipping in the wallet-identity release**. Its normative requirements apply
together only to the future fork release, after a non-conflicting CodeMeta key
prefix and value tag have been assigned and its conformance vectors pass. The
wallet release adds the staged-state WalletMark rejection to the existing fork
path; it does not implement or activate those future mechanisms. The existing
address derivation, Actor v9 encoding and checked fork counter remain the
address-group release behavior recorded in §5. Unless a clause explicitly names
the wallet-identity or address-group release, the requirements and acceptance
criteria below target the future coordinated fork release.

### 3.1 The `fork()` syscall

The runtime MUST expose a host syscall with this SDK interface:

```python theme={"system"}
from cowboy_sdk import fork

child_address = fork()                          # full copy, owner inherited
child_address = fork(endowment=100_000_000)     # seed child with 100_000_000 wei
child_address = fork(new_owner=hirer_addr)      # full copy, child owned by hirer
child_address = fork(mode="clean",              # code only, no storage —
                     new_owner=hirer_addr,      #   the instance-spawning form
                     payload=hire_config)
```

`fork()`:

* MUST be callable only from within an actor handler. It clones the currently executing actor and takes no target argument.
* MUST be synchronous: it creates the child and returns the child's 20-byte address before the calling handler continues.
* MUST be metered (§3.8) and MUST honor the **read-only execution flag** per CIP-6 §8.1: a `read_only` call MUST reject `fork()` with `HostError::Forbidden`.
* MUST count against the cross-actor call-depth limit defined for `call()` (CIP-6 §9.1); a `fork()` whose `on_fork` callback would exceed call depth is rejected.
* MUST accept an `endowment` argument (wei, non-negative integer; default `0`). When `endowment > 0`, the runtime MUST atomically debit `endowment` from the parent's native CBY balance and credit the same amount to the child as part of the fork. See §3.3.1.
* MUST accept a `new_owner` argument (20-byte address; default `None`). When given, the child's owner slot (`__OWNER__`) is set to `new_owner` as part of the fork before any callback runs. In full mode, this write follows the storage copy and overrides the inherited value. The zero address is rejected at the host, mirroring `transfer_ownership`. When omitted: full mode preserves a valid existing 20-byte owner value, including the explicit 20-byte zero-address renunciation marker; an unset owner (absent or empty slot) instead defaults to the **forking actor itself**. Clean mode always defaults to the forking actor. A renounced owner is a set value. It MUST NOT be converted into a new owner. Malformed nonempty owner values of any other width reject as `InvalidInput` at the storage-snapshot step. This closes the first-caller ownership bootstrap window for never-owned parents without undoing explicit renunciation. Owner state has no bearing on capability inheritance. §3.7.1 applies inheritance rules at every actor-identity boundary.
* MUST accept a `mode` argument: `"full"` (the default, with the copy semantics of §3.3) or `"clean"` (§3.3.2, code only with no storage).
* MUST accept a `payload` argument (bytes; clean mode only). It is delivered verbatim to the child's `on_fork_clean` callback (§3.5.1) as its initialization input, and is bounded by `MAX_INLINE_BLOB_BYTES` (64 KiB, the standard inline-blob cap); larger initialization data goes through CBFS by reference. Its bytes are charged as `payload.len()` Cells at the standard inline-blob rate, and the seeded lifecycle and receipt slots are charged as ordinary reserved-slot storage writes. The implementation adds exact constants to the CIP-3 gas schedule. The raw-host ABI specifies parameter order, encodings, and per-error result codes for the new rejections alongside the host function, mirroring the existing fork ABI conventions.
* MUST accept a `child_manifest` argument (the §3.7.1 fork profile; default `None` = verbatim manifest). Encoding is an explicit `Option`: omitted means verbatim, `Some(manifest)` means the profile. `Some` of an empty manifest is a valid, distinct value for a child with no grants. A manifest-bearing parent can never profile a child to the *legacy no-manifest* state. `None`-manifested actors predate entitlements and fail open, so the host rejects that construction. Profile bytes are bounded by `MAX_FORK_PROFILE_BYTES` (16,384, defined below; no deploy-time manifest byte cap exists to reference) and metered per §3.8; parameter order and stable error codes are fixed with the host ABI.
* The host enforces every parameter rule above before staging. A zero or malformed `new_owner`, an unknown `mode`, `payload` in full mode, or an over-cap payload each reject the syscall. Actor code can reach the raw host interface, so SDK-side `ValueError`s alone cannot enforce these rules. These parameters and both modes are MUST-support for a conforming runtime.

The raw host signature is **normative here**, replacing the v1 prototype's `fork_actor(u64) -> address`:

```
fork_actor(
  mode: u8,                 // 0 = full, 1 = clean; other values reject
  endowment: u64,           // wei — the native ledger (`Account.balance`, `transfer_balance`) is u64;
                            //   the SDK rejects integers exceeding u64::MAX before the host call
  new_owner: Option<[u8;20]>,   // None = 0x00 tag; Some = 0x01 tag + 20 bytes; zero address rejects
  child_manifest: Option<Bytes>,// None = 0x00 tag; Some = 0x01 tag + length-prefixed manifest codec bytes
  payload: Option<Bytes>,       // clean mode only; rejects in full mode; ≤ MAX_INLINE_BLOB_BYTES;
                                //   None and Some(empty) are both valid encodings and semantically
                                //   identical — the callback receives zero bytes and
                                //   __FORK_PAYLOAD_HASH__ = keccak256 of the empty byte string
) -> Result<[u8;20], HostError>
```

The signature above is the **logical ABI for the future coordinated fork
release**. The shipped host method still
accepts only `endowment: u64`; its ZIPC request is
`HostCall::ForkActor { endowment }`. The five-argument ABI above has not shipped.

Production host calls cross the Zygote worker/node boundary as serialized
`pvm-zipc` `HostCall`/`HostReply` messages. The worker's `HostApi` implementation
is a transport proxy; the node dispatches the requests to the host. ZIPC's
`WIRE_VERSION` is **11** at `ada5db98f`. Node and worker MUST use matching wire
versions, and a mismatch is rejected before the worker forks an execution
child. Every serialized request or reply shape change MUST bump the wire
version and ship compatible node and worker binaries together. The handshake
also checks the semantic build identity.

Implementing the proposed ABI requires coordinated changes to the Rust
`HostApi` trait, Python bindings, ZIPC request/reply schema, worker proxy, and
node dispatcher. The proposed Rust signature is
`fork_actor(mode: u8, endowment: u64, new_owner: Option<[u8;20]>, child_manifest: Option<Vec<u8>>, payload: Option<Vec<u8>>) -> Result<[u8;20], HostError>`.
At the binding from Python to Rust, integers are range-checked into `u8`/`u64`
(out-of-range raises before the host is called), `bytes` becomes `Vec<u8>`,
and Python `None`/value becomes `Option`. A `HostError` return surfaces as a
typed exception carrying the numeric code, so actor code branches on the same
pinned codes through either interface. Malformed-argument vectors exercise the
binding layer.

Error variants, each with a **pinned numeric code** in the shared `HostError` table (codes 1–9 and 100–117 were previously occupied; the wallet-identity release newly allocates 28 to `WalletAddressConflict`, so future fork errors must also treat 28 as occupied; existing allocations include `SandboxViolation` = 9, `NestedOutOfGas` = 116 and CIP-29's `EventSchemaMismatch` = 117; the fork block takes 120+): `InvalidForkMode` = 120, `InvalidOwner` = 121, `PayloadInFullMode` = 122, `PayloadTooLarge` = 123, `ForkProfileNotSubset` = 124, `NonInheritableGrant` = 125 (code 126 is unassigned after withdrawal of a draft error; later codes keep their pinned values), `MissingForkInitializer` = 127, `ForkCountOverflow` = 128, `AddressCollision` = 129, code 130 is unassigned, `KvBytesExceedsMax` = 131 (§3.3.3), `KvCountExceedsMax` = 132 (§3.3.3), `BalanceOverflow` = 133 (the child-side `pre-funded + endowment` checked add at its child funding step). `PinSetMismatch` = 134 belongs to CIP-26's upgrade rule (import-name equality on `upgrade_self`/`UpgradeActor`) and is allocated from this table so codes stay collision-free. Endowment failures reuse the existing `InsufficientCbyBalance` = 107; `Forbidden` = 5 covers read-only and call-depth rejections as it does for `call()`; malformed or invalid `child_manifest` content reuses `InvalidInput` = 2; gas exhaustion is `OutOfGas` = 1. The wallet-identity release uses that `WalletAddressConflict` = 28 allocation for a derived address carrying `WalletMark` (receipt slug [E1228](https://docs.cowboy.inc/errors/E1228.md)); it is distinct from an existing Actor collision. §3.3.2 requires fork after a same-handler `upgrade_self` to succeed from the entry tuple. An implementation cannot reject it as a dirty binding.

The bounds are `payload ≤ MAX_INLINE_BLOB_BYTES` (64 KiB) and `child_manifest ≤ MAX_FORK_PROFILE_BYTES` = 16,384, a new constant this amendment defines. No deploy-time manifest byte cap exists today to reference. Exact-max and cap+1 vectors are pinned for both.

Actor code can catch and branch on `HostError`. Validators must therefore report simultaneous defects in the same normative order. Every rejection path the syscall has appears in this one order (no other text in this CIP establishes precedence; where earlier sections say a check happens "before X", they are restating this order, which governs). First failure wins. After binding conversion, the host-crossing charge precedes
host execution. Within each following step, every required point read or scan
passes through the CIP-43 before-dispatch gate before the value-dependent
validation that needs it; failure to pay returns `OutOfGas` before that read
or validation. Reuse of an already loaded value causes no additional store
operation. Steps 14 and 16 below are bulk-work reservations, not exemptions
from these prerequisite Access charges. Overlapping-defect vectors include
insufficient Access capacity at each prerequisite read/scan.

1. Convert arguments at the binding layer. Range and type failures raise before the host runs under the §3.1 conversion rules.
2. Check `read_only`. If it is set, reject with `Forbidden` (5).
3. Check cross-actor call depth (§3.1). If the limit would be exceeded, reject with `Forbidden` (5), as for `call()`.
4. Check whether `mode` is valid. If invalid, reject with 120.
5. If `payload` is present in full mode, reject with 122.
6. If `payload` exceeds its cap, reject with 123.
7. If `child_manifest` exceeds its cap, reject with 123. `PayloadTooLarge` covers both byte fields, and the error detail names the field.
8. Reject a zero `new_owner` with 121. Wrong length is unrepresentable in `Option<[u8;20]>` and fails at step 1 during binding conversion. A wrong-length vector pins this precedence.
9. Check `exec.fork` and its `max_children` quota, returning existing codes 7 / 8. Check `econ.transfer` presence when `endowment > 0`, returning 7. Quota consumption waits for step 13.
10. In the future fork release, check callback-marker existence. Clean mode without `on_fork_clean` returns 127. This requires the allocated CodeMeta carrier and is inactive in the wallet-identity release.
11. Decode `child_manifest` canonically with no trailing bytes, then validate registry/schema conformance and reject duplicate or unsorted entries with `InvalidInput` (2). Follow the `DeployActor` sequence of decode, `validate_manifest`, then inheritance validation. A subset violation returns 124; a non-inheritable grant returns 125; a `sec.*` retention violation (§3.7.1) returns 125.
12. Take the §3.3.3 storage snapshot and resolve the owner. Malformed nonempty owner width returns `InvalidInput` (2). Compute birth deltas and check both caps, returning 131 / 132.
13. Check parent-side funding when `endowment > 0`. Compare `econ.transfer` `max_amount`/`max_per_block` quotas, returning 8, then sufficiency, returning 107. Mutate quota state only after every check in this step passes. A failed fork never consumes transfer quota. These checks precede address derivation, preserving §3.3.1's guarantee.
14. Reserve the checked aggregate for remaining deterministic copy/write work (§3.8), excluding prerequisite reads/scans already charged.
15. Perform checked increments of `fork_count` AND the parent's `children_count` (§3.4's no-saturation rule). Overflow returns 128. `ForkCountOverflow` covers both counters, and the error detail names the counter.
16. Derive the address and check the current staged state for a wallet marker, returning 28, and an Actor collision, returning 129. In the future coordinated fork release only, perform the §3.2 residue census traversal and per-row purge charges through incremental bulk-work reservation. `OutOfGas` (1) can also arise at any prerequisite Access gate. Stage purge deletes in the fork savepoint after census and charging. A later callback or enclosing-frame fault restores planted rows with all other fork state. A caught-later-failure test and a commit-and-reload test cover this rollback.
17. Check child-side funding after derivation, using the derived address's pre-existing account. Checked addition of `pre-funded + endowment` returns 133 on overflow.

Staging and the callback follow. §3.5 governs callback-time faults. Steps 13 and 17 check parent-side sufficiency before derivation (§3.3.1) and child-side overflow afterward, when the child address is known. Overlapping-defect vectors (single calls violating 3+ rules, including depth+mode, malformed-profile+over-cap, insufficient-funds+collision, and quota-exceeded+prefund-overflow) pin the order.

### 3.2 Child address derivation

The child address MUST be deterministic and collision-free across forks by the same parent:

```
h = keccak256(b"cip27.fork.addr.v1"
                          ‖ parent_address           # 20 bytes
                          ‖ u64_be(fork_count)       # 8 bytes
                          ‖ code_hash)                # frame-entry tuple's hash, 32 bytes
child_address = parent_address[0:2] ‖ h[14:32]
```

Fork addresses use their own derivation function: `child = parent_address[0:2] ‖ keccak256(b"cip27.fork.addr.v1" ‖ parent_address ‖ u64_be(fork_count) ‖ code_hash)[14:32]`, using keccak256, the exact domain bytes shown, the counter as an 8-byte big-endian unsigned integer, checked arithmetic (overflow rejects the fork), pinned by golden vectors. `derive_actor_address` with a special salt cannot serve here, because an inner salt tag would NOT achieve disjointness: `derive_actor_address` hashes any caller-supplied salt into the same `0xff`-prefixed outer preimage, so a `DeployActor` caller could pass the literal fork-salt bytes and occupy the parent's next fork address, permanently wedging the sequence. Only a domain tag in the **outer** preimage (equivalently, a separate derivation) makes the two address spaces structurally disjoint.

The first two address bytes always preserve the parent's address group; fork has no shard override. The remaining 18 hash bytes provide 144 bits of address entropy. The [CIP-6 §6.2 genesis execution rule](https://docs.cowboy.inc/cips/cip-6-sdk.md#62-address-derivation) applies: a group difference alone MUST NOT reject a synchronous call, and ordinary call permissions and resource limits remain in force.

`fork_count` is a new, fork-only counter on the actor record. `DeployActor` increments `children_count` when the deployer holds `exec.spawn`. Reusing that counter would let deploys create gaps in the fork address sequence. `fork_count` advances only on successful fork; `children_count` keeps its existing shared "descendants" semantics and continues to advance on both creation paths (it remains the `max_children` quota basis, covering forks and spawns alike).

Successive forks by one parent receive successive deterministic addresses. The caller supplies no salt, so the Nth fork's address is knowable in advance.

The encoded `Actor` record advances to **version 8**, appending the fixed-width `u64` `fork_count` after `storage_root`. New actors start at zero. Readers accept only the current version and decode no other version with defaults. A subsequent schema amendment, including CIP-4's delinquency field, must use its own coordinated format update. Every rollback the fork participates in restores the pre-fork `fork_count`, including failed-endowment rejection, callback fault, and enclosing-transaction revert. A leaked increment would shift every future fork address.

The other consensus-visible transitions MUST land together at the **future coordinated fork release**, not the wallet-identity release (pre-launch, no activation gate per the reset policy): the reserved receipt/mode key names become birth-only and host-unwritable, code validation begins recording the fork-initializer marker (§3.5.2), the complete bounded residue census/purge below begins running, and **the CIP-29 `subscribe_event` emitter-existence guard ships too**. §3.2's class-B closure depends on it, so a build that carries fork without that guard is invalid exactly as one missing the reserved-key change is. Because networks reset, there is no pre-release actor holding a colliding user-written `__FORK_*` key and no un-marked deployed code to backfill. These rules take effect at genesis.

In the wallet-identity release and the future fork release, `fork()` MUST reject a derived address carrying a **wallet marker** (`WalletAddressConflict`, code 28) or an existing **Actor** record (`AddressCollision`, code 129). Both reads use the current staged state. The marker's key and canonical encoding are fixed in [CIP-4 §§4.2–4.3](https://docs.cowboy.inc/cips/cip-4-storage.md#42-state-prefixes). An existing plain *account* with **no wallet marker** (pre-funded, see §3.3) is not a collision. These collision checks do not activate a residue purge in the wallet-identity release. Consequently, that release does **not** guarantee residue-free birth: the existing mailbox send path can target an unborn address, and the existing full-copy fork path does not clear those destination rows. The no-planted-input invariant below is a requirement of the future coordinated fork release, not a property established by wallet/actor role separation. Implementers must not advertise the future purge guarantee for the wallet-identity release.

The remainder of this section specifies residue census and purge for the future coordinated fork release, including classes A/B, all three census buckets, the write-time guards and their conformance tests. Beyond the account row, the pre-state a fork address may legitimately carry is exactly: the account's balance and nonce, CIP-20 token holdings, and CIP-18 PaymentGate budgets. These are keyed value ledgers any address can accumulate, and all are preserved. **Every other actor-scoped row is planted residue** (fork addresses are publicly computable, so rows can be planted at a future child address by whatever mechanism ever writes them): rejecting planted rows would let an attacker permanently prevent the parent's next fork, so the fork MUST deterministically clear it through a bounded, indexed, metered purge. The purge cannot scan the database. A fork address is publicly computable and several write paths perform no target-existence check, so an attacker can plant state at an unborn child's address. A child must never inherit those inputs. Planted residue splits into **two structurally different classes**, closed two different ways:

(A) The purge can enumerate and clear address-keyed rows. These key on the child's own 20-byte address, so the child's per-address structures enumerate them and a bounded, indexed, metered census clears them at birth (below). Each such class is enumerable from a per-address structure that already exists.

(B) The purge cannot enumerate rows keyed by a hash of the address. A write-time guard prevents their creation before birth. CIP-29 `EventSub`/`EventSubIndex` (`0x18`/`0x19`) key on `keccak256(sub_id)` and `keccak256(emitter‖topic)` over an unbounded topic space, with no per-emitter reverse index, so no census can discover subscriptions planted against the child as a future emitter. A prefix keyed by a *hash of* an address cannot be enumerated as a per-address prefix. CIP-29 therefore requires a write-time guard: **`subscribe_event` MUST reject a not-yet-live `emitter`** (§CIP-29 Risks), so nothing can be subscribed to the child before it exists; a subscription planted pre-birth is impossible, and post-birth subscriptions are ordinary CIP-29 behavior. This class is therefore never present at birth and needs no purge.

The purge (class A) inventory. Every per-address `StatePrefix` (CIP-4 §4.2) falls into exactly one of **three** buckets or the explicitly rejected-before-census class below; the classification is total:

* The purge clears address-keyed runtime state a newborn must not carry, each enumerable from a genuinely per-address structure: (a) storage-trie rows under the address's own trie root (including hashed-mode keys, which the trie enumerates even where prefix scans cannot); the physical address-keyed storage prefixes are `0x03` (`ActorStorage`, keys ≤32 bytes) and `0x22` (`ActorStorageHashed`, keys >32 bytes); (b) CIP-26 library-pin rows (`0x15`); (c) the kv accounting keys `kv_count`/`kv_bytes` (`0x12`/`0x13`); (d) mailbox rows and their head/tail pointers (`0x04`, `0x10`/`0x11`) plus dead-letter ring and tail (`0x1C`/`0x1D`), which attackers can plant because `send_message` does no callee-existence check; (e) actor event-log list (`0x09`); (f) the fairness counter (`0x1B`).
* The purge preserves keyed value ledgers any address legitimately accumulates: account balance/nonce, CIP-20 token holdings, and **CIP-18 PaymentGate budgets** (anyone can validly prefund a predictable future address's budget with real CBY only that address can withdraw, so deleting it would burn custody; CIP-18 needs no amendment).
* The following prefixes cannot contain rows for an unborn address, so the purge has nothing to clear or preserve:

  * **Timers** (`0x05` `keccak256(timer_id)`, index `0x06`, plus per-address `0x1A`/`0x0B`) and **deferred-tx** (`0x07` `keccak256(tx_hash)`, indexes `0x08`/`0x0D`, per-address `0x0C`). Both are hash-keyed *and* writer-gated: a timer schedules only for its own `ctx.actor_address`, and deferred materialization requires the target actor to already exist. Neither is plantable pre-birth, and neither is enumerable from a per-address structure. They are NOT in the cleared bucket because deleting the hash-keyed data rows would strand their index companions.
  * **CIP-14 routes** are FQDN-keyed and have no per-address reverse index.
  * The **CIP-26 `Library` catalog** (`0x14`) is keyed by the *publisher signer* `tx.from`.
  * **CIP-29 `EventSub`/`EventSubIndex` (`0x18`/`0x19`)** are the hash-of-address (class B) prefixes. Their closure is **conditional on the same-release CIP-29 `subscribe_event` emitter-existence guard** (a `Requires:` dependency). Absent that guard these ARE attacker-placeable and this bucket assignment does not hold.

  The **writer-gated** members (timers, deferred, routes, `Library`) share a unifying property that does NOT extend to `0x18`/`0x19`: each is written only by an authenticated signer or by the actor's own execution, and a keyless derived fork address has signed and executed nothing pre-birth, so no attacker and no accident can place a row there. Arbitrary third-party subscribers write `0x18`/`0x19` rows. Preventing those writes before birth depends solely on the CIP-29 guard.
* The host rejects `0x02 Actor` and `0x25 WalletMark` before the census. An Actor record rejects as a collision; a wallet marker rejects as `WalletAddressConflict`. Neither row may be purged, copied from the parent, or turned into a newborn Actor. These are explicit, conformance-checked exceptions to the three residue buckets. A wallet claim is authenticated permanent identity, not third-party planted residue.

The census **domain is precise**: a prefix is in scope iff it is **keyed by an actor address, directly or through a hash of one**. A `keccak256(emitter‖…)` prefix is address-keyed through a hash and IS in scope, which is why `0x18`/`0x19` are bucketed rather than skipped. Prefixes keyed by something else are out of scope by construction and belong to no bucket: `0x0A SystemState` (global `keccak256(key)`), `0x0E PvmPerInstrGas` / `0x16 TxReturnData` (`tx_hash`), `0x0F Code` and the proposed, separately allocated `CodeMeta` (`code_hash`), `0x17 PublishRootDedup` (`be(height)`), `0x1E–0x20` Timer scheduling structures (height/page or singleton), `0x21 CbssPhaseState` (global cadence keys), and `0x24 PendingExpiryCursor` (singleton). Any prefix added after this amendment that IS address-keyed (directly or via a hash) MUST be placed in one of the three buckets with a stated reason; the conformance test enumerates the live prefix table, computes this domain predicate per prefix, and fails on any in-domain prefix assigned to no bucket. It explicitly asserts two exceptions: directly address-keyed `0x02 Actor` and `0x25 WalletMark` reject before the census. The test MUST carry dedicated `0x02 → rejected-pre-census` and `0x25 → rejected-pre-census` assertions, preserve the wallet marker, and prove that no child or fork-counter increment commits on rejection. With those explicit exceptions this release's table passes and a future unclassified address-keyed prefix cannot slip through.

Placement and metering are pinned in the §3.1 order: the census runs immediately after the collision check passes (it needs the derived address; a colliding fork never pays for a purge), each bounded logical iterator advance is precharged to the forker at
CIP-43 `Scan(1)` Accesses (CIP-3 §2.2.1) before any corresponding host read, and each
returned cleared-bucket row is additionally charged as CIP-43 `W(row)` Accesses before it is staged for deletion, in addition to the copy/write aggregate and prerequisite Access gates; exhaustion returns `OutOfGas` before the next operation. The child's post-fork state is thus a pure function of the parent snapshot plus birth writes, never of pre-state beyond the preserved value ledgers. The clear is covered by the fork savepoint and verified by a **commit-and-reload** test (planted residue in every cleared class, including storage, pins, kv, mailbox, events, and fairness, absent after block commit and reload as well as in the overlay), alongside the collision and counter-wedge tests and a subscribe-to-unborn-emitter rejection test (CIP-29 guard).

### 3.3 Copied and uncopied fields

`fork()` is a *copy*, but not every field of the parent's on-chain presence has the same correct copy behavior. The following table is normative; where full and clean mode differ the row says so, and every encoded `Actor` field has a defined per-mode value: `address` (derived, §3.2), `storage_root` (full: the parent's root **plus the deterministic copy-on-write of the receipt, owner, and lifecycle birth writes**, so the final root is a defined function of parent root + those writes, not the parent root verbatim; clean: the root of exactly the seeded slots; both pinned by golden vectors), `manifest` (verbatim, or the fork profile when one is supplied, §3.7.1), transfer/usage counters (fresh, as for a new deploy), rent fields (fresh, as for a new deploy; the child pays rent on the bytes it holds, §3.3.3), `dormant_since_epoch` and `pre_evict_storage_hash` (`None`, both fields, both modes, because a newborn is never dormant or evicted), `fork_count`/`children_count` (0). A conformance test asserts no encoded field falls through implicitly.

| Field / category | Behavior | Notes |
| - | - | - |
| **`code_hash`** | **Inherit** (same) | The child runs the parent's code. Content-addressed; no re-store, no re-validate. |
| **Actor storage (base)** | **Full: subtree-share parent root; Clean: empty** | Full mode's *base* root is `parent.storage_root` (CIP-30 O(1) subtree share, copy-on-write on divergence); clean mode's base is empty. This is the root **before** birth writes — the final `storage_root` is base + the deterministic COW of the birth writes below, per §3.3's opening paragraph and golden vectors, never the parent root verbatim. |
| **`manifest`** | **Effective manifest** | Verbatim **only when the verbatim manifest is inheritance-valid for a new identity** (§3.7.1); otherwise the required fork profile is the manifest, validated as a strict inheritable subset. Non-inheritable grants never cross a fork. See §3.4/§3.7.1 for the per-field rules. |
| **CIP-26 library pins** (`ActorLibPin` table) | **Inherit** | The child has the parent's `code_hash` and therefore the same imports; library pins are part of the binding between code and on-chain libraries and MUST clone with it. |
| **`nonce`** | **Reset to 0** | New identity. |
| **`children_count`**, **`fork_count`** | **Reset to 0** | The child has its own descendants and its own fork sequence, not the parent's. |
| **`parent`** | **Set to forker** | See §3.5. |
| **Owner (`__OWNER__` reserved slot)** | **Birth write, conditional** | Write `new_owner` when supplied (both modes); otherwise write the forking actor in clean mode or when the full-mode snapshot's owner is unset (absent/empty). An omitted-owner full fork with a valid existing 20-byte owner, including the zero-address renunciation marker, preserves it and performs no extra owner write. Resolve the value from the syscall-time snapshot, include any write in birth accounting and gas, and apply it before any callback. |
| **Native CBY balance** | **Pre-existing balance preserved; `endowment` additive** | Balances live in the chain's balance ledger keyed by address, NOT in actor storage. Fork addresses are publicly computable in advance (§3.2), and `transfer_balance` can fund a not-yet-actor address — so the child's account may already hold CBY at fork time. CREATE2-like semantics apply: the pre-existing account balance is **preserved**, and `endowment` adds to it with **checked arithmetic** (overflow rejects the fork). "Starting balance" is therefore `pre-funded + endowment`, not guaranteed zero. On fork abort/rollback the pre-existing account row — balance and nonce — survives untouched: rollback removes the fork's writes, never the account that predated it. Two funding paths, both same-transaction atomic with the fork: (a) `fork(endowment=N)` — debits N from parent, credits N to child as part of the fork itself (§3.3.1); (b) post-fork `runtime.transfer_balance(child, N)` (CIP-6 §12.12) — separate syscall after `fork()` returns. **Cloning** balance would duplicate supply and violate the CBY conservation invariant; both funding paths move CBY between existing balances rather than cloning it. |
| **CIP-20 token holdings** | **Not copied from parent; pre-funded holdings preserved** | Token ledgers are keyed by address, not actor storage: nothing transfers from the parent, but tokens already sent to the (predictable) child address persist, as with CBY above. Supply conservation holds across fork for CBY and every CIP-20 token — fork never mints. |
| **CIP-18 PaymentGate budgets** | **Preserve** | Budgets are prefundable real-CBY custody keyed by address (anyone may deposit to a future address; only that address withdraws) — the third preserved ledger, per §3.2. Payment *authority* (policies the parent configured as a spender elsewhere) is not address-keyed state and does not copy. |
| **CIP-5 pending timers** | **Not copied** | Each scheduled timer's `actor_address` field names the parent; copying the storage view of "I scheduled a timer at H" without copying the scheduler entry would silently desynchronize. Timers stay with the parent; the child schedules its own in `on_fork` if needed. |
| **CIP-14 DNS route registrations** | **Not copied** | Route names are globally unique. The child cannot inherit a name still held by the parent; it MUST register a fresh name in `on_fork` if it wants ingress. |
| **CIP-24 secrets** | **Nothing to copy — not actor storage** | Full fork does not inspect actor storage for secret values: CIP-24 secrets live in **CBSS's own state** (prefix `0x04`, keyed by `SecretId{account, key_hash}`) — never in actor storage — so a fork copies no secret-bearing bytes, wrapped or otherwise. What governs a child's access is CIP-24's own authorization: releases are gated by the manifest's `secrets.*` entitlements (ordinary grants under §3.7.1's inheritance/attenuation rules) and bare-name refs resolve to the **actor's owning account** — a cross-owner child resolves to *its* owner's account, not the parent's. No fork-side storage predicate exists or is needed. |

> Under CIP-23, `sec.tee_required` declares that this actor's handlers must run on a TEE'd runner of class X. The declaration carries no actor-identity-bound credential. The platform verifies a runner's TEE attestation at runner registration time; the actor manifest just expresses the requirement. The field therefore clones verbatim with the rest of the manifest: any TEE'd runner offering the required capability serves the child the same way it served the parent.

`fork()` MUST NOT run the child's `init`. The child starts initialized. Its `on_fork` callback updates identity references (§3.6).

#### 3.3.1 Atomic endowment

When `fork()` is invoked with `endowment > 0`, the runtime MUST:

1. Verify the parent has at least `endowment` wei available. If not, `fork()` MUST fail with `HostError::InsufficientCbyBalance` *before* deriving the child address, staging the child record, or invoking `on_fork`. A failed-endowment fork creates no child and leaves the parent's `children_count` and `fork_count` unchanged.
2. Debit `endowment` from the parent's native CBY balance and credit `endowment` to the child's balance.
3. Stage both balance writes through the **same cross-call write-set machinery** used for the child's actor record and inherited `storage_root` (§3.9). On enclosing-transaction rollback, all five writes (parent debit, child credit, child record, `children_count` bump, `fork_count` bump) MUST reverse together.

The endowment write-set staging requirement is normative because a direct ledger mutation bypassing the write-set leaks balance on revert: a downstream rollback inside the same transaction (`on_fork` faults, parent's handler raises later, gas exhaustion) leaves the parent debited and the child either credited-but-undone or credited-on-an-uncommitted-actor.

`endowment == 0`, the default, performs no debit or credit and incurs no endowment surcharge. Base fork charges, including mandatory lifecycle/receipt writes below, still apply.

An endowment parameter on `fork()` provides these guarantees:

* Some `on_fork` paths need to spend immediately (e.g. `schedule_timer_ex` with `fee_payer = self`). Without atomic endowment, the parent must `fork()` and then `transfer_balance(child, N)` in two syscalls; if `on_fork` runs in between (as required by §3.6) and `on_fork` itself tries to spend, the spend fails because the credit hasn't happened yet. Folding the credit into the fork itself fixes the ordering.
* Insufficient parent balance fails the fork before it creates an underfunded child.
* `CREATE`/`CREATE2` atomically funds a new contract through its `value` field. `fork(endowment=N)` provides the equivalent operation.

The post-fork `transfer_balance` path (CIP-6 §12.12) remains valid for cases where the endowment amount depends on state the parent doesn't know pre-fork (e.g. computed from the child's address).

#### 3.3.2 Clean mode

`fork(mode="clean")` copies the **code binding and nothing else**: `code_hash`, `manifest` (per the §3.3/§3.7 manifest rules), and the CIP-26 library pins. The child starts with empty application storage. It inherits neither a storage-root share nor an owner slot.

A full copy can leak hire ledgers, volume pointers, credential references, or user data if `on_fork` fails to delete a sensitive key. The runtime also copies and charges for those bytes before deletion. Clean mode copies no application state and needs no scrubbing. The §3.3 timer and route exclusions still apply to full mode.

Clean mode creates a fresh actor running the parent's exact code. The child's `code_hash` always equals the parent's, preventing this path from deploying arbitrary code.

In the future coordinated fork release only, "no storage" means no application storage. The runtime atomically seeds the SDK's reserved lifecycle slots as part of fork staging, rolled back with the rest on abort: `__INITIALIZED__` = `0x01` on every child, both modes; `__OWNER__` **when §3.1 requires a birth write** (including a full fork from an unset owner, which defaults to the forking actor; a valid existing full-mode owner, including explicit renunciation, is preserved without an extra write). It additionally stamps the **fork receipt**, one rule for both modes: `__FORK_MODE__` = `0x01` (full) or `0x02` (clean), and `__FORK_PAYLOAD_HASH__` = keccak256 of the bytes actually delivered to the initializer callback. In full mode that payload is the 20-byte parent address, so the slot holds `keccak256(parent_address)`; there is no sentinel value. `__INITIALIZED__` is the single byte `0x01`. In full mode the storage copy may carry the *parent's* receipt slots; staging **overwrites** them with the child's own values. Each child's receipt describes its own birth. These key names were previously unreserved: from the future coordinated fork release the host rejects application writes to them (the wallet-identity release does not reserve these names), and a full-copied parent key with a colliding name is overwritten by the birth write (the child-local value wins).

In that future fork release, the receipt slots are a **distinct, birth-only slot class**, not entries in the existing `RESERVED_STATE_KEYS` list. The raw host accepts `set_reserved_state` / `delete_reserved_state` for every key on that list. Adding receipt keys there would let actor code forge receipts. Birth-only slots are written exactly once, by the fork syscall, and the host rejects any later write or delete from any context; direct raw-host overwrite and deletion attempts carry dedicated tests. Downstream consumers (e.g. CIP-33 spawn verification) treat the payload hash as binding a domain-separated envelope, so one slot suffices for arbitrarily structured commitments. The permission layer admits `init` from any caller while `__INITIALIZED__` is absent under the atomic-deploy bootstrap rule. Without the seeded flag, any caller could re-initialize the child from its first block. The same seeding requirement applies to a full-mode fork taken while the parent's own `init` has not completed.

Requirements:

* In the future fork release only, after CodeMeta allocation, the child's code MUST define an `on_fork_clean` callback (§3.5.1); `fork(mode="clean")` against code without one MUST be rejected before any child is staged. A clean child has no application state and `init` never runs on forks, so `on_fork_clean` is the only initializer. Rejecting an actor without one prevents permanently blank instances.
* The owner slot is written per §3.1 (explicit `new_owner`, else the forking actor) before `on_fork_clean` runs, so owner-gated handlers behave correctly from the first post-fork call.
* **The fork source is the frame-entry code binding**, both modes, as the single deterministic rule. Implementations MUST clone from the frame-entry tuple; dirty-binding rejection is NOT an allowed alternative (two conforming validators choosing differently would fork the chain, not the actor). The captured tuple is `(code_hash, code-bytes reference, manifest, canonical library pins)` frozen at handler entry, and it drives everything derived: the child address (§3.2 uses the tuple's `code_hash`), the child record, the callback code load, and the §3.7.1 inheritance validation. `upgrade_self` mutates all of code, hash, and manifest live, mid-handler, while old code continues executing and the new blob persists only at outer commit; a fork sourced from live fields would select code not currently executing and possibly not yet loadable. `upgrade_self` is additionally forbidden inside `on_fork`/`on_fork_clean` (`ForkInit` context, §3.5.2): a callback upgrade would stage a child pointing at an uncommitted blob and break any downstream code commitment.
* Address derivation (§3.2), `parent` (§3.4), `children_count`, endowment (§3.3.1), entitlement and quota (§3.6), and rollback (§3.9) are identical to full mode. Gas: clean mode charges the fork base costs but no storage-share step.

#### 3.3.3 Storage and rent at fork

The owning specification for actor storage limits and rent is **CIP-4 §12**. There is no per-actor quota and no storage bond. Rent bills the bytes an actor stores, `max(kv_bytes, RENT_MIN_BILLABLE_BYTES) × rent_rate` per rent epoch (CIP-4 §12.1), and every non-reserved actor is held to the protocol-wide `MAX_ACTOR_KV_BYTES` (8 MiB) and `MAX_ACTOR_KV_COUNT` (10,000) limits (CIP-4 §12.4). A full-mode child holds the parent's entire copied set from birth, and those bytes are the child's own rent liability; the CIP-30 O(1) share changes the copy cost, not the liability. Fork moves no value other than the endowment.

The runtime computes full-mode storage accounting in this normative order:

1. At syscall entry, take one atomic snapshot of the parent's storage accounting: `(storage_root, kv_count, kv_bytes)`, using the syscall-time read-your-writes view (the same view the copy takes; this is deliberately the *storage* snapshot, distinct from the §3.3.2 frame-entry *code* tuple, which is captured at handler entry).
2. Apply the deterministic birth-write deltas to the snapshot: `__INITIALIZED__`, `__FORK_MODE__`, `__FORK_PAYLOAD_HASH__` always; `__OWNER__` whenever §3.1 requires a birth write (explicit new owner, clean-mode default, or full-mode unset-owner default; its key/value sizes are fixed and pinned). The deltas are **overwrite-aware**: a birth write whose key exists in the copied set (a full-copied parent's colliding receipt key, §3.3.2) replaces bytes without adding a key. The result is the child's **final** `kv_count` / `kv_bytes` at birth.
3. Final `kv_bytes > MAX_ACTOR_KV_BYTES` rejects with `KvBytesExceedsMax` (131); final `kv_count > MAX_ACTOR_KV_COUNT` rejects with `KvCountExceedsMax` (132). These are the limits the ordinary write path enforces. Both are checked **before staging**, at the §3.1 order's cap step. Neither cap is ever discovered mid-copy as a late `StorageFull`; a host path that bypasses ordinary write checks would never hit one. Cap and cap+1 vectors for both dimensions, including a parent at exactly the key cap whose birth writes are pure overwrites (succeeds) versus one new key (rejects).
4. The child's rent fields start fresh, as for a new deploy: `rent_debt = 0`, `last_settled_epoch` = the current rent epoch, `rate_stamped_atto = 0`. From that epoch the child pays rent on its final `kv_bytes` from its own balance under CIP-4 §12.1–§12.3. A child with no endowment and no pre-funded balance accrues rent debt and is evicted on CIP-4's schedule unless someone funds it. The parent's rent state is unchanged.

Clean mode applies the same caps and rent state to a child that holds only its birth writes; it pays rent on them, never less than the CIP-4 billing floor.

Recursive forks compose under the same rule: each generation's child pays rent on its own copy, so storage amplification is always paid for at the CIP-4 rate by the actor that holds it. Conformance tests: caps at exactly `MAX_ACTOR_KV_BYTES` and one byte over (131), the key-cap overwrite versus new-key pair (132), the child's rent fields at birth, the child's first-epoch rent on its copied bytes, and an unfunded child accruing rent debt.

### 3.4 The `parent` field

The `Actor` record MUST carry a `parent: Address` field. For an actor created by `fork()`, `parent` is the forking actor. For an actor created by an **actor-origin `DeployActor`** (an `exec.spawn`-entitled actor deploying fresh code), `parent` is likewise the deploying actor. This amendment replaces the current implementation's `Address::ZERO` value: `children_count` already counts such deploys as descendants, and a lineage field that skips one creation path is not a lineage field. For genesis actors and actors deployed by an externally-owned account, `parent` is the zero address (`Address::ZERO`), meaning "no parent." `children_count` advances by **checked** increment on every creation path. At `u64::MAX` the creation rejects (no saturation; a saturated counter silently aliases descendants).

A `Piece` forked by a `Piece` has that `Piece` as its parent even if a `City` originally deployed the lineage.

Cowboy has no in-protocol actor delete, so the `parent` pointer is always resolvable. CIP-31 storage rent MAY drive an actor into a *dormant* / evicted state; an evicted parent's address remains valid and continues to be the child's `parent`. Implementations MUST NOT re-parent a child whose parent is evicted (no Unix-style "re-parent to init"); the lineage record is permanent.

Adding `parent` is a state-format change; implementations MUST bump the actor codec version and treat the field as present-and-zero for all pre-existing actors.

### 3.5 The `on_fork` callback

The copied storage can still refer to the parent's identity and peers. The runtime invokes the child's `on_fork` callback to update those references:

```python theme={"system"}
@fork_initializer
def on_fork(self, payload):
    parent_addr = payload          # the forking actor's address
    # fix up self-referential state: identity, role, peer links,
    # re-register routes (CIP-14), re-schedule timers (CIP-5), etc.
```

* `on_fork` runs as a nested `call()` from the `fork()` syscall. It counts against the call-depth limit (§3.1) and shares the fork's gas budget. It is **not** a CIP-29 hook (no isolated billing, no `MAX_EVENT_DEPTH`); the word "callback" is preferred over "hook" to avoid that confusion.
* `on_fork` MUST be obeyed strictly under CIP-6's determinism rules (§3.9). A non-deterministic `on_fork` would fork the chain, not the actor.
* A fault in a **present** `on_fork` MUST abort the fork entirely: the implementation rolls back all staged state, including the child record, storage copy, lib pins, endowment and `children_count`, and every callback effect. The state overlay's savepoints deliberately exclude the append-only effect logs in all six classes: events, outgoing messages, timer schedules, timer cancellations, timer extensions, and deferred-tx requests. A bare state rollback therefore leaves effects from a child that never existed; and because the failed fork does not advance `fork_count`, a later successful fork reuses the same deterministic address and inherits the leaked timer or message. The fork syscall therefore marks all six effect logs at entry and truncates them to the marks on callback fault. Fork-local marks are **not sufficient on their own**: a callback that *succeeds* inside a nested frame that later rolls back (A calls B; B forks C, whose initializer emits effects; B then faults; A catches) leaves the same leak with no fork-local trigger. The general rule is therefore normative: **every nested-frame savepoint covers all six effect logs**. Each cross-call frame marks the logs at entry and truncates to its marks on that frame's rollback, making effects transactional with the state they were emitted alongside at every level; the fork-entry marks become one instance of the general rule. This amendment requires new behavior, which no current test implements. It requires one test per effect class for the callback-fault case and one per class for the successful-callback-then-enclosing-fault case. (An **absent** `on_fork` skips the callback and the fork continues.) The abort-on-fault rule matches the current reference implementation and its property tests. A fault never falls back to the copied state: silent fallback returns a bare success and can hand a new owner an un-fixed snapshot after the author explicitly supplied a fixup callback.

`on_fork` is opt-in. Omitting it asserts the state is safe to copy byte for byte. The explicit decorator makes authors decide this, given the secrets concerns in §7.

#### 3.5.1 The `on_fork_clean` callback

Clean-mode children are initialized by a distinct callback:

```python theme={"system"}
@fork_initializer
def on_fork_clean(self, payload):
    # payload = the bytes the forker passed to fork(payload=...);
    # the forking parent is self.sender — the callback runs as a
    # nested call from the parent, so no separate parent argument is needed.
    ...
```

`on_fork_clean` receives the forker-supplied `payload` (§3.1). The callback's sender identifies the parent. It is REQUIRED for clean-forkable code (§3.3.2) and runs under the same nested-call, determinism, gas, and fault-aborts-the-fork rules as `on_fork` (§3.5). The fault rule is uniform across modes: a present initializer that faults aborts the fork; the modes differ only in whether the callback may be absent (full: yes, the state was copied; clean: no, §3.3.2).

#### 3.5.2 Fork callbacks are not public entry points

`on_fork` and `on_fork_clean` MUST be invocable **only through the `fork()` syscall**. Without this rule, any caller could re-run a child's identity fixup after the fork by re-registering routes, re-scheduling timers, or (clean mode) re-initializing a live instance over its state.

The centralized handler dispatcher checks the invocation kind. A name filter inside `call_actor` would reject the fork syscall's legitimate callback, which uses the ordinary cross-call path. Top-level transactions, mailbox deliveries, and event routes could bypass that filter because they do not all pass through `call_actor`. The fork syscall marks its callback invocation with `ForkInit`, a one-shot capability bound to the exact `{parent, child, mode, method}` tuple and consumed on delivery. Nested calls made inside the callback reset to `Normal` kind and can neither re-enter the reserved entrypoints nor evade the `ForkInit` `upgrade_self` ban by indirection. The **parent** remains non-reentrant for the callback's duration under the existing suspended-actor rule (it is mid-call, like any cross-call sender); the initializing-actor guard below protects the child. The suspended-actor set alone does not cover the child. The dispatcher rejects the reserved names arriving under any other kind.

The host decides callback existence from deploy-time metadata, never by attempting execution: code validation records which reserved callbacks the code defines. The proposed marker requires a dedicated **consensus carrier** (code state today is exactly `StatePrefix::Code` with a `StateValue::Code(Vec<u8>)` value, which offers no side-channel): a proposed new state prefix `StatePrefix::CodeMeta` with `StateValue::CodeMeta(u8)`. Its prefix and value tag MUST be assigned together by a coordinated schema amendment before this callback proposal ships; the earlier draft assignments `0x1E` and `0x12` are invalid because the current release uses them for `TimerIndexPage` and `TimerIndexMeta`, respectively (CIP-4 §§4.2–4.3). The wallet-identity amendment allocates only WalletMark and does not activate this proposed carrier. Its key uses the 32-byte `code_hash` verbatim in the 86-byte state-key format, with zero padding; its value is the one-byte bitset (`bit 0 = on_fork`, `bit 1 = on_fork_clean`; remaining bits MUST be zero and a set reserved bit rejects at decode, so future bits require an explicit change). It is written atomically with its code record wherever one is created (`DeployActor`, `UpgradeActor`, `upgrade_self`), exists exactly as long as the code does, and the fork syscall reads it via the **frame-entry** `code_hash` (§3.3.2's tuple), never a live field. State-sync and light-client paths carry the new prefix like any other (it is ordinary keyed state; the blast radius is the state-codec enum itself, re-pinned with the release). Creation is **idempotent per code\_hash** and covers every Code producer: `DeployActor`, `UpgradeActor`, `upgrade_self`, and `PublishLibrary` (which creates shared Code rows too). The bitset is the same pure function of the code bytes on every producer, explicitly including `PublishLibrary` (library code passes ordinary actor validation and MAY define the callbacks; a producer-dependent marker would make the value depend on whether publish or deploy touched the hash first, making consensus state depend on creation order). Publish-first/deploy-first vectors pin the equality. Dedup of Code blobs, so writing an identical marker over an existing one is a no-op, and a *conflicting* marker for an existing hash is unreachable (the marker is a pure function of the code bytes). Golden vectors: marker bytes for code with neither/either/both callbacks, reserved-bit rejection, idempotent re-create, and recomputation on each creation path. Thus `fork(mode="clean")` checks clean-forkability without staging anything. A present callback whose body happens to raise a not-found-shaped error is never misclassified as an absent handler. (The current reference implementation matches on the fault message and must switch to the marker.)

The SDK marks these handlers with a dedicated fork-initializer marker. They must not be declared `@public`. Permission decorators do not apply to them (the dispatcher's kind check replaces that layer), and the marker **implies DEFERRED handler mode**: the SDK's default is PURE, which would forbid exactly the message/timer/deferred effects §3.5 names as the callback's legitimate work; no separate `@deferred` stacking is needed or permitted.

While the callback runs, the child is an **initializing actor**. Self-calls bypass the existing suspended-actor set. An explicit initializing-actor guard therefore rejects every path into the child until the callback returns: direct self-call, self-event delivery, a callback-initiated chain re-entering the child through a third actor, mailbox delivery, replay of the reserved entrypoints, nested `upgrade_self` (§3.3.2's ban), and owner-gated dispatch. The `ForkInit` capability is consumed on delivery and does not propagate to nested frames, which reset to `Normal`. Decorating `on_fork` with `@callable_by(SELF)` denies the callback because its sender is the parent. `SELF` never matches. Use the fork-initializer marker.

### 3.6 Entitlement and quota

`fork()` is an actor-creating effect and MUST be gated by a dedicated entitlement:

* `exec.fork` is a new entitlement registered by this amendment (the registry at `docs/architecture/entitlements/entitlements-specification.mdx` lists `exec.spawn` with `max_children` and states "any entitlement not listed here is invalid"; that registry gains `exec.fork` with `max_children` in the same release, or `fork()` is unauthorizable). Read from the **frame-entry manifest** (the §3.3.2 fork-source tuple), not the live `ctx` manifest, so a same-handler `upgrade_self` cannot change whether the in-progress fork is authorized. Declared in the forking actor's manifest, covering both modes: full copy and clean (§3.3.2) are the same trust boundary of instantiating self-code. They differ only in the state they copy, so one grant governs both. Distinct from `exec.spawn` (which gates fresh-code `DeployActor`). The two have different cost profiles (`fork()` does no code validation; spawn does no storage copy) and different operational properties (fork is self-only; spawn can be against arbitrary code), so operators commonly want to grant cloning without granting arbitrary deployment.
* `max_children` is the quota carried on the `exec.fork` grant. `fork()` MUST be rejected once the parent's `children_count` reaches it. A successful `fork()` MUST increment the parent's `children_count`.
* `econ.transfer` is additionally required when `endowment > 0`; the endowment consumes the grant's `max_amount`/`max_per_block` quotas. A value-free fork (`endowment = 0`) does NOT require it. A code-cloning grant need not imply a balance-spending grant.

`exec.fork`, `exec.spawn` and `econ.transfer` are in the default entitlement set that every actor holds; a manifest grant for one of them adds its quotas.

### 3.7 Manifest cloning details

The manifest clones verbatim (§3.3), but a handful of manifest-bound capabilities have specific clone behaviors documented above:

* The child inherits `sec.tee_required` (CIP-23), a coarse capability requirement with no actor-identity binding.
* **CIP-14 ingress routes** declared on the manifest: clone the *entitlement* (the right to register a route), not any registered name. The child has the right but starts with no registered routes.

The child inherits declarations of what it can do. Registrations of names, sealed material, attestation tokens, and other runtime state reset.

#### 3.7.1 The fork inheritance boundary

A fork creates a new actor identity. Capability inheritance rules apply at that boundary regardless of mutable ownership. An owner-equality exemption would let a parent fork with the same `new_owner`, copy `sys.upgrade`/`econ.transfer`, then call `transfer_ownership` to hand those capabilities to anyone. Transfer does not revalidate inheritance, so the recipient would gain capabilities forbidden on an ordinary child deploy. The same risk applies when clean mode defaults the owner to the forker. `validate_inheritance` therefore takes no owner parameter.

Every fork, in either mode and with any owner, validates the child's effective manifest under the same inheritance rules as a child deploy. Non-inheritable grants never cross a fork. When the parent's verbatim manifest carries any non-inheritable grant, the fork MUST supply a fork profile through `child_manifest`. The runtime validates it as a strict subset of the parent's manifest restricted to inheritable grants. Any violation rejects the profile; the runtime cannot strip invalid grants and continue. A fork without a profile is valid only when the verbatim manifest passes. Downstream executable commitments hash the child's effective manifest after profile application.

Manifest profiles may drop or narrow authority grants such as `exec.*`, `econ.*`, and quota-bearing entitlements. They cannot widen those grants. Security constraints are entitlement IDs under the exact dotted prefix `sec.`. The dot is part of the normative `starts_with("sec.")` check: `sec.tee_required` and `sec.data_residency` match; unrelated IDs that merely begin with "sec" do not. CIP-24's `secrets.read` / `secrets.verify` are authority grants and attenuate under the grant rules. In both fork modes, profiles cannot drop or weaken security constraints. In v1, the child's effective manifest MUST carry every parent `sec.*` entry with identical key and value bytes. The validator treats TEE class strings and residency codes as opaque, so it cannot determine whether a different value is stricter. A per-constraint ordering registry remains future work. The runtime rejects a profile that omits or alters a `sec.*` entry. The current `validate_inheritance` iterates only child entries and would miss an omitted `sec.tee_required`, allowing a full copy of sensitive state to run without its TEE constraint. Validation must therefore iterate child entries to check grant attenuation and parent `sec.*` entries to check constraint retention. Clean mode keeps the same constraints because they apply to the code, which is unchanged. Any clean-mode relaxation would require a future amendment with an explicit per-constraint safety matrix. Conformance tests cover a profile omitting `sec.tee_required`, one altering `sec.data_residency`'s value bytes, which v1 equality rejects even if claimed to be stricter, and one carrying every `sec.*` entry byte for byte, which is accepted. Tests cover both modes.

The inheritance rules have these consequences:

* A spawning template carries `exec.fork`. Its profile determines whether children may fork recursively. Hired instances normally drop that grant, disabling recursive instantiation by default.
* A swarm parent cannot pass non-inheritable grants to workers, even under the same owner. The parent retains `econ.transfer` and funds children through endowments and transfers. Allowing children to inherit those capabilities would require a new `fork_inheritable` registry flag and ownership-transfer revalidation in a future amendment.

### 3.8 Gas

`fork()` MUST be metered in Cycles, Cells and Accesses per CIP-3 §2.2 and CIP-43:

* A base cost equal to `actor_deploy_base_cycles` / `actor_deploy_base_cells` for the new actor-record write.
* No per-code-byte cost applies because the fork supplies and stores no code.
* Once the CIP-30 subtree share is implemented, the storage copy is O(1) and costs only the constant-time root-pointer write. The current implementations (origin and CIP-30's own present state) still **physically enumerate**, and the interim rule is normative, not MAY: the enumeration path MUST **precharge one checked aggregate** from the §3.3.3 step-1 **syscall-time read-your-writes snapshot**, the exact image used for copying, caps, and birth accounting, so same-handler writes made before the fork are priced with everything else; charging from the *committed* counters would let the copy scan more than it priced and put unmetered work ahead of an OOG. The aggregate covers copied key/value bytes as Cells and the canonical
  CIP-43 `Copy(n)` Access reservation for the syscall-time row count; it does not
  add the removed `n × 200` storage-write Cycle charge. Copied keys are warmed by
  `Copy(n)` and MUST NOT also charge `W`. The same checked aggregate includes
  every deterministic non-residue charge of this section (actor-record base, birth
  slots, payload, profile, pin rows and endowment legs) and is reserved at
  step 14, excluding prerequisite reads/scans already charged through their gates.
  The full CIP-43 row remains in force: the actual host crossing, gated `R` point
  reads, fixed-bound `Scan(MAX_LIBS_PER_ACTOR)` for physical pin scans, and callback
  `NestedFrame`/first-nested setup charges are required. Already metered frame-entry
  pin snapshots may be reused without a second scan. These are the same charges
  decomposed by CIP-3, not an additional copy of the base row.
* The `on_fork` callback is metered as an ordinary nested call within the `fork()` budget.
* When `endowment > 0`, the two ledger writes (parent debit, child credit) MUST charge their persisted bytes as Cells and `W` Accesses under the cold/warm rules, with no structural Cycle surcharge. `endowment == 0` MUST NOT incur this endowment surcharge.
* The child's storage-accounting initialization (`kv_count`, `kv_bytes`) and rent fields are part of the base actor-record write, not separately metered.
* The birth writes are charged at the ordinary reserved-slot `state_set` schedule, both modes: `__INITIALIZED__`, `__FORK_MODE__`, `__FORK_PAYLOAD_HASH__` always; `__OWNER__` **only when it is written** (§3.3's conditional rule, where an omitted-owner full fork skips the owner write only when the snapshot already contains a valid 20-byte owner value, including explicit renunciation; an unset-owner default pays the ordinary owner-slot Cells and `W` Access charge, with no blob-commit Cycle term).
* `payload` (clean mode) is charged `payload.len()` Cells at the inline-blob rate; a supplied `child_manifest` is charged `child_manifest.len()` Cells at the same inline-blob rate (there is no separate deploy manifest rate to reference; the profile is capped at `MAX_FORK_PROFILE_BYTES`, §3.1). The child's inherited CIP-26 library-pin rows are charged `pin_count × LIB_PIN_OVERHEAD_CELLS (64)` Cells and no Cycles (pin writes are access-metered, CIP-43), per CIP-26's canonical pin row, not generic `state_set`; the pin table is per-actor state and its copy is real writes, not covered by the CIP-30 root share.
* The §3.2 residue census precharges CIP-43 `Scan(1)` Accesses before
  each bounded logical iterator advance, including the terminal/empty probe
  for each cleared-class cursor. The fixed cursor order follows §3.2's cleared
  inventory and rows use canonical key order. Every returned row is then
  charged separately as CIP-43 `W(row)` before staging deletion (order step 16).
  No uncharged whole-prefix scan, eager collection or hidden unbounded iterator
  advance is allowed. Budget exhaustion stops before the next read or delete
  and rolls back the fork savepoint. Charge logical operations identically
  regardless of database cache state; physical backend node visits do not alter
  consensus gas. A residue-free fork pays the bounded empty-probe Access costs but no
  deletion charge. Read-side returned key/value bytes additionally use CIP-43
  §6 bandwidth Cycles; deletion adds no structural Cycle surcharge. Conformance vectors MUST cover empty cursors, many tiny rows,
  and exhaustion before a traversal step and before a deletion.
* **CIP-3 §2.2.1 owns the complete fork schedule**, using CIP-43 for structural Accesses, for this coordinated implementation release: its table decomposes the CIP-43 base row and includes every conditional line above, including birth slots, payload, profile bytes, pin rows and endowment legs, plus the additional variable residue-census/deletion charges, with total-cost and OOG vectors. CIP-3 joins this CIP's coordinated release set.
* One fork savepoint covers the full staging, and every abort path restores all of it: the child `Actor` record, effective manifest, storage root (base + birth writes), lifecycle and receipt slots, library pins, both counters (`fork_count`, `children_count`), both balance legs of any endowment, the child's storage-accounting writes, the staged residue-purge deletes, the parent's `transfer_block`/`transfer_block_amount` consumption whenever an endowment consumed `econ.transfer` quota, and the six effect-log marks of §3.5. No field of §3.3's table is exempt.

### 3.9 Determinism and rollback

Every validator replaying the transaction MUST produce the identical child: identical address, identical inherited `storage_root`, identical `on_fork` outcome. Determinism holds because the address derivation, the state-root share, and `on_fork` are all deterministic functions of committed state and the PVM's deterministic execution mode (CIP-6 §17, which prohibits wall-clock time, unseeded randomness, and FPU use). `on_fork` runs under these same rules.

`fork()` MUST be transactional. If the enclosing transaction reverts after a `fork()`, the child MUST cease to exist, the parent's `children_count` increment MUST be undone, and (when `endowment > 0`) both the parent's debit and the child's credit MUST be undone, leaving the parent's pre-fork balance intact. A conformant implementation stages the full §3.8 rollback set, including the child record, effective manifest, storage root (base + birth writes), lifecycle/receipt slots, library pins, both counters, both endowment balance legs, the storage-accounting writes, the staged residue-purge deletes, the parent's `transfer_block`/`transfer_block_amount` quota consumption, and the six effect-log marks, in the fork savepoint, so an ordinary transaction rollback discards all of it with no bespoke undo path. Direct ledger mutations for the endowment that bypass the write-set are non-conformant; see §3.3.1.

## 4. Rationale

### 4.1 Why self-clone only

Restricting `fork()` to the caller makes the caller the child's parent and removes the need to authorize cloning a third party. Use `DeployActor` with another actor's `code_hash` to clone that actor.

### 4.2 Eternal-with-rent: fork as birth

Cowboy has no in-protocol actor deletion operation. CIP-31 introduces per-byte-per-epoch storage rent and eviction into a dormant state (CIP-4 §12.3). An evicted actor's record persists and remains addressable. `fork()` adds an actor to that population, with these consequences:

* No orphan / re-parent. The `parent` pointer is permanent; an evicted parent is still the child's parent.
* No `wait()`, no zombies, no exit status, no `SIGCHLD`. `fork()` is pure addition.
* `children_count` only ever increments.

Two bounds limit actor creation and retention:

1. `exec.fork` + `max_children` (§3.6) bounds the rate of fork by gating creation per actor.
2. CIP-31 storage rent bounds the steady-state population. An actor that does not pay rent eventually evicts. Maintaining forked actors costs rent.

Reviewers MUST consider a manifest granting `exec.fork` without `max_children` unbounded. CIP-31 rent is the second limit, not the first.

### 4.3 Why synchronous

Synchronous `fork()` returns a child address the parent can use within the handler. The parent can call the child, store its address, or pass it to a peer. Transactional rollback (§3.9) covers synchronous creation.

## 5. Reference implementation

> The address-group release implements the distinct derivation, checked fork-only counter, frame-entry code/manifest binding, Actor v9 encoding and the physical-copy funding guard described below. Modes, `new_owner`, fork profiles, birth-only receipt slots, `ForkInit` one-shot semantics, deploy-time callback markers and the complete birth/residue schedule remain the subsequent full amendment. The current release still uses full-copy fork and `on_fork` via `call_actor`; this release does not claim to implement every requirement above.

The storage-copy path physically walks both of the parent's address-keyed ranges: `StatePrefix::ActorStorage` (`0x03`, verbatim keys ≤64 bytes) and `StatePrefix::ActorStorageHashed` (`0x22`, hashed keys >64 bytes). It copies rows by slot, including long keys that user-key scans cannot enumerate. CIP-30 requires O(1) subtree sharing; that remains implementation work.

For this physical-copy prototype, the metered committed KV-byte counter is read first and that many Cells are charged before the range walk. Pending overwrites and deletes then determine the child image; if it grows, the additional Cells are charged before cloning the pending values. A shrink does not refund the already performed read. Thus the copy charge is `max(committed KV bytes, final child KV bytes)`, in addition to the fork base and ordinary metered point-read/Copy accesses. Insufficient budget stops before the corresponding copy work, and no child or counter increment is staged. The future full-amendment schedule in §3.8 remains distinct from this prototype guard.

## 5.1 Acceptance criteria

These criteria gate the **future coordinated fork release**. They do not assert
that birth-only slots, residue purging, clean mode or CodeMeta are enforced by
the wallet-identity release. Its current implementation scope is the §5 status
paragraph and the staged collision guard specified above.

* Golden vectors: child address derivation (domain bytes, u64\_be count), and golden `Actor` record bytes + `storage_root` per mode (clean root = exactly the seeded lifecycle + receipt slots).
* Raw-host overwrite and delete attempts against `__FORK_MODE__` / `__FORK_PAYLOAD_HASH__` rejected from every context, including `set_reserved_state`.
* A present callback whose body raises a not-found-shaped fault aborts the fork; it is not classified as an absent handler (deploy-time marker, not string matching).
* All six effect classes (event, message, schedule, cancel, extend, deferred) truncated on callback fault, one test each; the failed fork's address receives no leaked effect on successful retry.
* `upgrade_self` inside `ForkInit` rejected, including via a nested call from the callback; fork after same-handler `upgrade_self` clones the frame-entry tuple.
* Fork (either mode, same or different owner) with a non-inheritable grant in the verbatim manifest and no fork profile rejected; profile validated as strict inheritable subset; effective manifest hash matches the profile; `transfer_ownership` of a forked child conveys no additional grants.
* Failed endowment, callback fault, and enclosing-transaction rollback each restore the pre-fork `fork_count`; a successful retry derives the same next address.
* Checked overflow: `fork_count`, `pre-funded + endowment`; pre-existing account row (balance, nonce) survives fork rollback.
* `DeployActor` with the literal fork-salt bytes does NOT collide with any fork address (distinct derivation).
* Golden `Actor` codec bytes for v9; other versions are rejected; `fork_count` follows `storage_root`.
* §3.3.3 storage and rent: caps at exactly `MAX_ACTOR_KV_BYTES` / `MAX_ACTOR_KV_COUNT` succeed and one over rejects (131 / 132); the child's rent fields are fresh at birth and its first rent epoch bills its copied bytes; an unfunded child accrues rent debt; no fork path debits the parent except the endowment.
* §3.7.1 polarity: profile omitting or altering a parent `sec.*` entry rejected in both modes (v1 byte-exact equality); identical entries accepted; grant attenuation still validated as subset.
* All six effect classes truncated when a successful callback's enclosing frame later faults and is caught above (§3.5's general nested-savepoint rule), one test per class, in addition to the callback-fault six.
* Planted residue in **all six** §3.2 cleared classes, including the storage row, pin row, kv counters, mailbox row + head/tail and dead-letter pointers (the confirmed plantable class), event-log row, and fairness counter, at a future fork address is cleared: absent after block commit and reload, not merely hidden in the overlay; account balance/nonce, token holdings, and PaymentGate budgets all survive intact.
* Enumeration path precharges from the §3.3.3 step-1 syscall-time RYW snapshot counters (same-handler pre-fork writes included in the price): an OOG fork performs no unmetered scan work and charges exactly the precharge.
* Actor-origin `DeployActor` sets `parent` to the deploying actor; `children_count` at `u64::MAX` rejects creation (checked, not saturating).
* Callback marker recomputed identically at every code-record creation (`DeployActor`, `UpgradeActor`, `upgrade_self`, `PublishLibrary`, with byte-equal results for publish-first and deploy-first) and read via the frame-entry `code_hash`; fork after same-handler `upgrade_self` consults the entry code's marker, not the live code's.
* §3.1 validation order pinned by overlapping-defect vectors (single calls violating three or more rules report the lowest-numbered check).

## 6. Open questions

* The `max_children` parameter bounds fork creation through `exec.fork`. A future amendment could also cap the storage bytes an actor may copy at fork time.
* §3.5 passes only the parent's address to `on_fork`. Passing the child's address or a structured context remains an open question. The callback can already query `runtime.get_actor_address()` for its address.

## 7. Security considerations

* Per §4.2, `exec.fork` + `max_children` bounds the rate; CIP-31 rent bounds the steady-state population. Unbounded spawn grants MUST be flagged in manifest review.
* Storage copy costs O(1) once the CIP-30 subtree share is implemented. Until then, enumeration prices every copied byte up front under §3.8's precharge rule.
* A full-mode fork copies *most* of the parent's storage (the §3.3 exceptions excluded). Authors of forkable actors MUST treat copied storage as carrying every application secret the parent held (CIP-24-managed secrets are not in actor storage and do not copy, as stated in the §3.3 row). The `on_fork` callback can re-key, re-tag, or scrub per-identity material. Scrubbing uses a deny-list and fails open. When the child is destined for a different principal (instance spawning, store hires), use clean mode (§3.3.2), which fails closed: no state crosses. Full-mode-with-scrub is appropriate only when parent and child stay under one operator.
* Every required owner birth write completes before any callback. Clean children and full children of never-owned parents default to the forking actor; a full copy preserves a valid owner or the explicit zero-address renunciation marker. No default owner-resolution path leaves an unset owner for an external first caller to claim. Implementations MUST NOT move an owner write after `on_fork`/`on_fork_clean`. Required vectors cover absent and empty parent slots, a normal owner, explicit renunciation, an explicit `new_owner`, malformed nonempty width, callback-time owner visibility, and owner-default birth deltas at the key/byte caps. This requires a coordinated host change; an SDK-only check does not satisfy it.
* Without §3.5.2's dispatch reservation, callers could invoke `on_fork_clean` to re-initialize a clean-forked instance or invoke `on_fork` again on a full fork. Reviewers SHOULD verify that the dispatch layer rejects external invocation of the reserved names. Example usage alone cannot establish this.
* §3.2's derivation includes `parent.code_hash`. A future actor code-upgrade mechanism that mutates `code_hash` SHOULD be aware that subsequent fork addresses by the same parent will then derive from a different `code_hash` than the actor's prior forks. The deterministic sequence stays internally consistent and changes across an upgrade. If pre-upgrade addresses must remain enumerable post-upgrade, the upgrade mechanism MUST commit the `code_hash` sequence used at each fork.
* `on_fork` is arbitrary actor code and runs under the PVM's deterministic mode (CIP-6 §17). A non-deterministic `on_fork` causes validators to disagree on chain state.
* §3.3.1 requires the endowment debit/credit to flow through the same write-set machinery as the rest of the fork. A non-conformant implementation that mutates account balances directly will silently leak CBY on any tx-revert path (failed `on_fork`, post-fork exception in the parent, gas exhaustion later in the same tx). The parent stays debited and the child either never materializes or materializes with a balance that the next block's account scan still credits. Reviewers SHOULD check this path explicitly in any `fork_actor` implementation: a deliberate `on_fork` panic in a property test, followed by a balance-conservation assertion across the failing tx, is the cheapest test.


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