---
title: "Mutation hooks, exception kinds, tree version, Release"
url: https://recursiveai.org/onehtml/docs/mutation-hooks/
description: "Four parts of the mutable working layer (RecursiveAI.OneHtml.Mutation, see mutable-document.md) for a caller that binds the layer to the DOM from a script…"
version: "1.8.0"
source: https://github.com/recursive-ai-oss/onehtml-csharp/blob/9213d47aed47f691bf05853759fd8e328a6a980e/docs/mutation-hooks.md
---

# Mutation hooks, exception kinds, tree version, Release

Four parts of the mutable working layer (`RecursiveAI.OneHtml.Mutation`, see `mutable-document.md`) for a caller that binds the layer to the DOM from a script runtime or a UI toolkit: the exception kind of every failure, synchronous hooks at the DOM Standard's mutation steps, a cheap tree-version counter, and the guarantee about `Release`. The MutationObserver is in `mutation-observer.md`.

## 1. Exception kinds and the order of checks

`DomException.Kind` is a `DomExceptionKind`; `DomException.Name` is the DOM Standard's exception name. Every name of the DOM Standard that the layer can need has a kind of the same name: `HierarchyRequestError`, `NotFoundError`, `InvalidCharacterError`, `WrongDocumentError` (the first four are the same values as the older `HierarchyRequest`, `NotFound`, `InvalidCharacter`, `WrongDocument`, which keep their names and numbers), `IndexSizeError`, `SyntaxError`, `NamespaceError`, `InvalidStateError`, `NotSupportedError`, `InUseAttributeError`, `InvalidNodeTypeError`, `NotAllowedError`. `TypeError` is the WebIDL type error (an invalid `MutationObserverInit`). `StaleNode` and `LimitExceeded` are not DOM exceptions: a handle that outlived its node, and a configured limit.

`InvalidStateError`, `InvalidNodeTypeError` and `NotAllowedError` are **reserved**: no operation throws them yet. They are in the enum so a binding can map every DOM name now. `NamespaceError` (validate and extract), `InUseAttributeError` (attribute nodes) and `NotSupportedError` (cloning a shadow root, adopting a document, CDATA in an HTML document) are thrown. A host can also throw any kind itself: `new DomException(kind, message)` is public.

### Order inside one call

1. **Argument checks**, in argument order, before anything is read from the tree: a null reference is `ArgumentNullException` (a null node handle is `ArgumentException`); a handle of another document is `WrongDocumentError`; a released handle is `StaleNode`. For the *child* or *reference child* argument of `InsertBefore`, `ReplaceChild` and `RemoveChild` a handle of another document is `NotFoundError` instead, because such a node is simply not a child of anything here (DOM 4.2.3 pre-remove, pre-insert step 3). A node to insert that belongs to another document is adopted after the pre-insertion checks (`dom-node-model.md` section 6); `WrongDocumentError` remains for the other calls that name a node of another document (`SerializeNode`, `Release`, and so on).
2. If a mutation observer is registered: `LimitExceeded` when `MaxQueuedMutationRecords` records are waiting (nothing changes).
3. **Ensure pre-insertion validity** (DOM 4.2.3), in the spec's order, for `AppendChild`, `PrependChild`, `InsertBefore` and `InsertAdjacentHtml`; `ReplaceChild` runs steps 1 and 2 first, then its own child check, then 4 to 6:
   1. the parent is not a document, document fragment or element: `HierarchyRequestError`;
   2. the node is a host-including inclusive ancestor of the parent: `HierarchyRequestError`;
   3. the child is not a child of the parent (`ReplaceChild`: the replaced child): `NotFoundError`;
   4. the node is a document: `HierarchyRequestError` (a document node cannot be a child);
   5. a text node into a document, or a doctype into a non-document: `HierarchyRequestError`;
   6. the document-specific rules (one element, doctype before the element, no text in a fragment going into a document): `HierarchyRequestError`.
4. Limits: `MaxDepth`, `MaxNodes`, `MaxValueLength` and the others: `LimitExceeded`. A failed call changes nothing.

| Operation | Throws, in order |
|---|---|
| `AppendChild`, `PrependChild`, `InsertBefore` | argument checks; pre-insertion validity 1–6; limits |
| `ReplaceChild` | argument checks; steps 1, 2; `NotFoundError` (old child not a child); steps 4–6; limits. A child replaced by itself is allowed. |
| `RemoveChild` | argument checks (foreign child: `NotFoundError`); `NotFoundError` if the node's parent is not this node |
| `Remove` | `StaleNode` only; no parent is not an error |
| `ReplaceChildren` | argument checks for every node; parent not an element or fragment: `HierarchyRequestError`; a document or doctype node, or an ancestor: `HierarchyRequestError`; limits. Nothing changes when one fails. |
| `SetTextContent` | `LimitExceeded` |
| `SetInnerHtml`, `InsertAdjacentHtml` | not an element, or `BeforeBegin`/`AfterEnd` with no element parent: `HierarchyRequestError` (the DOM uses `NoModificationAllowedError` for the second; not in the kind list); the markup limits (`HtmlLimitExceededException`); then as `ReplaceChildren` / insertion |
| `SetAttribute`, `SetAttribute(ns, …)` | not an element: `HierarchyRequestError`; invalid name: `InvalidCharacterError` (the name checks come before the value and the limits); `LimitExceeded` |
| `RemoveAttribute`, `ToggleAttribute` | none for an absent attribute; `ToggleAttribute` adding an invalid name: `InvalidCharacterError` |
| `AddClass`, `RemoveClass`, `ToggleClass`, `HasClass` | token checks first: empty is `SyntaxError`, ASCII whitespace is `InvalidCharacterError`; then not an element: `HierarchyRequestError` |
| `SetStyleProperty`, `RemoveStyleProperty` | an invalid property or declaration: `InvalidCharacterError` |
| `SetData`, `AppendData`, `InsertData`, `DeleteData`, `ReplaceData` | no character data: `HierarchyRequestError`; offset past the end: `IndexSizeError` (a count past the end is clamped); `LimitExceeded` |
| `Normalize` | none (`LimitExceeded` from the merged data) |
| `CreateElement` | not a valid element local name: `InvalidCharacterError` |
| `ParseFragment` | the context is not an element: `HierarchyRequestError` |
| `MutationObserver.Observe` | argument checks; `StaleNode`; then `TypeError` in the order of DOM 4.3.2 (after applying the `attributes` and `characterData` defaults: nothing observed; `attributeOldValue` or `attributeFilter` without attributes; `characterDataOldValue` without character data) |
| `Release` | `WrongDocumentError`, `StaleNode`; attached node or the document root: `HierarchyRequestError` |

`CreateElement` follows the DOM's "valid element local name": not empty, the first character an ASCII letter, `:`, `_` or a non-ASCII character, and no ASCII whitespace, U+0000, `/` or `>`. Attribute names use the looser check of the layer (no ASCII whitespace, NUL, `/`, `>`, `=`, `<`); the DOM's "valid attribute local name" is the same without `<`, and the difference is left as it was.

Tests: `tests/OneHtml.Tests/Mutation/DomExceptionTests.cs` translates `Node-insertBefore`, `Node-appendChild`, `Node-replaceChild`, `Node-removeChild`, `pre-insertion-validation-notfound.js`, `pre-insertion-validation-hierarchy.js`, `Element-setAttribute`, `Element-setAttribute-crbug-1138487` and `Document-createElement` from WPT `dom/nodes` at commit `ffc4686d117de150daf1287809302e3edea82dc6` (unmodified in `testdata/wpt/dom-nodes`). Left out: cases that insert a second *document* node or build documents with `createHTMLDocument` or `createDocument` (a document cannot be a child here; documents are created by parsing); processing instructions and CDATA sections (no factories); the JavaScript `TypeError` checks for non-Node arguments (the C# signatures take handles); frames and mutation events; `setAttributeNS` with arbitrary namespaces (the attribute model has four); `Document-createElement`'s namespace, case and `createElementNS` parts (HTML documents only, no `createElementNS`).

## 2. Mutation hooks

`MutationHooks` is a class with one virtual method per step of the DOM Standard; override what you need and register the object:

```csharp
IDisposable all = document.AddMutationHooks(hooks);                       // every node
IDisposable one = document.AddMutationHooks(hooks, "img");                // HTML elements named img
IDisposable svg = document.AddMutationHooks(hooks, "a", ElementNamespace.Svg);
```

| Step | Method | When it runs |
|---|---|---|
| Insertion steps (DOM 4.2.3 insert) | `InsertionSteps(inserted)` | For each inserted node and its descendants in tree order, once that node is linked and before the next inserted node is. |
| Post-connection steps | `PostConnectionSteps(connected)` | After the whole insertion (all nodes linked, the mutation record queued, the children changed steps run), for each inserted node that is connected, in tree order, skipping any that is no longer connected. |
| Removing steps (4.2.3 remove) | `RemovingSteps(removed, oldParent)` | After the node left its parent: for the node (with its old parent), then for each descendant in tree order (with the null node as old parent). Before the mutation record. |
| Children changed steps | `ChildrenChangedSteps(parent)` | On the parent after each insertion (once per insert call, after the record, before post-connection steps) and after each removal. |
| Adopting steps (4.5) | `NodeAdopted(oldNode, newNode)` then `AdoptingSteps(newNode, oldDocument)`, on the hooks of the document the node moved to; `AttributeAdopted` for attribute nodes | Run for every adopted node in shadow-including tree order after the copy exists and the original is released. The old handle is stale; its `Key` is what a runtime stored. |
| Cloning steps (4.5) | `CloningSteps(copy, source, subtree)` | By `CloneNode`, for each copied node in tree order, after the whole copy is built (the DOM runs each before the node's children are copied). |
| Attribute change steps (4.9) | `AttributeChangeSteps(element, localName, ns, oldValue, value)` | After an attribute is added (`oldValue` null), changed (also to the same value) or removed (`value` null), after the mutation record. |

**Filter.** A registration with a name and namespace gets a step for a node that is an element with that local name and namespace; `ChildrenChangedSteps` is filtered by the parent. A registration without one gets every node of any kind, including text, comments, fragments and the document. Registrations run in the order they were made.

**Order of one insertion** (`AppendChild(x)`): removal of `x` from its old parent (removing steps, record, children changed steps there) → insertion steps for `x` and its descendants → mutation record → children changed steps of the new parent → post-connection steps. A fragment is inserted node by node: its children leave it (removing steps and children changed steps with the fragment as parent, one record on the fragment), then each is linked and its insertion steps run, then one record, one children changed step and the post-connection steps for all of them. `ReplaceChild`: the node is adopted (removed from its old parent), the child removed, the node inserted, one record. "Replace all" (`SetTextContent`, `SetInnerHtml`, `ReplaceChildren`): each old child is removed (removing steps and children changed steps per child), then the new nodes are linked and the insertion steps run, then one children changed step and the post-connection steps. `SetInnerHtml` replaces with the parsed fragment, so the parsed children show a removal from that fragment first.

**Re-entrancy.** A step runs on the editing thread, in the middle of the edit, and may read or change the tree and register or dispose hooks (registration is copy-on-write; a step that disposes itself still lets the others run). The layer re-reads the tree before it links the next node: a node that a step moved elsewhere is taken out of the way (with its own removal steps and record) and a reference child that a step removed makes the insertion append. Post-connection steps are the safe place for work that depends on the whole insertion; the test `A_step_may_edit_the_tree_post_connection_steps_run_after_the_whole_insert` shows a step seeing a not-yet-inserted sibling as disconnected and the same sibling as connected in its post-connection step. A step may `Release` a node it removed (§4); a mutation record that was going to name the node still holds a handle equal to the one the caller has. An exception thrown by a step propagates to the caller of the edit, which stays as far as it had got.

**Cost.** A document with no hook registered pays one field test per edit and allocates nothing (test `A_document_with_no_hooks_pays_nothing_and_a_disposed_registration_leaves_nothing_behind`). With hooks, each insertion collects the inserted subtree once.

**Parsers.** A parser that builds through the mutable layer (`CreateElement`, `AppendChild`, `InsertBefore`) fires the same steps, as `A_parser_that_builds_through_the_layer_fires_the_same_hooks` shows; connected-ness is evaluated at each link, so a parser that appends a child to a connected parent gets insertion steps and post-connection steps per node. The incremental parser that does this is a later unit; nothing in the hook code is specific to it.

## 3. Tree version

`MutableDocument.TreeVersion` (a `long`) increases by one for every change to the tree: a node linked or unlinked, character data changed, an attribute added, changed (also to the same value) or removed. It is readable at any time in constant time, including mid-transaction and from steps and observers; it starts at 0, never decreases and is not reset or changed by `Commit` (a commit is not a change). It is independent of `Version`, the commit counter. A cache computed at version *v* is current while `TreeVersion == v`.

`MutableDocument.GetAttributeVersion(localName)` is a counter of the same kind for one attribute name over the whole document, constant time: it increases when an attribute of that stored local name (lower case for HTML attributes) is added, changed or removed on any element, and not for structure edits, so a cache of `getElementsByClassName`, an id index or a `name` map needs `TreeVersion`-style invalidation only for structure plus its own attribute's counter. It is 0 for a name no attribute ever had. A per-subtree counter is not provided: it would cost a walk to the root on each edit.

## 4. Release

`MutableDocument.Release(detachedRoot)` is legal on the editing thread at any time for the root of a detached subtree that has no owner (a template content root is owned by its template): in the middle of a transaction, after the nodes were inserted and removed again, from a mutation observer callback, a commit observer and a hook (including the removing steps of the node being removed). The slots become reusable after the next `Commit`; handles into the subtree become stale at once (`IsStale`, `StaleNode`) and observer registrations on its nodes are dropped. It is refused with `HierarchyRequestError` for a node with a parent and for the document root. The call is on the writer thread like every edit; the layer takes no locks. Tests: `Release_is_legal_mid_transaction_and_after_the_nodes_were_touched`, `Release_is_legal_from_observers_commit_observers_and_hooks`.

## Names for consumers

`DomExceptionKind` (new members and aliases above), `DomException.Name`, `MutationHooks` (`InsertionSteps`, `PostConnectionSteps`, `RemovingSteps`, `ChildrenChangedSteps`, `AdoptingSteps`, `CloningSteps`, `AttributeChangeSteps`), `MutableDocument.AddMutationHooks(MutationHooks)` and `AddMutationHooks(MutationHooks, string localName, ElementNamespace ns = Html)`, `MutableDocument.TreeVersion`, `MutableDocument.GetAttributeVersion(string)`, `MutableDocument.Release(MutableNode)` (unchanged signature).
