Status: Partially implemented (incremental-invalidation-initial) Author: Claude Opus 4.6 Created: 2026-03-13 Tracking: v0.5 milestone (Project Roadmap)
Replace Donner's current full-tree recomputation model with incremental invalidation: when a DOM mutation (style change, attribute edit, tree insertion) occurs, only the affected elements and their dependents are recomputed. The system tracks dirty state at five levels — style, layout, shape, paint, and render instances — and propagates invalidation through the dependency graph so that each instantiateRenderTree() call does minimal work.
The incremental-invalidation-initial branch implements the first, intentionally narrow slice of this design:
The following work is explicitly not included in this branch:
Today, every call to RenderingContext::instantiateRenderTree() runs an 8-step pipeline that recomputes everything from scratch:
For a 1000-element document where one element's fill attribute changes, this recomputes all 1000 elements' styles, layouts, shapes, and paints. The actual changed element needs ~1ms of work; the full recomputation takes ~50ms.
The codebase already has per-system invalidation methods, but they're incomplete:
| Method | What it does | What it doesn't do |
|---|---|---|
| StyleSystem::invalidateComputed(handle) | Removes ComputedStyleComponent | Doesn't cascade to children that inherit |
| StyleSystem::invalidateAll(handle) | Removes style + marks for reparse | Doesn't cascade |
| LayoutSystem::invalidate(handle) | Clears cached viewBox/transforms | Doesn't cascade to descendants |
| SVGGeometryElement::invalidate() | Removes ComputedPathComponent | Doesn't invalidate paint/render |
| RenderingContext::invalidateRenderTree() | Clears ALL render instances | Nuclear option — no granularity |
The composited renderer (CompositedRenderer) already has fine-grained layer dirty tracking via markEntityDirty(Entity), markLayerDirty(uint32_t), and invalidateAnimatedLayers(). This design connects DOM mutations to that existing layer system.
Understanding which computations depend on which inputs is critical:
A single per-entity component tracks which aspects need recomputation:
Using a component (rather than a field on each computed component) keeps the data compact and allows efficient ECS queries: registry.view<DirtyFlagsComponent>() gives all entities that need work.
When a mutation occurs, dirty flags propagate according to these rules:
Optimization: Track which properties changed. If only opacity changed (non-inherited, no paint/filter impact), only mark RenderInstance dirty on E. If color changed (inherited), cascade Style to all descendants.
Transform changes cascade WorldTransform to all descendants because the absolute transform is the product of all ancestor transforms.
Tree structure changes are the most expensive because they affect draw order, which requires re-linearizing the render tree. This is inherently O(n) over the tree.
createComputedComponents() is modified to skip clean entities:
Each DOM mutation API marks the appropriate dirty flags and propagates:
The composited renderer already tracks per-layer dirty state. The incremental invalidation system feeds into it naturally:
This means a single-element style change results in:
vs. today's: recompute everything, re-rasterize everything.
The upcoming spatial grid (SpatialGrid in the interactivity system) needs updating when element geometry or transforms change. Elements with WorldTransform or Shape dirty flags need their spatial grid entries updated:
This integration is not included in the initial incremental-invalidation-initial branch. That branch is intentionally limited to DOM mutation dirty flags and the render-tree fast path. Spatial index maintenance remains follow-up work.
This is O(k) where k is the number of changed entities, vs. the current O(n) full rebuild.
Add the DirtyFlagsComponent and wire it into mutation entry points.
Phase 1 is implemented in the initial branch, but tree mutations currently cause a conservative full recomputation on the next render rather than a narrowly-scoped structural rebuild.
Implement cascading invalidation for inherited properties and transforms.
Modify StyleSystem to skip clean entities.
At this point the style stage has a selective path, but the rest of createComputedComponents() still falls back to whole-tree recomputation once anything is dirty.
The selective branch landed unreachable. RenderingContext::ensureComputedComponents() set RenderTreeState::needsFullStyleRecompute unconditionally immediately before calling createComputedComponents(), so StyleSystem::computeAllStyles() always took the whole-tree branch, discarded every ComputedStyleComponent, and recomputed the cascade for the entire document on any dirty entity. Only the unit tests that call computeAllStyles() directly ever exercised the selective branch.
The flag was guarding a real hazard rather than being redundant. Tearing down shadow trees destroys the cloned entities, and repopulating a main shadow-tree instance creates fresh clones that each carry an empty ComputedStyleComponent placeholder. Nothing marks those clones dirty, so the selective branch would skip them, and the paint/mask/marker pass that follows dereferences ComputedStyleComponent::properties on every entity it sees.
The fix marks the clones dirty where they are created, which is where the knowledge that they are new lives, and narrows the forced whole-tree restyle to the one case that still needs it: documents with active animation overrides. applyAnimationOverrides() writes animated presentation attributes directly into the cached computed styles, which is only sound while those styles are rebuilt from their unanimated base on every pass.
Closing the selective path also exposed a gap in the invalidation hooks: removing an element through the document mutation API requested a full rebuild but not a full restyle, which left the remaining siblings' structural selector matches (:nth-child, :empty, :first-child, sibling combinators) stale. Element removal now requests the whole-tree restyle.
Measured effect on the prepare phase for an incremental frame (parse, prepare once, then time the prepare that follows a single transform edit on a group; medians of five interleaved A/B rounds, -c opt, Linux aarch64):
| Document | Before | After | Delta |
|---|---|---|---|
| Ghostscript_Tiger (240 paths) | 3.44 ms | 1.62 ms | -53% |
| Synthetic, 10,003 elements with a class-selector stylesheet | 84.2 ms | 29.0 ms | -66% |
| The same synthetic document, plus a g[transform] rect rule | 88.4 ms | 91.5 ms | parity |
The third row is the fallback: once a stylesheet selects on the attribute being written, the edit takes the whole-tree restyle and the document performs as it did before. Interleaved in the order above it measured 6% slower, but re-running that document with the order reversed put the two at 91.5 ms and 91.5 ms, so the gap is measurement drift rather than a cost of the check.
The first prepare of a document is unchanged, as expected: it has never been able to use the selective branch, because no computed styles exist yet. Measured over the same rounds, 4.90 ms before and 4.89 ms after for Ghostscript_Tiger, 103.5 ms before and 104.0 ms after for the synthetic document, both within run-to-run noise.
Correctness is pinned by per-mutation-class equivalence tests in donner/svg/renderer/tests/RendererPublicApi_tests.cc: presentation attribute, transform, class, inline style, text content, structural insert, structural remove (including a structural selector case), and <use> retarget edits each require the incrementally rendered document to be byte-identical to a freshly parsed document in the same final state, with variants covering main shadow trees (<use>), offscreen shadow trees (clipPath, mask, pattern, marker) and an animated document.
The transform branch of trySetPresentationAttribute() is the one attribute write that stays on the selective pass, and it needs care: the value is stored in AttributesComponent, which is a live selector input, so [transform], [transform="..."] and combinators keyed on them can start or stop matching, on other elements as well as the written one. It therefore requests the whole-tree restyle when, and only when, a loaded stylesheet actually selects on that attribute. That question is answered from a per-stylesheet cache of the attribute names its selectors reference, computed in StylesheetComponent::parseStylesheet(), which every stylesheet load and mutation path funnels through. The cache is keyed by attribute name rather than being a single "uses any attribute selector" flag because the user agent stylesheet always contains one (*[xml|space=preserve]), which would set a single flag for every document and give back the whole win. SVGGraphicsElement::setTransform() writes no attribute, so the compositor's drag path never reaches this check at all.
Remaining over-approximation, deliberately left for a follow-up: SVGElement::setStyle(), updateStyle(), setClassName(), setId(), the generic-attribute path of setAttribute() and the non-transform branch of trySetPresentationAttribute() all request a whole-tree restyle unconditionally. That is correct but broader than necessary. Class, id and attribute edits can change selector matches on unrelated elements, so narrowing them in general needs the selector dependency index listed under Non-Goals; the cheaper move is to extend the per-attribute check above to the other presentation attributes, which would leave only genuinely selector-relevant writes on the whole-tree path.
A frame whose dirty set only moves content, changes its compositing, or points external <use> elements at another external instance now keeps every computed component and rebuilds only the render instances. RenderingContext::ensureComputedComponents() asks PlanRetainedUpdate() (donner/svg/renderer/RetainedRenderTreeUpdate.h) whether the dirty set qualifies before it starts the full rebuild. A qualifying frame:
Shadow trees are not torn down, styles of unchanged elements are not recomputed, and no external document is admitted again unless it or its resource families changed. The traversal still visits every rendered entity, so a retained frame costs O(rendered entities) with a small constant, not O(changed entities); patching instances in place is a possible next step.
The three qualifying changes and their marks:
| Change | Mutation path | Dirty flags |
|---|---|---|
| Transform write | SVGGraphicsElement::setTransform() | Layout, Transform, WorldTransform on the element; LayoutSystem::invalidate() drops the descendants' cached absolute transforms without flagging them |
| opacity attribute | trySetPresentationAttribute() | Style, Compositing, RenderInstance on the element and its descendants, whose computed styles are dropped (opacity: inherit); the element and its descendants are restyled through the selective style pass |
| External <use> retarget | setHref(), href / xlink:href writes | ShadowTree, RenderInstance, plus the layout flags |
| External <use> geometry | setX(), setY(), setWidth(), setHeight() | ShadowTree, RenderInstance, plus the layout flags: the instance is re-attached so that layer caches see a content change, not a move |
A transform attribute written through setAttribute() also marks Paint (an XML transform edit is a settled change that re-rasterizes filtered layers), so it takes the full rebuild, as does any transform write while a stylesheet selects on [transform].
opacity and href writes now request the whole-tree restyle only when a stylesheet selects on the attribute, as transform writes already did. An href write takes the retained path only when the use is presented, owns no shadow tree, and the new reference is external while the old one was external or absent; anything else keeps the previous InvalidateUseInstance() behaviour.
PlanRetainedUpdate() falls back to the full rebuild when any dirty entity carries another flag, or when one of these changes could reach a computed component:
External documents are admitted to the resource family at most once per full rebuild, however many uses reference them (ResourceManagerContext::loadAdmittedExternalSVG()). A use retargeted between rebuilds reuses that admission only while the loader generation and SubDocumentCache::admissionFingerprint() are unchanged: the admitted document's entity and payload size, and the identity, limit revision and membership revision of the families of both the host and the admitted document. A nested document of the admitted one that grew or changed families is re-checked only when the next full rebuild starts a new admission pass; until then, the memo also keeps the admitted documents referenced. Unchanged uses keep the documents they were given, as they did on frames with nothing dirty.
RenderTreeState::retainedUpdatesEnabled forces the full rebuild for tests and diagnostics, and RenderTreeState::counters records full rebuilds, retained updates, shadow-tree teardowns and in-place retargets. SubDocumentCache::cachedDocumentAdmissions() counts re-admissions of cached documents. Pixel identity against the full rebuild is pinned per change kind in donner/svg/renderer/tests/RetainedRenderTreeUpdate_tests.cc (ancestor transforms, nested uses, symbols, clip paths and masks in both unit systems, objectBoundingBox filters, markers, patterns, text, opacity, external sprites, ConcurrentDom), and the per-frame work of a game-like sprite field in SpriteFieldPrepareCorrectness_tests.cc. SpriteFieldPrepareWallclock_tests.cc reports prepare time with and without retained updates.
Measured with that test (-c opt, Apple Silicon, a shared and loaded machine, so the ratios are the signal): 150 external uses across 7 sheets, every use moving each frame plus a few retargets and an occasional fade, median host-document prepare 1.2 to 1.3 ms before this change (two runs), 0.23 ms on a full rebuild that admits each sheet once, and 0.16 ms with the retained update.
opacity writes take the retained path too: the written element and its descendants are restyled through the selective style pass, then the instances are rebuilt. CompositorController refuses a promotion while any entity still carries a pending Style dirty flag, as it already did while a whole-tree restyle or full rebuild was pending, so it never trusts styles or instances a pending attribute write made stale. Two cases keep the full rebuild: an opacity write on or above text, because text layout memoizes each span's opacity (which opacity: inherit ties to an ancestor), and opacity on a <stop>, which stays on the plain style path.
<use> geometry written through the DOM: the parser applies x, y, width and height through the typed setters, at override precedence, so a later setAttribute() of the same attribute was ignored and a referenced <symbol> or nested <svg> kept its old viewport. These writes now take the same precedence, and InvalidateUseGeometry() drops only the layout of a presented external use (its instance takes the viewport when it is drawn) and rebuilds the shadow tree of any other.
Modify LayoutSystem to skip clean entities.
Complete the incremental pipeline for remaining systems.
Connect incremental invalidation to the layer system.
Update the spatial grid incrementally instead of rebuilding.
This phase is out of scope for the initial branch created from this design. It should land as a separate follow-up once the core invalidation flow is in place and validated.
Shadow trees (created for <use>, <clipPath>, <mask>, <pattern>, <marker>) are cloned subtrees. When the source element changes, the shadow tree must be re-cloned. This is handled by the ShadowTree dirty flag — when set, the shadow tree is torn down and rebuilt from the (now-updated) source element.
Shadow tree invalidation is triggered when:
Fill and stroke can reference paint servers (<linearGradient>, <radialGradient>, <pattern>) by ID. When a paint server's content changes, all elements referencing it need Paint dirty. This requires a reverse reference map (paint server → referencing elements), which the PaintSystem can maintain.
The animation system already updates AnimatedValuesComponent per tick. With incremental invalidation, animation ticks should mark affected entities dirty:
This replaces the current invalidateRenderTree() call in SVGDocument::setTime(), which is a nuclear invalidation.
On the first render, no DirtyFlagsComponent exists on any entity. The incremental path must detect this and fall through to full recomputation. After the first render, all entities are clean (no DirtyFlagsComponent), and subsequent mutations add flags incrementally.
The 8-step pipeline has ordering dependencies:
The incremental path must respect these ordering constraints. Within each step, only dirty entities are processed, but steps still execute in order.
For a document with N elements and k dirty elements:
| Operation | Full recomputation | Incremental |
|---|---|---|
| Style resolution | O(N) | O(k + d) where d = inheriting descendants |
| Layout | O(N) | O(k) |
| Transform accumulation | O(N) | O(k + d) where d = descendants of changed |
| Shape decomposition | O(k_shapes) | O(k_shapes) (same — already per-element) |
| Paint resolution | O(N) | O(k) |
| Render instance update | O(N) | O(k) |
| Layer rasterization | O(dirty_layers × elements_per_layer) | Same |
For the common case (k=1, N=1000): ~1000x reduction in style/layout/paint work.