---
title: "Mutable working layer"
url: https://recursiveai.org/onehtml/docs/mutable-document/
description: "A Document never changes, and Apply(edits) returns the re-parse of edited markup. That is the right model for lossless source editing, and the wrong one…"
version: "1.7.0"
source: https://github.com/recursive-ai-oss/onehtml-csharp/blob/ce3c88332a47927ccc2e92cd702a4bb2577f27ef/docs/mutable-document.md
---

# Mutable working layer

**Status:** implemented. Everything here is an addition to the published API; no existing type changes behaviour. Section 14 lists where the built layer differs from the signatures and prose below (the differences win) and gives measured costs; figures marked *estimate* in sections 3 and 9 are the original design estimates, and section 14 has the measurements.

A `Document` never changes, and `Apply(edits)` returns the re-parse of edited markup. That is the right model for lossless source editing, and the wrong one for a program that mutates a live DOM many times a second (a script runtime, a UI toolkit). This layer adds a **mutable DOM** with the shape of the DOM Standard's mutation methods, stable node identity, a net-effect **change set** per commit, and immutable `Document` snapshots on demand that plug into `DocumentStyles`, `LiveDocumentStyles` and `AccessibilityTree`.

## 1. Model in one page

- A `MutableDocument` owns a mutable tree. It starts from a parsed `Document` (or an empty one) and is changed with DOM-style calls on `MutableNode` handles.
- **Reads see pending edits.** `appendChild` followed by `parentNode` shows the new parent immediately, as in the DOM. Snapshots (`Document`) show only committed state.
- **`Commit()` closes the current transaction.** It never re-parses, never rolls back and cannot fail on the content of the edits (every edit is validated when it is made). It returns a `DocumentCommit`: a version number, a `DocumentChanges` (what changed, net of the whole transaction) and a lazily built immutable `Document` snapshot.
- **Identity is a `MutableNode`**: document reference, slot and generation. It never changes for as long as the node lives, across any number of commits. A snapshot `Node` (document + index) is a *view* of a `MutableNode` at one version; `WorkingSnapshot` converts both ways.
- Snapshots are real `Document` objects, so selectors, `DocumentStyles`, `LiveDocumentStyles`, `AccessibilityTree`, the checker and the serializers work on them unchanged. They carry no source bytes (section 8).

### Why not `Apply`

`Apply` serializes the edit into markup, re-parses, and requires the re-parse to equal the expected tree. Trees built by DOM calls often cannot round-trip through markup: a `div` inside a `p`, a nested `a` or `form`, text directly inside `table`, an element with a name the tokenizer would not produce. A re-parse check would reject or silently reshape them. The working layer therefore builds snapshot columns directly from its own tree and never parses. (Fragment markup passed to `InnerHtml`-style calls does go through the fragment parser, as the DOM Standard says.)

## 2. Public API

Namespace `RecursiveAI.OneHtml.Mutation` (in `RecursiveAI.OneHtml`). Doc comments here are one line; the shipped ones state defaults and edge behaviour.

```csharp
public sealed class MutableDocument
{
    /// <summary>Starts a working document from a parsed document; each node's id equals its index in <paramref name="source"/>.</summary>
    public static MutableDocument Create(Document source, MutableDocumentOptions? options = null);

    /// <summary>The same as Create(Document.Parse(html)).</summary>
    public static MutableDocument Parse(string html, ParseOptions? parse = null, MutableDocumentOptions? options = null);

    public MutableDocumentOptions Options { get; }

    /// <summary>The document node (or the fragment root) of the working tree.</summary>
    public MutableNode Root { get; }
    public MutableNode DocumentElement { get; }

    // --- factories: detached nodes owned by this document ---
    public MutableNode CreateElement(string localName, ElementNamespace ns = ElementNamespace.Html);
    public MutableNode CreateTextNode(string data);
    public MutableNode CreateComment(string data);
    public MutableNode CreateDocumentFragment();
    /// <summary>HTML fragment parsing in the context of <paramref name="context"/>; returns a detached fragment holding the parsed nodes.</summary>
    public MutableNode ParseFragment(string html, MutableNode context);
    /// <summary>Copies a subtree of any snapshot (or of this document) into detached nodes; ids are new.</summary>
    public MutableNode Import(Node source, bool deep = true);
    public MutableNode CloneNode(MutableNode node, bool deep = false);

    // --- transactions ---
    /// <summary>True when edits were made since the last commit that changed something.</summary>
    public bool HasPendingChanges { get; }
    /// <summary>Closes the transaction; with nothing pending returns an empty commit at the current version and notifies nobody.</summary>
    public DocumentCommit Commit();
    /// <summary>Latest committed version; 0 is the starting document.</summary>
    public long Version { get; }
    /// <summary>The snapshot of the latest commit (built on first use).</summary>
    public WorkingSnapshot Snapshot(CancellationToken cancellationToken = default);
    /// <summary>Changes from an earlier snapshot of this document to the latest commit, merged as if they were one transaction.</summary>
    public DocumentChanges ChangesSince(WorkingSnapshot earlier);
    /// <summary>Called after each non-empty commit, in registration order, on the committing thread.</summary>
    public IDisposable Observe(Action<DocumentCommit> observer);

    // --- lifetime ---
    /// <summary>Frees a detached subtree's slots for reuse; handles into it become stale.</summary>
    public void Release(MutableNode detachedRoot);
    /// <summary>One more than the largest slot ever handed out; size slot-indexed side arrays to this and grow when it changes (it only grows).</summary>
    public int SlotCapacity { get; }
    public int NodeCount { get; }          // attached + detached, live slots
    public int AttachedNodeCount { get; }
    public int DetachedRootCount { get; }

    // --- serialization (plain HTML fragment serialization algorithm) ---
    public string SerializeChildren(MutableNode node, bool scriptingEnabled = false);
    public string SerializeNode(MutableNode node, bool scriptingEnabled = false);
}

public readonly struct MutableNode : IEquatable<MutableNode>
{
    public MutableDocument? Document { get; }          // null for the null node
    public bool IsNull { get; }
    /// <summary>A value unique to this node in its document for its lifetime; safe as a dictionary key from any thread.</summary>
    public ulong Key { get; }
    /// <summary>The node's slot, 0 ≤ Slot &lt; SlotCapacity. A consumer may index an array by it, and must compare <see cref="Key"/> to detect a reused slot.</summary>
    public int Slot { get; }
    public bool IsStale { get; }                        // released

    // --- reads (live; writer thread only) ---
    public NodeKind Kind { get; }
    public ElementNamespace Namespace { get; }
    public string LocalName { get; }
    public MutableNode Parent { get; }
    public MutableNode FirstChild { get; }
    public MutableNode LastChild { get; }
    public MutableNode NextSibling { get; }
    public MutableNode PreviousSibling { get; }
    public bool IsConnected { get; }                    // reaches Document.Root
    public MutableNode TemplateContent { get; }         // template elements: their content fragment
    public string? GetAttribute(string name);
    public bool HasAttribute(string name);
    public MutableAttributes Attributes { get; }        // (namespace, localName, value) in order
    public string Data { get; }                         // text, comment, PI
    public string TextContent { get; }
    public IEnumerable<MutableNode> Children { get; }   // struct enumerator, no allocation

    // --- structure (DOM "mutation methods"; each throws DomException before changing anything) ---
    public MutableNode AppendChild(MutableNode child);
    public MutableNode PrependChild(MutableNode child);
    public MutableNode InsertBefore(MutableNode child, MutableNode reference);   // reference null = append
    public MutableNode ReplaceChild(MutableNode newChild, MutableNode oldChild);
    public MutableNode RemoveChild(MutableNode child);
    public void Remove();                                                         // ChildNode.remove()
    public void ReplaceChildren(ReadOnlySpan<MutableNode> nodes);
    public void SetTextContent(string text);                                      // remove all children, insert one text node
    public void SetInnerHtml(string html);                                        // fragment-parse in this element's context, replace children
    public void InsertAdjacentHtml(InsertPosition position, string html);

    // --- attributes ---
    public void SetAttribute(string name, string value);
    public void SetAttribute(AttributeNamespace ns, string localName, string value);
    public bool RemoveAttribute(string name);
    public bool ToggleAttribute(string name, bool? force = null);

    // --- inline style (CSSOM single-property edits on the style attribute) ---
    /// <summary>Sets one declaration in the style attribute through the declaration helpers the editor uses; other declarations keep their text.</summary>
    public void SetStyleProperty(string property, string value, bool important = false);
    /// <summary>Removes one declaration; no-op when absent.</summary>
    public void RemoveStyleProperty(string property);

    // --- class list (DOMTokenList semantics over the class attribute) ---
    public bool AddClass(string token);
    public bool RemoveClass(string token);
    public bool ToggleClass(string token, bool? force = null);
    public bool HasClass(string token);

    // --- character data ---
    public void SetData(string data);                                             // text, comment, PI
}

public enum InsertPosition { BeforeBegin, AfterBegin, BeforeEnd, AfterEnd }

public sealed class MutableDocumentOptions
{
    public int MaxNodes { get; init; } = 4 * 1024 * 1024;              // live slots, attached or not
    public int MaxAttributesPerElement { get; init; } = 1024;
    public int MaxTotalAttributes { get; init; } = 4 * 1024 * 1024;
    public int MaxDepth { get; init; } = 4096;                         // tree depth after any insertion
    public int MaxValueLength { get; init; } = 1024 * 1024;            // one attribute value or one text node, in chars
    public long MaxValueStoreChars { get; init; } = 256L * 1024 * 1024; // live attribute and text characters
    public int MaxObserverNesting { get; init; } = 64;                 // commits made from inside observers during one delivery
    public int JournalCommits { get; init; } = 256;                    // how far back ChangesSince can name elements precisely
    public ParseLimits? FragmentLimits { get; init; }                  // for ParseFragment / SetInnerHtml
}

public enum DomExceptionKind { HierarchyRequest, NotFound, InvalidCharacter, WrongDocument, StaleNode, LimitExceeded }

/// <summary>A DOM-level failure; the working document is unchanged.</summary>
public sealed class DomException : InvalidOperationException
{
    public DomExceptionKind Kind { get; }
}
```

Existing typed exceptions apply otherwise: `ArgumentNullException`/`ArgumentException` for bad arguments, `OperationCanceledException` for cancellation. `DomException` is the only new exception type; limit failures use `Kind == LimitExceeded` with the limit's name and value in the message (the working layer's limits are its own, not `HtmlLimitExceededException`).

### Rules the mutation methods follow

- **Insertion** follows the DOM Standard's "ensure pre-insertion validity", "pre-insert", "insert", "adopt" and "remove" algorithms: a node already in a tree is removed from its old parent first (that is how a move is made); inserting a document fragment inserts its children and empties it; an ancestor can't be inserted into its descendant; a document root accepts at most one element child, at most one doctype before it, comments and processing instructions; text can't be a child of a document; a node from another `MutableDocument` is a `WrongDocument` error (use `Import`). All checks happen before anything changes.
- **Attributes.** `SetAttribute(name, …)` on an HTML element lowercases the name with ASCII case folding (DOM "set an attribute value"; the document is an HTML document). Names must be non-empty and contain no ASCII whitespace, NUL, `/`, `>` or `=` (`InvalidCharacter`). Setting an existing attribute keeps its position; a new one goes last. Setting a value equal to the current one is a no-op and records nothing.
- **Class list** follows DOMTokenList: tokens split on ASCII whitespace; add/remove/toggle edit the `class` attribute through the ordered set serializer (duplicates collapse, order of first occurrence kept); a token with whitespace or an empty token is `InvalidCharacter`. A class edit that changes nothing writes nothing. A class edit that changes the token set rewrites the whole attribute value in normalized form, as the DOM does.
- **Text.** The DOM does not merge adjacent text nodes, so neither does this layer; there is no `Normalize`, and a commit never merges text nodes.
- **`SetInnerHtml`/`ParseFragment`** build a `FragmentContext` from the element (name, namespace, form association, quirks mode of the document) and use the existing fragment parser. Scripts stay inert text. `template` elements get a content fragment as the parser does.
- **Serialization of a `template`** and of void/raw-text elements follows HTML 13.3 as the existing `Document.SerializeNode` does.

## 3. Identity and the snapshot relationship

- **`MutableNode`** = (`MutableDocument`, `int slot`, `int generation`), 16 bytes like `Node`. Slots are the mutable tree's own indexes. A slot is never reused while its node exists. Detached nodes (removed, not re-inserted) stay valid because a script may re-insert them; they cost memory until the caller calls `Release(detachedRoot)`, which frees the subtree's slots, bumps their generations, and makes old handles report `IsStale` / throw `StaleNode`. Nothing is freed implicitly. `Key` packs slot and generation.
- **The starting document.** `MutableDocument.Create(doc)` gives node `i` of `doc` the slot `i`; snapshot version 0 **is `doc` itself** (same object, source and lossless output intact). A consumer that already holds `Node` handles into `doc` can convert them with `snapshot.ToMutable(node)`.
- **Later snapshots.** A snapshot is a new `Document` whose indexes are the **document-order (pre-order) rank** of the attached nodes at that version, so that "document order = index order" still holds for every consumer that sorts by `Node.Index` (restyle lists, dependency lists, navigation lists). Indexes therefore change between snapshots, as they do after `Apply`; `MutableNode` does not.

```csharp
/// <summary>One immutable version of a MutableDocument: a Document plus the map between its nodes and stable identities. Free-threaded.</summary>
public sealed class WorkingSnapshot
{
    public MutableDocument Source { get; }
    public long Version { get; }
    public Document Document { get; }
    /// <summary>The view of a node at this version; the null node when it was not attached at this version.</summary>
    public Node ToNode(MutableNode node);
    /// <summary>True when the node is attached at this version (then <see cref="ToNode"/> returns a non-null node).</summary>
    public bool Contains(MutableNode node);
    /// <summary>The identity behind a snapshot node; throws if the node is from another document.</summary>
    public MutableNode ToMutable(Node node);
    /// <summary>Old index → new index for the nodes both snapshots hold (-1 when absent), the shape StyleChange.OldToNew wants.</summary>
    public int[] MapTo(WorkingSnapshot newer);
    /// <summary>The same, written into a caller buffer of length <c>Document.NodeCount</c>; allocates nothing.</summary>
    public void MapTo(WorkingSnapshot newer, Span<int> oldToNew);
}
```

**Guarantee:** `ToNode`, `ToMutable` and `Contains` are O(1) and allocate nothing. `ToMutable` is an array read; `ToNode` is a slot→index array read (kept per snapshot, 4 bytes per slot plus 4 per node for the reverse). Both include the generation so a reused slot is never mistaken for the old node.

### Can a commit produce an immutable snapshot, and at what cost?

Yes, lazily. `Commit()` itself is O(k) bookkeeping for k edits and builds nothing. `commit.Snapshot` (or `doc.Snapshot()`) walks the attached tree once with an explicit stack and writes the arena columns directly:

- Node and attribute columns are written fresh in pre-order (one pass, O(n + attributes)); parent/child/sibling indexes come from the slot→index map. *Estimate:* a few ns per node per column, about 70 bytes written per node and 30 per attribute; low single-digit milliseconds at 35k nodes. This is the cost the existing design avoids on the read path and pays here once per snapshot, not once per edit.
- Text and attribute values are **not copied**. The working document keeps one append-only character pool; snapshots point into it (the arena already stores values that are not verbatim source slices as offsets into a side store). A snapshot shares the pool array up to its length; growth allocates a new array and old snapshots keep theirs. Dead characters (replaced values) are compacted into a fresh pool when they exceed half of the live total; old snapshots keep the old pool.
- A structural-only-attribute/text commit (no insert, remove or move) could copy the previous snapshot's columns and patch k entries (indexes unchanged). That is an optimization for phase 2 if the benchmark asks for it; the pre-order walk is the baseline.
- Memory per retained snapshot ≈ the columns above (about 70 B/node + 30 B/attribute, *estimate*); the pool is shared. Snapshots are garbage-collected when unreferenced. The working document itself holds about the same column width per live slot (including detached ones) plus the pool.
- If nothing needs a snapshot (a consumer that only reads `DocumentChanges` and the live nodes) none is built, and commits cost O(k).

## 4. The change set

A commit's `DocumentChanges` describes the **net effect of the transaction**: it compares the tree at the start of the transaction with the tree at commit. It is not a log of calls. All data in it is immutable and free-threaded; node references are `MutableNode` identities plus values captured at commit (names, strings), so a consumer on another thread needs no access to the live tree.

```csharp
public sealed class DocumentCommit
{
    public MutableDocument Source { get; }
    public long Version { get; }                    // version after this commit
    public bool IsEmpty { get; }                    // nothing changed; Version equals the previous one
    public DocumentChanges Changes { get; }
    public WorkingSnapshot Snapshot { get; }         // built on first use and cached; GetSnapshot takes a token
    public WorkingSnapshot GetSnapshot(CancellationToken cancellationToken);
    public WorkingSnapshot? PreviousSnapshot { get; } // null until the previous version has been materialized
    /// <summary>The same information in the editor's ChangeSet shape (Added, Removed, Changed, MapToNew; Ranges is empty).</summary>
    public ChangeSet ToChangeSet(WorkingSnapshot previous, CancellationToken cancellationToken = default);
}

public sealed class DocumentChanges
{
    public long FromVersion { get; }
    public long ToVersion { get; }
    public bool IsEmpty { get; }
    public StyleImpact Impact { get; }
    /// <summary>Roots of subtrees that are attached now and were not attached before. Descendants are not listed.</summary>
    public IReadOnlyList<InsertedNode> Inserted { get; }
    /// <summary>Roots of subtrees that were attached before and are not now. Their nodes stay valid (detached) until released.</summary>
    public IReadOnlyList<RemovedNode> Removed { get; }
    /// <summary>Nodes attached before and now whose place changed.</summary>
    public IReadOnlyList<MovedNode> Moved { get; }
    /// <summary>Elements (attached before and now, not inserted) whose attribute set changed.</summary>
    public IReadOnlyList<AttributeChange> Attributes { get; }
    /// <summary>Elements whose class token set changed (derived from the class attribute change).</summary>
    public IReadOnlyList<ClassChange> Classes { get; }
    /// <summary>Elements whose inline style changed through <c>SetStyleProperty</c>/<c>RemoveStyleProperty</c>, one entry per property; a <c>style</c> attribute written as a whole is in <c>Attributes</c> only.</summary>
    public IReadOnlyList<InlineStyleChange> InlineStyles { get; }
    /// <summary>Text, comment and PI nodes (attached before and now, not inserted) whose data changed.</summary>
    public IReadOnlyList<TextChange> Text { get; }
    /// <summary>Parents whose list of children changed (insert, remove or move into, out of, or within them).</summary>
    public IReadOnlyList<MutableNode> ChildListChanged { get; }
    /// <summary>True when the list-valued members were not computed per node because the journal did not reach back (ChangesSince only); every surviving element must be treated as changed.</summary>
    public bool IsApproximate { get; }
}

public readonly record struct InsertedNode(MutableNode Node, MutableNode Parent, MutableNode PreviousSibling, MutableNode NextSibling);
public readonly record struct RemovedNode(MutableNode Node, MutableNode OldParent, MutableNode OldPreviousSibling, MutableNode OldNextSibling);
public readonly record struct MovedNode(MutableNode Node, MutableNode OldParent, MutableNode OldPreviousSibling, MutableNode OldNextSibling,
                                        MutableNode NewParent, MutableNode NewPreviousSibling, MutableNode NewNextSibling);
public readonly record struct AttributeDelta(AttributeNamespace Namespace, string LocalName, string? Old, string? New); // null = absent
public readonly record struct AttributeChange(MutableNode Element, IReadOnlyList<AttributeDelta> Deltas);
public readonly record struct ClassChange(MutableNode Element, IReadOnlyList<string> Added, IReadOnlyList<string> Removed);
/// <summary>One inline-style property of one element: the declared value before and after (null = not declared), lower-cased property name, with its priority.</summary>
public readonly record struct InlineStyleChange(MutableNode Element, string Property, string? Old, string? New);
public readonly record struct TextChange(MutableNode Node, string Old, string New);

[Flags] public enum StyleImpact
{
    None = 0,
    Attributes = 1,   // an element attribute changed
    Structure = 2,    // a subtree was inserted, removed or moved
    Text = 4,         // character data changed
    StyleSheets = 8,  // a style element or link (rel, href, media, disabled, ...) was inserted, removed, moved, or had its text or attributes changed
}
```

### Field semantics

- **Sibling anchors, not indexes.** `PreviousSibling`/`NextSibling` in `Inserted`/`Moved` are the node's neighbours **at commit** (the final tree); in `Removed`/`Moved` the `Old*` ones are its neighbours **at the start of the transaction**. They are `MutableNode` identities and may themselves be inserted, removed or moved in the same commit; the null node means "none". This is the information a DOM mutation record carries and it costs O(1) to produce; an integer index would need an O(children) walk per node on a long list. A consumer that wants an index reads it from the snapshot.
- **Order.** Every list is in the order the nodes were **first changed** in the transaction (deterministic for a given call sequence), not document order. This keeps commit O(k). Document order is available after the fact: sort by `snapshot.ToNode(n).Index`. `Deltas` within an element are in the order each attribute was first changed. `Added`/`Removed` class tokens are in order of first appearance in the new/old attribute value.
- **Net effect and coalescing** (the rules; every pair below is a test case):
  - *Created and inserted, then changed:* one `Inserted` entry for the subtree root; later attribute, text and class edits to nodes inside it are not listed (a consumer reads the node's current state).
  - *Inserted then removed (or created, inserted, removed):* nothing. The node was never in a committed tree.
  - *Changed then removed:* one `Removed` entry; the attribute/text/class changes are dropped (the node's old state is not reconstructed; `Old` values are not kept for removed nodes).
  - *Removed then inserted back at the same place:* nothing structural (and it is not in `Moved`). If its attributes changed in between, they are listed.
  - *Inserted then moved (inside the same transaction):* one `Inserted` entry with the final place.
  - *Moved twice:* one `Moved` entry, old place from the start, new place from the end. Moving back to the starting place cancels.
  - *Removed from A and inserted into B:* `Moved` (old parent A, new parent B), because the node is attached at both ends. Removed in one commit and inserted in a later commit is `Removed` then `Inserted`, not `Moved`: a commit sees the detached state.
  - *Reorder within one parent:* a survivor whose relative order among the parent's surviving children is unchanged is not moved; the minimal set that is (longest increasing subsequence over old order, earliest on ties) is listed as `Moved`. Appending or removing in a long list therefore never reports its untouched neighbours.
  - *Attribute set then restored:* no entry. *Several sets:* one delta with the first old and the last new value. `class` changes appear both in `Attributes` (strings) and `Classes` (tokens); in the same way a change made with `SetStyleProperty`/`RemoveStyleProperty` appears in `Attributes` (the whole `style` string) and in `InlineStyles` (the property). *Inline styles:* one entry per (element, property) with the first old and last new value; setting a property back to its original value cancels; a whole-attribute write to `style` after property edits discards that element's `InlineStyles` entries (the restyle then treats `style` as any-property); `ClearedContexts` is not here, see section 6.
  - *Text node data changed twice:* one `TextChange` with the first old and last new data. A text node replaced by another is `Removed` + `Inserted`.
  - *Subtree roots only:* descendants of an inserted or removed root are not listed; a node moved with its subtree is one `MovedNode`. A node inside a moved subtree that is also moved *relative to its parent* is listed separately.
- **`ChildListChanged`** lists each parent once; it exists because `:empty`, `:first-child`, `:nth-*`, sibling combinators and the accessibility tree's required-owned-elements checks depend on child lists, and so the restyle can seed those parents.
- **`Impact`** says which of the consumers' work lists is non-empty; `StyleSheets` is what turns on `StyleChange.SheetsChanged`.
- **`ChangesSince(earlier)`** merges the retained per-commit changes with the same net-effect rules (first old, last new). Slots released in between are never named. If `earlier` is older than `JournalCommits` commits, the result has `IsApproximate = true` and empty per-node lists: restyle then treats every surviving element as changed (correct, slower), and the id map for `OldToNew` is still exact because every snapshot records (slot, generation) per index.
- **Observers** receive the `DocumentCommit` after the version has been bumped.

## 5. The commit model

**State.** One *pending transaction* is always open. Each edit validates, applies to the live tree, and appends O(1) baseline information for the nodes it touches (parent and neighbours at first touch, original attribute values, original text; only for nodes attached at the start of the transaction). Cost is proportional to touched nodes; untouched nodes cost nothing.

**Reads.** `MutableNode` reads see pending edits. `Snapshot`/`ToNode` see the last commit. `HasPendingChanges` tells you which you are looking at. Nothing is visible to other threads until committed (and only through immutable commit objects).

**What fails a commit.** Nothing about the edits: each one is checked when made, and an edit that throws `DomException` (hierarchy, wrong document, stale handle, invalid name, any limit) has changed nothing, so the transaction holds only valid edits. There is no rollback (section 12). `Commit()` itself throws only `DomException(LimitExceeded)` when observers nest past `MaxObserverNesting` (the commit is still complete). Building a snapshot can throw `OperationCanceledException`; the commit stands and the next access retries the snapshot. Node limits are enforced at edit time, so the snapshot build cannot exceed them.

**Thread safety.** `MutableDocument` and `MutableNode` reads/writes: one thread at a time (external synchronization, or one owner thread). `MutableNode` equality, `Key`, and `IsNull` need no synchronization. `DocumentCommit`, `DocumentChanges`, `WorkingSnapshot`, `Document` are immutable and may be read from any thread while the writer keeps editing; building a snapshot lazily is itself synchronized (first use takes an internal lock; the writer must not mutate while a lazy build runs on another thread. To avoid that, call `commit.Snapshot` from the writer thread before handing the commit over, or use `doc.Snapshot()` there).

**Cancellation.** Edits are O(1) and take no token. `Snapshot(ct)`, `Restyle`, the live-styles rebase and the tree `Update` take tokens; cancelling them leaves the commit, the document and every previous result intact.

### Early commit

`doc.Commit()` is the hook a layout query calls. Semantics:

- **Nothing pending (guarantee):** O(1), **allocates nothing** (it returns one cached empty commit per version), returns the **same `Snapshot` reference** as the last commit, has empty `Changes` and the current `Version`, and runs no observer. Safe to call as often as wanted.
- **Pending edits:** commits them exactly as at a checkpoint. A caller that only needs layout up to date still has to restyle: `commit.Snapshot` + `styles.Restyle(commit)` (section 6) or the incremental pieces from the last styled version via `ChangesSince`.
- **Re-entrant call from an observer:** allowed. Edits an observer makes belong to the *next* transaction. If it calls `Commit()`, those edits commit immediately, the new commit is returned to it, and its observer notifications are **queued** and delivered after the current delivery finishes, in commit order, so observers never see commits out of order and the stack never grows with commit count. An empty re-entrant `Commit()` returns the empty commit (nothing queued). Observers that keep committing are cut off after `MaxObserverNesting` commits in one delivery (`DomException.LimitExceeded`, thrown to the observer).
- **Observer exceptions** stop that delivery, leave the document and the commit consistent, and propagate to whoever called `Commit()` that started the delivery; later observers for that commit do not run.
- **Writer-only:** `Commit()` from another thread is a usage error with undefined result unless synchronized by the caller.

## 6. How it composes with what exists

| Existing | Use |
|---|---|
| `Document`, `Node`, selectors | Snapshots are ordinary `Document`s. `QuerySelectorAll` etc. run on the snapshot. Live reads use `MutableNode`; no selector API on `MutableNode` in v1. |
| `Apply`, `EditResult`, `ChangeSet` | Unchanged and independent. `commit.ToChangeSet(previous)` builds a `ChangeSet` (Added, Removed, Changed with `NodeChanges.Attributes/Data/Children/Parent`, `MapToNew`, empty `Ranges`) from a commit, for consumers written against that type. Calling `Apply` on a post-mutation snapshot is not supported (it has no source); an edit made by the saved-edit format goes to the original document or to a re-created one. |
| `DocumentStyles.Restyle(Document, StyleChange)` | **Reused, with a seeded path.** New extensions `styles.Restyle(DocumentCommit commit)` and `Restyle(DocumentChanges, WorkingSnapshot from, WorkingSnapshot to)` build a `StyleChange` with `OldToNew = from.MapTo(to)`, `Elements` from `Attributes` (with attribute names; for an `InlineStyles` entry the restyle may narrow to that property), `Classes`, `ChildListChanged` and `Text` parents, and `SheetsChanged = Impact.HasFlag(StyleSheets)`. **When `IsApproximate` is false the restyle is seeded from the change set and skips the full tree comparison:** an inserted root means its whole subtree; a removed or moved entry means its old and new parents and its old and new following siblings (all following siblings when a rule uses `~` or `:nth-*`, so sibling combinators and structural pseudo-classes are re-matched); `ChildListChanged` parents cover `:empty`, `:first-/last-/only-child` and `:has()` ancestors. When `IsApproximate` is true the existing tree comparison is the fallback. **Requirement (a test): the result equals a fresh `DocumentStyles.Create` on the new snapshot, for the same context and options.** A new internal seed input to the existing restyle carries this; `StyleChange` and `Restyle(Document, StyleChange)` do not change. Returns the existing `RestyleResult` (`RestyledElements` are indexes in the new snapshot; map back with `ToMutable`), which gains one additive property, `InteractionContexts ClearedContexts` (below). |
| `LiveDocumentStyles` | Fixed to one `Document`, so a commit needs a new instance. **`LiveDocumentStyles.Rebase` is part of this build.** `public static RebaseResult Rebase(LiveDocumentStyles previous, RestyleResult restyle, WorkingSnapshot from, WorkingSnapshot to, CancellationToken ct = default)`. **Contract: the new live styles equal `LiveDocumentStyles.Create(restyle.Styles)` plus the previous interaction state re-applied through the node map; form-state overrides of removed nodes are dropped.** It carries unchanged style objects over by the index map instead of re-running the cascade, so its cost is O(n) array carry-over plus the restyled elements. `RebaseResult` holds `LiveDocumentStyles Styles` and `[Flags] InteractionContexts ClearedContexts`. `[Flags] enum InteractionContexts { None = 0, Focus = 1, Hover = 2, Active = 4, Target = 8 }` lists which of the four contexts pointed at a node that was removed and so was cleared. **Where it is reported:** by `Rebase`, and by `RestyleResult.ClearedContexts` for `Restyle(commit)`, because the contexts live in the styles (`StyleContext`), not in the document; `DocumentChanges` is document-only and cannot hold it. The library only clears; blur/focus events, focus fix-up and choosing a new focus are the engine's. **Form state stays out of the layer:** the engine owns it keyed by `MutableNode` and re-applies it with `ApplyFormState`/`ApplyState` on the new instance after `Rebase`, using `to.ToNode(mutableNode)`. |
| `AccessibilityTree` | New overloads `Update(DocumentCommit commit, RestyleResult restyle, CancellationToken)` and `Update(DocumentChanges, WorkingSnapshot from, WorkingSnapshot to, RestyleResult, …)`. The second works over a **multi-commit `ChangesSince`** (exact within the journal; `IsApproximate` makes it a full build or a conservative recompute, reported in `UpdateInfo`) as well as over one commit, with `from` the snapshot the tree was built for. They call the existing `UpdateCore` with a `ChangeSet` built from the changes and the restyle's `RestyledElements` and `PseudoElementsMayDiffer` as seeds, so they inherit its rules: names and descriptions are carried over for elements whose inputs (ID references, labels, contents, hidden, role, parent, style) did not change; roles, hidden status, `aria-owns`, states, relations and diagnostics are linear passes recomputed; a full restyle, a reached limit, CSS counters in a name or rendered facts cause a full build, reported in `UpdateInfo`. **The tree update is never automatic:** `Commit`, `Snapshot`, `Restyle` and `Rebase` do no accessibility work, so a consumer that never calls `Update` pays nothing per commit. **Accepted cost:** linear passes plus incremental names (a fraction of a `Build`; the 1.6.0 build is 280 µs on an 8 KB page), not O(k). `AxNode.Node` points into the snapshot; map to identity with `ToMutable`. |
| `RenderedFacts` | Describe one snapshot; a commit makes them stale, as `Apply` does. Unchanged rules from `Update` apply. |
| `PageOutline`, checker | Run on the snapshot. `Checker.Recheck` takes an `EditResult`-based change set today; a `ChangeSet` from `ToChangeSet` may be passed where it takes one, otherwise run a fresh check. |

## 7. Limits and hostile callers

Every limit is checked **before** the allocation or work it guards, and throws `DomException(LimitExceeded)` with nothing changed.

- **Nodes:** `MaxNodes` counts live slots including detached ones, so creating millions of nodes and never attaching them fails at the limit. `Release` returns slots.
- **Attributes:** per element and total, as `ParseLimits` has them.
- **Values:** one attribute value or text node ≤ `MaxValueLength`; all live values ≤ `MaxValueStoreChars`. The pool also holds dead characters; when dead exceeds live it is compacted (O(live), amortized O(1) per character written), so a loop that rewrites one attribute forever uses bounded memory. Per-call cost of class edits and attribute rewrites is linear in the current value length (a 1 MiB class string edited a million times is a million megabyte-scans; the default per-value cap bounds one call, not a loop; callers rate-limit scripts).
- **Depth:** insertion validates that the tree depth stays ≤ `MaxDepth` (walk up from the parent, at most `MaxDepth` steps; a per-node height upper bound for the inserted subtree, refreshed at each commit's walk). No operation recurses on tree depth: insertion, removal, clone, import, serialization and snapshot building use explicit stacks.
- **Cycles:** the "inserted node is an inclusive ancestor of the parent" check is an ancestor walk, O(depth) ≤ `MaxDepth`.
- **Quadratic hazards:** `AppendChild`/`RemoveChild` are O(1) on linked children, never O(siblings). No operation computes a child index. `ChildListChanged`, net-effect bookkeeping and observers are O(touched). A same-parent reorder is O(c log c) in that parent's touched survivor count. `SetInnerHtml` is O(markup + old subtree). Observer nesting is bounded by `MaxObserverNesting`. The journal keeps `JournalCommits` commits, each O(its own k), so its memory is bounded by edits made, not by n.
- **Fragment markup** is subject to `FragmentLimits` (default `ParseLimits.Default`).

## 8. Serialization and lossless behaviour

- **The working layer is not lossless and does not claim to be.** Version 0 is the parsed `Document`, with its source and `ToLosslessBytes()` unchanged. After the first non-empty commit, snapshots have no source bytes: `Node.Source` ranges are empty and `NodeSource.IsDisplaced` is true for every node, `Document.Source` is empty, `WriteLossless`/`ToLosslessBytes` give the plain serialization (the same fallback documents with no source use).
- **`MutableDocument.SerializeNode/SerializeChildren`** and `Document.SerializeNode` on a snapshot use the HTML fragment serialization algorithm (13.3): double-quoted attributes, `&`, `<`, `>` and NBSP escaped, void elements without end tags, raw-text elements verbatim. Output is deterministic and equal for the live tree and its latest snapshot; parsing it again can give a different tree for trees markup cannot express (section 1), exactly as in the DOM.
- **Preserving untouched markup** after mutations (so a runtime could write back a patched page) is a different feature: it needs to track source ranges through mutation. It is not in v1; for a lossless patch of a parsed page use `Apply` on the original document.

## 9. Costs at a glance (*estimates*) and the phase-2 benchmark

| Step | Cost for k edits on n nodes |
|---|---|
| One edit | O(1) (+ O(name) for attributes, + O(MaxDepth) worst case for insert checks); allocation: baseline entry (~48 B) per first touch, plus the node's slot columns (~70 B) and pool chars for created nodes |
| `Commit()` | O(k) time and allocation (change records); no tree walk |
| Snapshot | O(n + attributes) time, ~70 B/node + ~30 B/attribute allocated; text and values shared |
| `ChangesSince` over c commits | O(total touched) |
| `styles.Restyle(commit)` | seeded: affected-rule matching and cascades for the seeded elements; no tree comparison unless `IsApproximate` (which costs O(n), about 2 ms on 6.6k elements in the 1.6.0 notes) |
| `LiveDocumentStyles.Create` (the contract's reference) | ≈ `ComputeAll`, O(n) cascades |
| `LiveDocumentStyles.Rebase` | O(n) array carry-over + restyled elements' styles; no cascade for unchanged elements |
| `AccessibilityTree.Update` | linear passes O(n) + names for the dirty set; fraction of a `Build` |
| Empty `Commit()` | O(1), no allocation |
| Memory | live document ≈ column width per slot + pool; each retained snapshot ≈ columns |

**Benchmark.** Measure snapshot + seeded restyle + `Rebase` end to end (the engine's flush: `ChangesSince`, then those three) on a 1,000-row list (about 3k nodes) and on 10k nodes, for k = 1, 10 and 100 typical edits of each kind: append, remove, move, attribute toggle, class toggle, text change, single style property. **Target: at most about 0.5 ms for a typical single change on 3k nodes.** It is a target to report against, not a gate. Report the AX `Update` cost separately, and `Commit()` alone (O(k)) and the empty commit. If the O(n) terms dominate, the first optimizations are, in order: patch-copy of columns for non-structural commits, then chunked columns (only if the numbers say so).

## 10. Tests

- **Transaction/change-set correctness:** random call sequences on random documents, comparing `Changes` against a diff of two snapshots (net inserted/removed/moved/attributes/classes/text recomputed from the trees by brute force), including every coalescing rule above, and `ChangesSince` equal to the diff of the two snapshots.
- **Handle stability:** random sequences with commits between; every surviving `MutableNode` maps to the node with the same kind/name/attributes/text in the new snapshot; stale handles throw; released slots are never confused with their old occupants.
- **Snapshot equals re-parse where markup can express the tree:** serialize, parse, compare tree shapes with the existing tree comparer.
- **Styles/AX after edits:** `Restyle` equals `DocumentStyles.Create` on the new snapshot; `Update` equals `Build`; the same for `Rebase` vs `Create`.
- **Limits:** crafted input for node count, depth (including moving a deep subtree under a deep node), attribute rewrites, observer nesting.
- **Seeded restyle and `Rebase`:** `Restyle(commit)` with `IsApproximate` false equals `DocumentStyles.Create` on the new snapshot, over random edit sequences on documents with sibling combinators, `:nth-*`, `:empty`, `:has()`, inline styles and `<style>` edits; `Rebase` equals `Create` plus re-applied state; `ClearedContexts` is right for each of the four contexts.
- **Maps:** the span `MapTo` equals the array `MapTo`; `ToNode`, `ToMutable`, `Contains` allocate nothing (allocation-counting test); the empty `Commit()` allocates nothing and returns the same snapshot reference.
- **Inline style:** `InlineStyles` coalescing (set twice, set and restore, whole-attribute write after property edits) against a brute-force diff.
- A SharpFuzz target for the call-sequence reader (untrusted: the sequences come from script).

## 12. Decisions

These were open in the first draft and are settled.

- **Snapshots on demand**, typically one per flush: the engine commits as often as it must, then takes `ChangesSince(lastStyledSnapshot)` and one snapshot.
- **Change lists are in first-touch order**; document order comes from the snapshot index.
- **Adjacent text nodes are kept** as the DOM has them; a commit never merges them and there is no `Normalize`.
- **Focus fix-up and events belong to the engine.** The library clears a removed focus, hover, active or target node and reports which (`ClearedContexts`).
- **Detached nodes are freed only by `Release`**; no weak handles or finalizers.
- **No rollback.** Edits are validated when made, and the only commit-time failure is observer nesting.
- **Net effect only**; there is no raw mutation log.
- **Form state is not in the layer.** The engine keeps it keyed by `MutableNode` and re-applies it after `Rebase`.
- **No shadow trees, slots or custom elements** (`template` content only).
- **Single writer**, with immutable commit and snapshot objects readable from any thread.
- **Accessibility cost** is linear passes plus incremental names, and the update is explicit, never automatic.
- **Limits:** the defaults in section 2 (4M nodes, depth 4096, 256 journal commits) stand.
- **`Import` and `CloneNode` work within one `MutableDocument`;** `Import(Node)` from a `Document` snapshot copies a subtree in. Nodes of another `MutableDocument` are a `WrongDocument` error.

## 13. Open items

None. A source-less snapshot serializes through the plain serialization as `WriteLossless` does for documents with no source (section 8); the depth bookkeeping is described in section 14.

## 14. As built: differences and measurements

**Differences from the text above (these win).**

- `ChangesSince` and `Snapshot()` throw `InvalidOperationException` while edits are pending (commit first). A `DocumentCommit` can build its snapshot only while it is the latest version or after it has been built (`IsSnapshotAvailable`). `PreviousSnapshot` is null when the version before was never materialized; then pass both snapshots to `Restyle(changes, from, to)` and to the tree `Update`.
- A commit with any pending edit raises the version even when its net change set is empty (edits inside `template` content are not in change sets but are part of snapshots). `DocumentCommit.IsEmpty` means "no pending edits"; `DocumentChanges.IsEmpty` means "nothing listed".
- Lists are in first-touch order; within an element, attribute deltas follow the element's current attribute order, then removed attributes.
- `InlineStyles` is derived from the difference of the `style` attribute before and after, so a whole-attribute write is covered and lists the properties whose declared value changed (the "discard on whole write" rule is gone). A value carries ` !important` when important. Inline-style edits on inserted, removed or character-data nodes are not listed.
- Baselines also record the neighbours of a touched node, so `Old*` siblings are exact. A same-parent reorder uses a weighted longest increasing subsequence (untouched nodes are forced into it). The parent's child order is copied the first time a pre-existing child of it is removed or moved in a transaction, so a commit is O(k + children of parents that lost or moved a pre-existing child), not strictly O(k); appends and attribute, class, text and style edits are O(k).
- Slots are reused only after the next `Commit()`. Released and removed nodes appear in change records under the key they had when first touched. `Release` does not mark the transaction pending. Released nodes count against `MaxNodes` until the next commit.
- `WorkingSnapshot.Contains` is true for template content nodes; they are in snapshots but not in change sets.
- `StyleImpact.StyleSheets` also covers `base` elements and the doctype, as the editor does.
- `MutableDocumentOptions.MaxNames` caps distinct names. `ReplaceChildren` on a document throws `HierarchyRequest`. The depth check uses a per-node height upper bound and falls back to an exact walk (bounded) before refusing, so a refusal can be conservative for a subtree whose bound is stale.
- Snapshot nodes have no source; the quote style of attributes is double. A template's content follows the template in snapshot order.
- `InteractionContexts` is in `RecursiveAI.OneHtml.Mutation`; `RebaseResult` is in `RecursiveAI.OneHtml.Css`. `RestyleResult.ClearedContexts` is set by every restyle (also `WithContext`).
- `AccessibilityTree.Update(DocumentCommit, RestyleResult)` returns the same tree for an empty commit, and throws `ArgumentException` when the commit does not lead from the tree's document. The `Update(DocumentChanges, from, to, restyle)` overload accepts any pair of snapshots with their merged changes; approximate changes make every surviving element count as changed.
- `DocumentStyles.RestyleCore` now checks the parent of a node that keeps its index but moves (found while building the seeded restyle).

**Measured costs** (indicative; AMD Ryzen 9 7950X3D, 32 logical cores, load under 1 during the runs, .NET SDK 10.0.403, in-process BenchmarkDotNet, one invocation per iteration with a fresh document, 15 iterations, Release). Page: a `ul` of rows, each `li.item > a > text`, with a stylesheet of nth-child, last-child, adjacent-sibling, descendant, `:hover`, `:focus-visible`, `:empty` and `:has()` rules. 1,000 rows are about 3,000 nodes. Times are means for k = 1 / k = 100 edits of a kind spread over the list.

| Step, 1,000 rows | append | remove | move | attribute | class | text | style property |
|---|---|---|---|---|---|---|---|
| `Commit()` | 3.5 / 23 µs | 53 / 74 µs | 50 / 78 µs | 3.0 / 18 µs | 5.1 / 36 µs | 3.5 / 18 µs | 5.9 / 65 µs |
| Snapshot | 82 / 91 µs | 81 / 81 µs | 82 / 84 µs | 81 / 82 µs | 83 / 80 µs | 83 / 91 µs | 83 / 82 µs |
| Flush: commit + snapshot + seeded restyle + `Rebase` | 1.58 / 1.87 ms | 1.66 / 1.50 ms | 1.65 / 1.70 ms | 0.51 / 0.59 ms | 0.44 / 0.66 ms | 0.14 / 0.21 ms | 0.52 / 0.71 ms |
| `AccessibilityTree.Update` | 3.2 / 2.8 ms | 2.6 / 2.3 ms | 2.7 / 2.6 ms | 1.8 / 1.8 ms | 1.8 / 1.9 ms | 1.7 / 1.8 ms | 1.8 / 1.9 ms |

With 3,333 rows (about 10,000 nodes) the flush is 5.2–5.5 ms for append, remove and move, 1.6–1.8 ms for attribute, class and style, and 0.44–0.50 ms for text. The tree `Update` is 5.9–9.5 ms there, against a full `Build` of 7.4–9.9 ms. The empty `Commit()` takes 1.9 ns and allocates 0 B; `WorkingSnapshot.ToNode` takes 1.0 ns and allocates 0 B.

Reading the numbers: the cost of a flush does not grow with k up to 100, but it does grow with the list, because the snapshot is a full pre-order rebuild (about 27 ns per node) and the seeded restyle re-matches what the stylesheet's sibling and structural selectors reach (`.item + .item`, `:nth-child(odd)` and `:last-child` reach every following sibling of an inserted or removed row). For a single text, attribute, class or style change on 3,000 nodes a flush takes 0.14–0.52 ms. A structural change takes 1.6 ms on this deliberately sibling-heavy stylesheet. The tree `Update` is not faster than a `Build` at this size: 1.7–3.2 ms against 2.2–2.4 ms for a full `Build` of the same snapshot at 3,000 nodes (the update also converts the change set and carries names over, which costs about what the skipped name computations save, and its restyled-element list is long after structural edits). Treat it as correct and cheap on memory, not as a speed-up, until it is optimized. Optimizations the numbers point at, in order: patch-copying the previous snapshot's columns for commits with no structural edit (snapshot 82 µs → a few µs), narrowing the restyle of following siblings to the rules that read sibling position, and a tree update that avoids the full change-set conversion.
