app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+344
View File
@@ -0,0 +1,344 @@
# 01 — GPUI, Zed Text & Rendering Architecture, and Warp's UI Framework (`warpui`)
**Sources inspected directly:**
- `kitlangton/gpui` (`gpui 0.2.2` + Kit's commit `2582af8`, "Fix Metal display link fallback and rendering quality")
- `zed-industries/zed` (`5447804`, Oct 2026) — `crates/gpui`, `crates/gpui_apple`, `crates/gpui_macos`, `crates/gpui_ios`, `crates/gpui_linux`, `crates/gpui_windows`, `crates/gpui_wgpu`, `crates/gpui_web`, `crates/sum_tree`, `crates/rope`, `crates/text`, `crates/multi_buffer`, `crates/editor`
- `warpdotdev/warp` (`f8a9c71`, Oct 2026) — `crates/warpui_core` (MIT), `crates/warpui` (MIT), and ["How Warp Works"](https://www.warp.dev/blog/how-warp-works)
- a private Mac launcher app, cited as `launcher/` (`docs/motion.md`, `docs/glass.md`, `docs/perf-log.md`, `docs/raycast-research.md`, `src/native_ui.rs`)
- `scrawl` (`src/native/pill/{mod.rs,model.rs,atlas.rs,pill.metal}`, `scrawl/perf/start-latency.md`)
---
## Executive Summary
1. **GPUI has grown into a 174k-LoC multi-crate platform engine (`gpui*` across 13 crates at Zed `5447804`), up from ~97k LoC in `gpui 0.2.2`.** Between `0.2.2` and Oct 2026, Zed split GPUI into `gpui` (101,878 LoC), `gpui_apple` (5,351 LoC, shared Metal + CoreText), `gpui_macos` (9,711 LoC), `gpui_ios` (3,684 LoC), `gpui_linux` (16,934 LoC), `gpui_windows` (14,798 LoC), `gpui_wgpu` (7,969 LoC, replacing `blade-graphics` and powering Linux + Web), and `gpui_web` (7,866 LoC, WASM + WebGPU/WebGL2 + Canvas2D fallback).
2. **GPUI's renderer is a flat 7-primitive batcher (`Shadow`, `Quad`, `Underline`, `MonochromeSprite`, `SubpixelSprite`, `PolychromeSprite`, `Path`, `Surface`) sorted by a 4-ary spatial R-tree (`BoundsTree`).** It achieves ~0.2–0.8 ms GPU encode/render times for typical editor frames by packing primitives into a single 64 KB-aligned `InstanceBuffer` (`crates/gpui_apple/src/metal_renderer.rs:58-77`) and merging non-overlapping draw batches across `DrawOrder` via `BoundsTree<Bounds<ScaledPixels>>` (`crates/gpui/src/bounds_tree.rs:14-18`, `MAX_CHILDREN = 4`).
3. **GPUI's biggest rendering weaknesses are full-window redraws, lack of offscreen layer/filter compositing, and synchronous window-resize barriers.** GPUI clears and redraws the entire window drawable every dirty frame (`MTLLoadAction::Clear`, no dirty-rect scissor damage). Its `AnyView::cached` mechanism (`crates/gpui/src/view.rs:258-312`, `crates/gpui/src/window.rs:4014-4123`) only skips *CPU* layout/prepaint/paint by replaying `Scene` slices (`Scene::replay`, `crates/gpui/src/scene.rs:208-274`). Worse, `Path` batches clear and resolve a full-viewport 4x MSAA intermediate texture on *every* path batch (`crates/gpui_apple/src/metal_renderer.rs:1100-1215`), and live window resizing sets `presentsWithTransaction = true` with `command_buffer.waitUntilScheduled()` on the main thread (`crates/gpui_apple/src/metal_renderer.rs:845-853`).
4. **Two of Kit's four `kitlangton/gpui` (`2582af8`) fixes are still missing in upstream Zed (`5447804`).** Upstream Zed now includes perceptual luminance-based glyph dilation (`glyph_dilation_for_color`, `crates/gpui_apple/src/text_system.rs:265-274, 510-516`) and triangular blue-noise gradient dithering (`gradient_color`, `crates/gpui_apple/src/shaders.metal:326-331`). However, upstream Zed **still** lacks Gaussian shadow dithering in `shadow_fragment` (`crates/gpui_apple/src/shaders.metal:472-502`), still leaves `CAMetalLayer` colorspace unconfigured when `use_display_p3` is false (`crates/gpui_apple/src/metal_renderer.rs:321-334`), and still lacks the `CVDisplayLinkCreateWithCGDisplay` fallback in `crates/gpui_macos/src/display_link.rs:28-56` (causing `kCVReturnInvalidDisplay = -6661` panics/failures on headless or asleep Mac Studio displays).
5. **GPUI's 3-phase `Element` pipeline (`request_layout` → `prepaint` → `paint`) + `EntityMap` lease model is ergonomic for static/editor UIs but brittle for choreographed motion and nested state.** Entities are leased out of a `SecondaryMap<EntityId, Box<dyn Any>>` onto the stack during `update` (`crates/gpui/src/app/entity_map.rs:138-233`), causing runtime `double_lease_panic` crashes whenever an observer, event callback, or AppKit delegate re-enters an entity currently being updated.
6. **Zed's text engine (`sum_tree` → `rope` → `text` → `multi_buffer` → `editor::display_map`) is best-in-class and cleanly decoupled from GPUI.** `SumTree<T>` (`crates/sum_tree/src/sum_tree.rs:18`, `TREE_BASE = 6`, 12 items/node) + `Chunk` (`crates/rope/src/chunk.rs:9-33`, 128-byte `ArrayString` with four `u128` bitmaps for `chars`, `chars_utf16`, `newlines`, `tabs`) provides $O(\log N)$ seek between UTF-8 bytes, UTF-16 code units, and `Point(row, col)` using hardware `popcnt`/`tzcnt`, and `LineLayoutCache` (`crates/gpui/src/text_system/line_layout.rs:458-560`) adds zero-allocation `shape_line_by_hash` (`crates/gpui/src/text_system.rs:689-720`).
7. **Upstream GPUI added `spring.rs`, `hot_reload.rs` (`subsecond`), `AccessKit` (`window/a11y.rs`), `gpui_ios`, and `gpui_web`, but animation remains a closure wrapper.** Even with `SpringAnimation` (`crates/gpui/src/spring.rs:1-214`), GPUI animations work by cloning and rebuilding the wrapped element subtree inside `request_layout` on every tick (`crates/gpui/src/elements/animation.rs:208-246`), with no persistent velocity across interrupted retargets, no off-main-thread compositor, and no GPU-property-only fast path.
8. **The launcher and Scrawl both hit hard architectural walls in GPUI and replaced GPUI windows with native AppKit/Core Animation/Metal surfaces.** The launcher's GPUI morph suffered 6 structural visual defects (`launcher/docs/motion.md:20-75`), 11–18 ms cold glyph/emoji stalls (`launcher/docs/perf-log.md:72-97`), and 641 µs `SyncList` re-measurements, leading it to move its panel to a `WindowServer`-composited `CASpringAnimation` + SwiftUI panel (`launcher/src/native_ui.rs`). Scrawl replaced GPUI's `HudPillWindow` with a 440-line 3-pass native `CAMetalLayer` + `NSGlassEffectView` renderer (`scrawl/src/native/pill/mod.rs:1-31`) to get offscreen blur/glow passes, sub-millisecond cold start (`0.08 ms` hidden init vs `6.93 ms` eager), and zero idle CPU.
9. **Warp's `warpui` (`crates/warpui_core` + `crates/warpui`, MIT-licensed in `warpdotdev/warp`) is GPUI v1's direct sibling—originally co-designed with Nathan Sobo in 2021.** Warp kept the retained `Presenter` + Flutter-style `SizeConstraint` `Element` tree while adding two notable innovations GPUI lacks: thread-local automatic dependency tracking via `Tracked<T>` (`crates/warpui_core/src/core/autotracking/mod.rs:1-200`, eliminating manual `cx.notify()`) and a dual GUI + Ratatui TUI presenter (`crates/warpui_core/src/presenter/tui.rs:1-150`). However, its rendering pipeline (3 shaders, shelf-next-fit atlas without eviction, no subpixel AA, no offscreen filter passes) is less capable than GPUI's.
10. **Recommendation for Rune: Do NOT fork GPUI (or `warpui`); build a fresh, modular architecture while stealing `sum_tree`/`rope`, `BoundsTree` batching, `etagere` + `LineLayoutCache`, and `kitlangton/gpui` (`2582af8`) shader/text refinements.** Forking GPUI locks Rune into a 174k-LoC monolithic `App`/`Window` god-object where fixing borrow-reentrancy, retained compositor layers, interruptible spring retargeting, offscreen filter graphs, and damage-tracked rendering requires rewriting the core anyway.
---
## 1. GPUI Renderer (`gpui`, `gpui_apple`, `gpui_wgpu`, `gpui_windows`)
### 1.1 Scene Representation & Batching (`crates/gpui/src/scene.rs`, `bounds_tree.rs`)
Every frame, GPUI's paint phase populates a flat `Scene` struct (`crates/gpui/src/scene.rs:34-46`):
```rust
pub struct Scene {
pub(crate) shadows: Vec<Shadow>,
pub(crate) quads: Vec<Quad>,
pub(crate) paths: Vec<Path<ScaledPixels>>,
pub(crate) underlines: Vec<Underline>,
pub(crate) monochrome_sprites: Vec<MonochromeSprite>,
pub(crate) subpixel_sprites: Vec<SubpixelSprite>,
pub(crate) polychrome_sprites: Vec<PolychromeSprite>,
pub(crate) surfaces: Vec<PaintSurface>,
layer_stack: Vec<DrawOrder>,
bounds_tree: BoundsTree<Bounds<ScaledPixels>>,
}
```
- **Spatial `DrawOrder` assignment via `BoundsTree`:** Instead of assigning monotonically increasing z-indices (which would break batching whenever a parent draws a quad, then text, then another sibling quad), `Scene::insert_primitive` queries `bounds_tree.insert(bounds)` (`crates/gpui/src/scene.rs:171-206`). `BoundsTree` (`crates/gpui/src/bounds_tree.rs:14-18`) is a custom 4-ary R-tree (`MAX_CHILDREN: usize = 4`) where each node stores the maximum `u32` ordering among its descendants. Querying the tree finds the highest `DrawOrder` of any *spatially intersecting* primitive already in the scene and assigns `max_overlapping_order + 1`. Non-overlapping primitives of the same kind therefore receive identical `DrawOrder`s (or sort adjacent to each other).
- **Finish & `PrimitiveBatch` iterator:** At the end of `Window::draw`, `Scene::finish()` (`crates/gpui/src/scene.rs:283-292`) sorts all 7 primitive vectors by `(draw_order, id)` using `.sort_unstable()`. During `present()`, `Scene::batches()` (`crates/gpui/src/scene.rs:299-415`) runs a 7-way merge iterator that coalesces contiguous primitives of the same kind (and same `AtlasTextureId` for sprites) into a single `PrimitiveBatch` instanced draw call.
- **Coordinate spaces:** Layout runs in logical `Pixels(f32)`, scene primitives are stored in `ScaledPixels(f32)` (`Pixels * scale_factor`), and atlas/rasterization coordinates use integer `DevicePixels(i32)` (`crates/gpui/src/scene.rs:10-25`).
### 1.2 Metal Backend (`crates/gpui_apple/src/metal_renderer.rs`, `shaders.metal`)
On macOS and iOS, `MetalRenderer` (`crates/gpui_apple/src/metal_renderer.rs:226-265`) renders into a `CAMetalLayer`:
- **Single-buffer instancing:** All per-frame instance data (`Quad`, `Shadow`, `Underline`, `MonochromeSprite`, `SubpixelSprite`, `PolychromeSprite`, `PathRasterizationVertex`, `PathSprite`) is bumped into one shared `InstanceBuffer` (`crates/gpui_apple/src/metal_renderer.rs:58-77`, default capacity `2 * 1024 * 1024` bytes = 2 MB, grown dynamically) with 64 KB-aligned sub-allocations (`align = 64 * 1024`). If the buffer overflows mid-frame, `draw()` returns `false`, doubles `instance_buffer_size`, and retries the command buffer encode (`crates/gpui_apple/src/metal_renderer.rs:483-509`).
- **Triple-buffered pool:** `InstanceBufferPool` (`crates/gpui_apple/src/metal_renderer.rs:79-121`) holds `max_buffers_in_flight = 3` (`CAMetalLayer.maximumDrawableCount = 3`), returning buffers to the pool in the `MTLCommandBuffer` completion handler block (`crates/gpui_apple/src/metal_renderer.rs:835-843`).
- **8 Render Pipeline States:**
1. `quads` (`quad_vertex` / `quad_fragment`, `crates/gpui_apple/src/shaders.metal:333-444`): SDF rounded rectangle with per-corner radii (`Corners<ScaledPixels>`), per-edge border widths (`Edges<ScaledPixels>`), dashed/solid border antialiasing, and solid/linear-gradient background fill (`BackgroundTag::Solid | LinearGradient | PatternSlash`).
2. `shadows` (`shadow_vertex` / `shadow_fragment`, `crates/gpui_apple/src/shaders.metal:446-502`): Analytic 4-step Gaussian integral of an SDF rounded box (`erf` approximation along X, 4-sample quadrature along Y).
3. `underlines` (`underline_vertex` / `underline_fragment`, `crates/gpui_apple/src/shaders.metal:551-621`): Straight or sine-wave (`wavy`) underlines.
4. `monochrome_sprites` (`monochrome_sprite_vertex` / `monochrome_sprite_fragment`, `crates/gpui_apple/src/shaders.metal:623-702`): Samples `R8Unorm` glyph/SVG masks from `MetalAtlas`, supports 2x2 `TransformationMatrix` (for rotated SVGs), and outputs premultiplied `HSLA -> linear/sRGB RGBA`.
5. `subpixel_sprites` (`subpixel_sprite_vertex` / `subpixel_sprite_fragment`, `crates/gpui_apple/src/shaders.metal:704-777`): Dual-source blending (`color(0), index(0)` and `color(0), index(1)`) with `Source1Color` blend factor for LCD subpixel text AA. (Note: disabled by default on macOS in `gpui_apple` where grayscale + luminance dilation is preferred, used on Windows/Linux).
6. `polychrome_sprites` (`polychrome_sprite_vertex` / `polychrome_sprite_fragment`, `crates/gpui_apple/src/shaders.metal:779-858`): `BGRA8Unorm` atlas tiles (color emojis, raster images) with SDF corner clipping, grayscale filter, and opacity.
7. `paths_rasterization` + `paths` (`path_rasterization_vertex`/`fragment` and `path_vertex`/`fragment`, `crates/gpui_apple/src/shaders.metal:504-549`): Arbitrary vector paths (`PathBuilder`, `crates/gpui/src/path_builder.rs:1-250`). Filled paths use Lyon (`lyon::tessellation::FillTessellator`) or Loop-Blinn quadratic curve UV coordinates (`st_position` in `PathVertex`); stroked paths use `lyon::tessellation::StrokeTessellator`.
8. `surfaces` (`surface_vertex` / `surface_fragment`, `crates/gpui_apple/src/shaders.metal:860-910`): Hardware-decoded `CVPixelBuffer` (`kCVPixelFormatType_420YpCbCr8BiPlanarFullRange`) YCbCr-to-RGB video surfaces via `CVMetalTextureCache`.
### 1.3 Severe Bottlenecks in GPUI's Renderer
1. **Path rendering allocates & clears a full-viewport 4x MSAA texture per path batch:** Look at `MetalRenderer::draw_paths_to_intermediate` (`crates/gpui_apple/src/metal_renderer.rs:1100-1215`). Every time `Scene::batches()` yields a `PrimitiveBatch::Paths` (which cannot be merged across an intervening `Quad` or `MonochromeSprite` if bounding boxes overlap), GPUI ends the main `MTLRenderCommandEncoder`, starts a new render pass on a **full-window** `path_sample_count = 4` MSAA texture + resolve texture (`MTLLoadAction::Clear` across the entire viewport, not just the path's bounding box!), renders the path triangles, ends the encoder, and starts a *new* main `MTLRenderCommandEncoder` with `MTLLoadAction::Load` to blit the resolved texture via `path_sprite`. Having N interleaved path layers in a frame triggers $2N + 1$ full render-pass switches and $N$ full-window 4x MSAA clears.
2. **No offscreen layer stack, backdrop filter, or group opacity:** `window.with_element_opacity(opacity, ...)` (`crates/gpui/src/window.rs:1249`) simply multiplies `element_opacity` into each individual quad/sprite color at CPU paint time. Overlapping children within a translucent container bleed through each other (Classic alpha-compositing bug) instead of compositing as a group. There is zero support for offscreen Gaussian blur, vibrancy, or shader post-processing passes—which is why Scrawl had to bypass GPUI for its glowing/blurred HUD pill (`scrawl/src/native/pill/mod.rs:1-31`).
3. **Full-window redraw every frame & `Scene::replay` limits:** GPUI has no dirty-rect scissor/damage tracking at the GPU level; `draw()` always runs `MTLLoadAction::Clear` on the full `CAMetalDrawable`. `Entity::cached` (`crates/gpui/src/view.rs:258`) + `Scene::replay` (`crates/gpui/src/scene.rs:208-274`) copies the previous frame's `Quad`/`MonochromeSprite` structs from `rendered_frame.scene` into `next_frame.scene` and re-inserts every primitive into `BoundsTree` on the CPU. If *any* animation ticks in a window, the entire window's `Scene` is re-sorted, re-uploaded to `InstanceBuffer`, and re-rendered by the GPU.
4. **Synchronous `presentsWithTransaction` stall during resize:** During window resize (`crates/gpui_macos/src/window.rs:3320-3341`), GPUI sets `renderer.set_presents_with_transaction(true)`, which forces `command_buffer.commit(); command_buffer.wait_until_scheduled(); drawable.present();` on the main thread (`crates/gpui_apple/src/metal_renderer.rs:845-853`).
### 1.4 Cross-Platform Renderers (`gpui_wgpu`, `gpui_windows`)
- **`gpui_wgpu` (`crates/gpui_wgpu/src/wgpu_renderer.rs:1-250`):** In `gpui 0.2.2`, Linux used `blade-graphics`. By Oct 2026 (`5447804`), Zed replaced `blade-graphics` with `gpui_wgpu` (7,969 LoC), which now powers **both** `gpui_linux` (Wayland + X11 via Vulkan/GL) and `gpui_web` (WebGPU + WebGL2 fallback). It implements the exact same 7-primitive pipeline in WGSL (`crates/gpui_wgpu/src/shaders.wgsl`) including dual-source blending (`wgpu::Features::DUAL_SOURCE_BLENDING`) when supported by the adapter (`crates/gpui_wgpu/src/wgpu_renderer.rs:150-166`), falling back to single-source alpha blending on WebGL2/uncooperative drivers.
- **`gpui_windows` (`crates/gpui_windows/src/directx_renderer.rs:1-200`):** Uses raw Direct3D 11 (`ID3D11Device`, `IDXGISwapChain1`) bound to `IDCompositionDevice` / `IDCompositionVisual` (`DirectComposition`) for transparent/acrylic window support and low-latency flip-model presentation, with 4x MSAA intermediate textures for paths (`PATH_MULTISAMPLE_COUNT = 4`, line 29) and HLSL shaders compiled at build time.
### 1.5 Texture Atlas (`etagere` in `crates/gpui_apple/src/metal_atlas.rs`)
`MetalAtlas` (`crates/gpui_apple/src/metal_atlas.rs:1-250`) wraps `etagere::BucketedAtlasAllocator`:
- Separate texture lists by `AtlasTextureKind`:
- `Monochrome` → `MTLPixelFormatR8Unorm` (glyphs, rasterized `resvg` SVGs)
- `Subpixel` → `MTLPixelFormatBGRA8Unorm`
- `Polychrome` → `MTLPixelFormatBGRA8Unorm` (color emojis, images)
- Starting page size: **1024×1024** for Monochrome/Subpixel, **2048×2048** for Polychrome (`crates/gpui_apple/src/metal_atlas.rs:138-145`), dynamically allocating additional `MTLTexture` pages when `etagere` fills up.
- Uploads happen synchronously on the CPU into `MTLStorageModeManaged` (Intel) or `MTLStorageModeShared` (Apple Silicon unified memory) via `replaceRegion_mipmapLevel_withBytes_bytesPerRow` (`crates/gpui_apple/src/metal_atlas.rs:265-285`).
### 1.6 Exact Diff Analysis: `kitlangton/gpui` (`2582af8`) vs Upstream Zed (`5447804`)
In `kitlangton/gpui`, commit `2582af8` ("Fix Metal display link fallback and rendering quality", 4 files changed, +127/-16 lines) fixed four concrete production bugs in `gpui 0.2.2`:
| Fix in `kitlangton/gpui` (`2582af8`) | How it works in `kitlangton/gpui` | Status in Upstream Zed (`5447804`, Oct 2026) |
|---|---|---|
| **1. `CVDisplayLink` fallback (`src/platform/mac/display_link.rs:25-60`)** | When `CVDisplayLinkCreateWithCGDisplay(display_id, ...)` fails with `kCVReturnInvalidDisplay` (`-6661`, common on headless/asleep displays or virtual displays), falls back to `CVDisplayLinkCreateWithActiveCGDisplays` and calls `CVDisplayLinkSetCurrentCGDisplay` best-effort. | **MISSING in upstream Zed.** `crates/gpui_macos/src/display_link.rs:28-56` still calls `CVDisplayLinkCreateWithCGDisplay` and immediately returns `Err` on non-zero `CVReturn`! Worse, `crates/gpui_macos/src/window.rs:839-845` skips starting the display link if `!occlusionState.contains(NSWindowOcclusionStateVisible)`, but `WindowFrameSource` still uses a 60 Hz `dispatch_source_create(DISPATCH_source_type_timer)` fallback only when occluded (`display_link.rs:240-310`). |
| **2. Explicit `sRGB` `CAMetalLayer` colorspace (`src/platform/mac/metal_renderer.rs:257-263`)** | Sets `layer.set_colorspace(CGColorSpaceCreateWithName(kCGColorSpaceSRGB))` on the `CAMetalLayer` so macOS WindowServer composites `BGRA8Unorm` in a deterministic sRGB color space instead of untagged device RGB. | **PARTIALLY MISSING in upstream Zed.** `crates/gpui_apple/src/metal_renderer.rs:321-334` only sets `kCGColorSpaceDisplayP3` when `use_display_p3()` is true (`colorspace` setting =P3) and sets `null()` when false, leaving default sRGB windows untagged! |
| **3. Gradient + Shadow dithering (`src/platform/mac/shaders.metal:326-331, 495-503`)** | Adds interleaved gradient noise `dither_noise(position)` (`fract(52.9829189 * fract(dot(position, float2(0.06711056, 0.00583715))))`) with triangular PDF `(n1 + n2 - 1.0) / 255.0` to **both** linear gradients (`gradient_color`) **and** `shadow_fragment` (scaled by `min(alpha * 2.0, 1.0)`), eliminating 8-bit Mach banding on dark glass/shadows. | **HALF-MERGED in upstream Zed.** `crates/gpui_apple/src/shaders.metal:326-331` has the exact same `gradient_color` triangular dither, **but `shadow_fragment` (`crates/gpui_apple/src/shaders.metal:472-502`) has NO dithering**, so subtle dark drop shadows still band in 8-bit `BGRA8Unorm`. |
| **4. Perceptual luminance glyph dilation (`src/platform/mac/text_system.rs:274-305, 514-525`)** | Replaces constant black-on-white CoreGraphics glyph rasterization (`set_gray_fill_color(0.0, 1.0)`) with 5 discrete dilation levels (`0..=4`) keyed in `RenderGlyphParams::dilation` based on perceptual luminance `(0.2126*R + 0.7152*G + 0.0722*B).sqrt()`, calling `cx.set_should_smooth_fonts(true)` + `cx.set_gray_fill_color(luminance, 1.0)` so light text on dark backgrounds gets native macOS stem thickening. | **MERGED in upstream Zed.** Present verbatim in `crates/gpui_apple/src/text_system.rs:265-274, 510-516` (`glyph_dilation_for_color`, `params.dilation as f64 * 0.25`). |
---
## 2. Element / View / Entity Model (`crates/gpui/src/{app.rs,view.rs,element.rs,window.rs}`)
### 2.1 Ownership & the `EntityMap` Lease Model (`crates/gpui/src/app/entity_map.rs`)
GPUI solves Rust's single-owner graph problem by making `App` the sole owner of all stateful models and views (`crates/gpui/src/_ownership_and_data_flow.rs:1-40`):
- `EntityMap` (`crates/gpui/src/app/entity_map.rs:56-60`) stores `entities: SecondaryMap<EntityId, Box<dyn Any>>` alongside `ref_counts: Arc<RwLock<EntityRefCounts>>` (a `SlotMap<EntityId, AtomicUsize>`).
- `Entity<T>` is a lightweight handle (`EntityId` + `Weak<RwLock<EntityRefCounts>>` + `PhantomData<T>`) that increments/decrements the atomic refcount on `Clone`/`Drop` and pushes zero-refcount IDs onto `dropped_entity_ids` (`crates/gpui/src/app/entity_map.rs:190-209`).
- **How `entity.update(cx, |this, cx| ...)` works:** `EntityMap::lease` (`crates/gpui/src/app/entity_map.rs:138-167, 219-227`) **physically removes** `Box<dyn Any>` from `self.entities` (`self.entities.remove(entity_id)`), moves it onto the call stack inside a `Lease<T>`, runs the closure with `(&mut T, &mut Context<T>)`, and re-inserts it in `end_lease` (`self.entities.insert(entity_id, entity)`).
- **The Re-Entrancy Footgun (`double_lease_panic`):** Because `lease` removes the `Box<dyn Any>` from `SecondaryMap`, *any* attempt to `.read(cx)` or `.update(cx)` that same `Entity<T>` while its `update` closure is still on the call stack hits `None` and panics at runtime (`crates/gpui/src/app/entity_map.rs:230-233`):
```rust
panic!("cannot {operation} {entity_type} while it is already being updated")
```
While `Context::notify()` and `Context::emit()` queue effects onto `App::pending_effects` (`VecDeque<Effect>`) and flush them in a loop only when the outermost `App::update` finishes, synchronous callbacks (such as window activation/appearance callbacks, focus listeners, or helper methods passed an `&mut App` that also hold an `Entity<Self>`) routinely trigger this panic. Note `crates/gpui/src/window.rs:1992-2000` where Zed itself had to spawn an async task on `foreground_executor` inside `on_appearance_changed` specifically to avoid a synchronous App borrow panic!
### 2.2 Views (`Render`), Components (`RenderOnce`), and the 3-Phase `Element` Pipeline
In GPUI (`crates/gpui/src/view.rs:197-247`, `crates/gpui/src/element.rs:1-520`):
- **Stateful Views (`impl Render for MyView`):** Hold persistent state in `Entity<MyView>`. Calling `cx.notify()` marks the `EntityId` dirty in `window.dirty_views` (`crates/gpui/src/window.rs:2265-2275`).
- **Stateless Components (`#[derive(IntoElement)] impl RenderOnce for MyButton`):** Consumed by value (`fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement`) each frame.
- **3-Phase `Element` Trait (`crates/gpui/src/element.rs:50-145`):**
1. **`request_layout(&mut self, global_id, inspector_id, window, cx) -> (LayoutId, Self::RequestLayoutState)`:** Builds the Taffy layout tree (`TaffyLayoutEngine`, `crates/gpui/src/taffy.rs:31-107`, which wraps `taffy::TaffyTree` with `taffy.disable_rounding()` and custom pixel-snapping in `compute_layout`). Views call `Render::render` during this phase (or during `prepaint` if cached).
2. **`prepaint(&mut self, global_id, inspector_id, bounds, request_layout, window, cx) -> Self::PrepaintState`:** Runs **after** Taffy solves `compute_layout` at the root (`crates/gpui/src/window.rs:3721-3728`). Every element now knows its resolved `Bounds<Pixels>`. Elements register `Hitbox`es (`window.insert_hitbox`), push `DispatchNode`s into `DispatchTree` for keyboard/action routing, build `AccessKit` nodes if a screen reader is active (`crates/gpui/src/element.rs:428-463`), and shape text lines.
3. **`paint(&mut self, global_id, inspector_id, bounds, request_layout, prepaint, window, cx)`:** Runs after `self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position)` (`crates/gpui/src/window.rs:3758`). Because hit-testing happens *between* `prepaint` and `paint`, elements can query `hitbox.is_hovered(window)` during `paint` and emit hover colors/cursors on the same frame without a 1-frame lag! Elements push primitives into `window.next_frame.scene` and register mouse listeners (`window.on_mouse_event`).
- **`ElementArena` (`crates/gpui/src/arena.rs`, `window.rs:395-476`):** `AnyElement` boxes are bump-allocated into a per-`App` `Arena` (cleared at the end of `window.draw(cx)` via `arena_clear_needed.clear(cx)`, `crates/gpui/src/window.rs:1910-1912`) so constructing thousands of `Div`/`Svg`/`Canvas` elements per frame does not hit the system allocator.
- **Cross-frame Element State (`GlobalElementId`):** Elements with an explicit `.id(...)` push onto `window.element_id_stack` (`ElementIdStack`, `crates/gpui/src/window.rs:1023`), forming a path-hashed `GlobalElementId` (`crates/gpui/src/element.rs:250-285`). `window.with_element_state::<S, _>(global_id, ...)` moves state from `rendered_frame.element_states` (`FxHashMap<(GlobalElementId, TypeId), ElementStateBox>`) into `next_frame.element_states` (`crates/gpui/src/window.rs:1203-1210`). Unvisited state is automatically dropped at frame end (immediate-mode GC).
- **View Caching (`Entity::cached`, `crates/gpui/src/view.rs:258, 484-643`):** Opt-in only (`entity.cached(style)`), requiring a caller-supplied definite `StyleRefinement` because GPUI skips calling `Render::render` during `request_layout`! During `prepaint_view` (`view.rs:546-561`), if `bounds`, `content_mask`, and `text_style` match the previous frame and `!window.dirty_views.contains(&entity_id)`, GPUI calls `window.reuse_prepaint` and `window.reuse_paint` (`crates/gpui/src/window.rs:4014-4123`), which slice-clones hitboxes, mouse listeners, dispatch tree nodes, line layouts, and `Scene` primitives from `rendered_frame` into `next_frame`. **Pain point:** Notice comments at `window.rs:3463-3500` and `3893-3900`—because `reuse_prepaint`/`reuse_paint` rely on fragile index ranges (`Range<PrepaintStateIndex>`, `Range<PaintIndex>`) into flat `Frame` vectors, any mutation that shifts vector indices (such as nested `deferred_draws` or `.pop()` on `input_handlers`) corrupts cached subtrees and panics!
### 2.3 Focus, Actions, and Keybinding Dispatch (`crates/gpui/src/key_dispatch.rs`)
- **`FocusHandle` & `FocusId` (`crates/gpui/src/window.rs:543-726`):** Ref-counted slotmap key owned by `App::focus_handles`. During `prepaint`, `.track_focus(&focus_handle)` attaches a `FocusId` to the current `DispatchNode` in `DispatchTree` (`crates/gpui/src/key_dispatch.rs:220-224`).
- **`DispatchTree` & `KeyContext` (`crates/gpui/src/key_dispatch.rs:71-250`):** Every frame builds a tree of `DispatchNode`s mirroring the element hierarchy. Each node can hold a `KeyContext` (e.g., `"Editor && mode == full"`), `focus_id`, `key_listeners`, and `action_listeners` (`TypeId` → closure).
- **Capture & Bubble Phases:** When a keystroke arrives, `DispatchTree::dispatch_key` computes the `focus_path` from the root `DispatchNode` down to the focused `FocusId`, matches single-key or multi-key chord sequences (`"cmd-k left"`) against the `Keymap` from deepest context to root, and dispatches the resulting `Action` (`Capture` phase top-down, then `Bubble` phase bottom-up).
---
## 3. Text & Layout System (`crates/gpui/src/text_system.rs`, `sum_tree`, `rope`, `text`, `multi_buffer`)
### 3.1 Platform Shaping & Rasterization Backends
GPUI abstracts platform text shaping behind `PlatformTextSystem` (`crates/gpui/src/platform.rs`):
1. **macOS & iOS (`AppleTextSystem`, `crates/gpui_apple/src/text_system.rs:1-749`):**
- Uses `font-kit` for font loading/metrics and Apple **CoreText** (`CTLine::new_with_attributed_string`, `crates/gpui_apple/src/text_system.rs:540-636`) for shaping.
- **Ligature-breaking trick across syntax runs (`crates/gpui_apple/src/text_system.rs:567-579`):** Because CoreText shapes an entire `CFAttributedString` at once and will form ligatures across adjacent syntax tokens if their attributes are identical, GPUI alternates `px(f32::from(font_size).next_up())` (1 ULP float increment!) on adjacent `FontRun`s (`break_ligature = !break_ligature`) so CoreText breaks ligatures at token boundaries (e.g. when a cursor or selection splits `!=`).
- **Subpixel positioning & Dilation (`crates/gpui_apple/src/text_system.rs:480-537`):** Rasterizes glyphs into an 8-bit grayscale `CGContext` (or 32-bit RGBA premultiplied for color emojis, swapped to straight-alpha BGRA) with `SUBPIXEL_VARIANTS_X = 4, SUBPIXEL_VARIANTS_Y = 1` (`crates/gpui/src/text_system.rs:49-52`), shifting the glyph origin by `subpixel_variant / 4.0` device pixels and applying 5-step luminance dilation (`0.0..=1.0` gray fill color with `set_should_smooth_fonts(true)`).
2. **Linux & Web (`CosmicTextSystem`, `crates/gpui_wgpu/src/cosmic_text_system.rs:1-200`):**
- Uses `cosmic-text` (`FontSystem`, `ShapeLine`, `ShapeBuffer` — which uses `rustybuzz` / HarfBuzz under the hood) for shaping and `swash` (`ScaleContext`) for subpixel-positioned glyph/emoji rasterization.
- On `gpui_web` (`crates/gpui_web/src/text_system.rs:1-200`), `WebTextSystem` wraps `CosmicTextSystem` (loaded with embedded fonts) and adds a **Canvas2D fallback** (`CanvasFontFallback`) that measures and rasterizes missing CJK/emoji glyphs via the browser's native `<canvas>` 2D context using system fonts!
3. **Windows (`DirectWriteTextSystem`, `crates/gpui_windows/src/direct_write.rs:1-200`):**
- Uses `IDWriteFactory5`, `IDWriteTextAnalyzer1`, and `IDWriteFontFallback` for shaping, ClearType subpixel rendering with gamma/contrast tables (`DirectXRenderer::get_font_info`, `directx_renderer.rs:32-37`), and a dedicated Direct3D 11 shader pass (`ShaderModule::EmojiRasterization`, `direct_write.rs:63-165`) to rasterize layered COLRv0/COLRv1/DirectWrite color glyphs into the atlas.
### 3.2 `LineLayoutCache` & Zero-Allocation Hash Lookups (`crates/gpui/src/text_system/line_layout.rs:458-560`)
- `LineLayoutCache` maintains two `FrameCache` maps (`previous_frame` and `current_frame`). Every shaped line is looked up in `current_frame`; on miss, it checks `previous_frame`, moves the `Arc<LineLayout>` into `current_frame` if found, or calls `platform_text_system.layout_line(...)` on miss. At `finish_frame()`, `previous_frame` is replaced by `current_frame`, automatically evicting any line layout that wasn't used in the frame just drawn.
- **`shape_line_by_hash` (`crates/gpui/src/text_system.rs:689-720`):** Added in recent Zed so the editor can hash rope chunks + `FontRun`s and hit `lines_by_hash` *without* allocating a contiguous `SharedString` per visible line on every frame.
### 3.3 Zed's Rope, `SumTree`, CRDT `Buffer`, `MultiBuffer`, and `DisplayMap`
Zed's text architecture is a layered tower of immutable, persistent, `Arc`-shared B+ trees (`crates/sum_tree/src/sum_tree.rs:1-200`):
```
[ DisplayMap ] ← Highlighting + BlockMap (diagnostics/creases)
↑
[ WrapMap ] ← Soft-wrapping transforms (SumTree<WrapTransform>)
↑
[ TabMap ] ← Hard-tab expansion transforms
↑
[ FoldMap ] ← Code folding transforms (SumTree<FoldTransform>)
↑
[ InlayMap ] ← LSP inlay hints injected without mutating buffer
↑
[ MultiBuffer ] ← Excerpts from 1..N buffers (SumTree<Excerpt>) — powers project search & split diffs
↑
[ text::Buffer ] ← CRDT operation log, Lamport anchors, UndoMap, SumTree<Fragment>
↑
[ rope::Rope ] ← SumTree<Chunk> (128-byte ArrayString + 4x u128 bitmaps)
```
1. **`SumTree<T: Item>` (`crates/sum_tree/src/sum_tree.rs:18`):** A copy-on-write B+ tree (`Arc<Node<T>>`) with `TREE_BASE = 6` (up to $2 \times 6 = 12$ child pointers or leaf items per node). Every internal node caches a `Summary` (monoid with `zero()` and `add_summary()`) for each child. A single `SumTree` can be indexed and binary-searched (`cursor.seek(&target, Bias::Left)`) along **any `Dimension<'a, S>`** derived from `S` in $O(\log_{12} N)$ time, and cloned in $O(1)$ (`Arc::clone`) for background threads!
2. **`rope::Rope` & `Chunk` (`crates/rope/src/{rope.rs,chunk.rs}`):**
- `Rope` is simply `SumTree<Chunk>` (`crates/rope/src/rope.rs:26-28`).
- Each leaf `Chunk` (`crates/rope/src/chunk.rs:9-33`) holds an inline `ArrayString<128, u8>` (`MAX_BASE = 128`, `MIN_BASE = 64`) plus **four `u128` bitmaps** (1 bit per byte of the 128-byte chunk!):
- `chars: u128` — bit $i$ is 1 iff `text[i]` is a UTF-8 code point start byte.
- `chars_utf16: u128` — bit $i$ is 1 for every UTF-8 start byte, *plus* bit $i+1$ is 1 for 4-byte UTF-8 sequences ($\ge 240$, which take 2 UTF-16 code units). Thus `(chars_utf16 & mask).count_ones()` gives the exact UTF-16 offset in 1 CPU instruction!
- `newlines: u128` — bit $i$ is 1 iff `text[i] == b'\n'`.
- `tabs: u128` — bit $i$ is 1 iff `text[i] == b'\t'`.
- Each node summarizes `TextSummary { len: usize, chars: usize, len_utf16: OffsetUtf16, lines: Point, first_line_chars: u32, last_line_chars: u32, last_line_len_utf16: u32, longest_row: u32, longest_row_chars: u32 }`. Converting between byte offset, `Point(row, column)`, and LSP `PointUtf16(row, utf16_col)` descends the `SumTree` to the 128-byte `Chunk` and uses bitwise mask + `count_ones()` (`popcnt`) / `leading_zeros()` (`lzcnt`)—no linear byte scanning.
3. **`text::Buffer` & `Anchor` (`crates/text/src/{text.rs,anchor.rs}`):**
- Implements an operation-based CRDT (`BufferSnapshot`, `crates/text/src/text.rs:113-124`) backed by `visible_text: Rope`, `deleted_text: Rope`, `fragments: SumTree<Fragment>`, and `insertions: SumTree<InsertionFragment>`.
- `Anchor` (`Lamport` timestamp + offset within insertion fragment + `Bias`) survives arbitrary concurrent local and remote edits and resolves back to a byte/`Point` offset in $O(\log N)$ via `fragments`.
4. **`multi_buffer::MultiBuffer` (`crates/multi_buffer/src/multi_buffer.rs:74-93`):**
- Presents either a single `Buffer` (`singleton: true`) or a `SumTree<Excerpt>` stitching slices from multiple `Buffer`s into one unified coordinate space (`MultiBufferRow`, `MultiBufferPoint`, `Anchor`). Every Zed editor view—single file, multibuffer project search results, inline git diff hunks, and split diffs—renders a `MultiBuffer`.
5. **`editor::DisplayMap` (`crates/editor/src/display_map.rs:1-145`):**
- A 5-layer pipeline (`InlayMap` → `FoldMap` → `TabMap` → `WrapMap` → `BlockMap`) where each layer is a `SumTree<Transform>` with `TransformSummary { input: TextSummary, output: TextSummary }`. Incrementally synced via `Patch<T>` (`Edit<InputDim>` → `Edit<OutputDim>`), allowing soft-wrapping (`WrapMap` runs asynchronously on a background thread when lines exceed a threshold), code folding, inlay hints, and inline diagnostic/AI blocks without mutating the underlying `MultiBuffer`.
### 3.4 IME & Accessibility Integration
- **macOS `NSTextInputClient` (`crates/gpui_macos/src/window.rs:236-270, 3368-3587`):** Implemented via Objective-C runtime class registration on `GPUIView`, forwarding `insertText:replacementRange:`, `setMarkedText:selectedRange:replacementRange:`, `unmarkText`, `firstRectForCharacterRange:actualRange:`, and `characterIndexForPoint:` to the active element's `PlatformInputHandler` (registered during `paint` via `window.handle_input(&focus_handle, handler, cx)`).
- **iOS `UITextInput` (`crates/gpui_ios/src/ios/text_input.rs:129-200`):** Implemented via a hidden responder `GPUITextInputView` subclassing `UIView` with custom `GPUITextPosition`, `GPUITextRange`, and `GPUITextSelectionRect` classes.
- **Web `ImeMirror` (`crates/gpui_web/src/window.rs:57, 70-86`):** Synchronizes a hidden DOM `<textarea>` (`ImeMirror`) with the canvas caret.
- **Accessibility (`crates/gpui/src/window/a11y.rs`, `crates/gpui/src/_accessibility.rs`):** Recently added `AccessKit` integration (`accesskit::TreeUpdate` built lazily during `prepaint` only when `window.a11y.is_active()` is true, `crates/gpui/src/window.rs:3691-3694, 3790-3815`, using `GlobalElementId::accesskit_node_id()`, `crates/gpui/src/element.rs:253-255, 428-463`).
---
## 4. Animation, Platform Layer, Hot Reload, and Real-World Failure Modes
### 4.1 Animation Architecture (`crates/gpui/src/elements/animation.rs`, `spring.rs`)
- **In `gpui 0.2.2` (`kitlangton/gpui`):** Only time-based `Animation { duration, oneshot, easing: Rc<dyn Fn(f32) -> f32> }` (`ease_in_out`, `cubic_bezier`, `pulsating_between`, `bounce`).
- **In Zed `5447804` (`crates/gpui/src/spring.rs:1-214`):** Upstream Zed added an analytic underdamped/critically-damped/overdamped harmonic oscillator solver (`SpringConfig { stiffness, damping, mass }`, presets `SpringConfig::snappy()` = stiffness 400 / damping 30, `bouncy()` = 300 / 15, `smooth()` = 200 / 25) and `SpringAnimation<T: Interpolatable>` (`f32`, `Pixels`, `Point<Pixels>`, `Size<Pixels>`, `Hsla`).
- **Why GPUI's animation model is still fundamentally limited:**
1. **Immediate-mode subtree cloning on every tick:** Look at `AnimationElement::request_layout` (`crates/gpui/src/elements/animation.rs:208-246`) and `SpringElement::request_layout` (`crates/gpui/src/spring.rs:410-465`). On every frame while an animation is active, GPUI clones the underlying element (`self.element.clone()`), calls the user's animator closure `animator(element, delta)`, schedules `window.request_animation_frame()`, and runs full **Taffy `request_layout` → `prepaint` → `paint` → full-window `Scene` sort → GPU clear & redraw**.
2. **No velocity preservation on retargeting:** `SpringAnimation` (`crates/gpui/src/spring.rs:165-195`) computes position analytically from `(from, to, start: Instant)` with zero initial velocity ($\dot{x}(0) = 0$). If `to` changes mid-flight (interruptible UI interaction), resetting the spring discards current velocity $\dot{x}(t)$ instead of integrating or solving the initial-value problem with non-zero $v_0$.
3. **Main-thread bound:** Because animations run inside `Window::draw` via `next_frame_callbacks` (`crates/gpui/src/window.rs:1878-1887`), any main-thread hitch (even 8.4 ms on a 120 Hz ProMotion display) drops frames across every animation in the window.
### 4.2 Why the Launcher and Scrawl Had to Bypass GPUI
Kit's own production apps (the launcher and `scrawl`) provide the most concrete empirical evidence of where GPUI breaks down:
#### Case Study A: The launcher (`launcher/docs/{motion.md,perf-log.md}`)
The launcher originally built its panel and compact pill morph in GPUI (`kitlangton/gpui`) and hit two walls:
1. **Six structural motion/compositing defects (`launcher/docs/motion.md:20-75`):**
- *Two competing coordinate spaces:* Moving/resizing the `NSWindow` via AppKit (`window.resize()`) while rendering the inner pill inside GPUI's `Scene` caused 1-frame desynchronization ("two systems fighting over the same pixels").
- *Top-left anchor jump on collapse:* Switching from the expanded 680×424 window to the compact 100×36 pill caused the pill to render at `(0,0)` (top-left of the large window) for 1–2 frames before `NSWindow::setFrame:` took effect.
- *Hard content pop & background snap:* Because GPUI cannot cross-fade two retained view snapshots as offscreen textures with independent scale/blur transforms, the search bar and results list popped out in 1 frame (`Frame 12 → Frame 13`), and background alpha snapped (`0.95 → 0.30`).
- *Fix in the launcher:* The launcher replaced the GPUI morph and launcher panel with native AppKit/SwiftUI (`launcher/src/native_ui.rs:1-99`) using a single `NSGlassEffectView` / `CAMetalLayer` driven by `CASpringAnimation` in `WindowServer` at a locked 120 Hz with zero per-frame Rust/CPU participation.
2. **Measured GPUI CPU frame times & cold-glyph spikes (`launcher/docs/perf-log.md:1-145`):**
- Steady-state GPUI `Window::draw` CPU frame time (cached): **2.65 ms** before optimization, **1.46 ms** after removing per-row `SyncList` re-measurement (**641 µs/frame** wasted re-measuring row 0) and `TextInput` re-layout (**266 µs/frame**).
- **Cold glyph/emoji rasterization spikes:** Opening the Emoji grid in GPUI caused **11.1–18.4 ms** frame spikes (2.2× the 8.33 ms 120 Hz budget) because `AppleTextSystem::rasterize_glyph` (`crates/gpui_apple/src/text_system.rs:435-537`) synchronously allocates a `CGContext`, renders the `CTFont` glyph on the CPU main thread, and uploads to `MetalAtlas` during `paint`.
- **Memory footprint:** Even an idle GPUI window with `MetalRenderer` (3× 2 MB `InstanceBuffer`s + `MetalAtlas` pages + font caches) consumed **78.8 MB RSS** at launch (`launcher/docs/perf-log.md:135`).
#### Case Study B: Scrawl (`scrawl/src/native/pill/mod.rs`, `scrawl/perf/start-latency.md`)
Scrawl's HUD pill needs a liquid-glass capsule (`NSGlassEffectView`), an offscreen Gaussian-blurred waveform glow (`glow_a`, `glow_b` intermediate `RGBA8Unorm` textures), and 120 Hz spring animations:
- GPUI's `Scene` cannot express multi-pass offscreen blur (`Pass 1: Clear glow_a` → `Pass 2: H-blur glow_a -> glow_b` → `Pass 3: Composite V-blurred glow_b + SDF shapes + R8 atlas text onto drawable`, `scrawl/src/native/pill/mod.rs:11-23`).
- Scrawl replaced GPUI's `HudPillWindow` with a 440-line native `NSPanel` + `CAMetalLayer` + `CVDisplayLink` module (`scrawl/src/native/pill/{mod.rs,model.rs,atlas.rs,pill.metal}`).
- **Measured startup win (`scrawl/perf/start-latency.md:26-35`):** Deferring `NSPanel`/`CAMetalLayer`/pipeline creation until the pill is shown cut `HudPillHandle::spawn()` cold-start latency from **6.93 ms** to **0.08 ms** (an **86×** reduction), and the display link fully stops (`CVDisplayLinkStop`) when idle for **0% CPU/GPU usage**.
### 4.3 Mobile (`gpui_ios`), Web (`gpui_web`), Hot Reload (`subsecond`), and Compile Times
- **`gpui_ios` (`crates/gpui_ios/src/ios/{window.rs,text_input.rs}`, 3,684 LoC):** Uses `objc2-ui-kit` (`UIWindow`, `UIViewController`, `GPUIMetalView` with `CAMetalLayer`, `CADisplayLink`, `UIPanGestureRecognizer`, `UIScreenEdgePanGestureRecognizer` for back-swipe, and `GPUITextInputView` implementing `UITextInput`). Still early: `TouchEvent` in `crates/gpui/src/interactive.rs:114-117` explicitly notes *"Dispatch contract (core implementation pending)"*.
- **`gpui_web` (`crates/gpui_web/src/{window.rs,text_system.rs}`, 7,866 LoC):** Runs GPUI in WASM on a full-bleed `<canvas>` using `gpui_wgpu` (`WebGPU` or `WebGL2`), `ResizeObserver`, `requestAnimationFrame`, `ImeMirror`, and `WebTextSystem` (`CosmicTextSystem` + `<canvas>` 2D fallback for system CJK/emoji fonts).
- **Hot Reload (`crates/gpui/src/hot_reload.rs:1-82`, `crates/gpui/src/view.rs:344-352`):** Compiled when `--cfg gpui_hot_reload` is active. Integrates Dioxus's **`subsecond`** binary hot-patching crate (`dx serve --hot-patch`). Every `ViewElement` render passes through `subsecond::HotFn::current(render_view_impl::<V>).call((view, window, cx))` (`crates/gpui/src/view.rs:351`), and when `subsecond` applies a jump-table patch, `hot_reload::register` marks all views in all windows dirty and calls `window.refresh()`.
- **Compile-time & Dependency Weight:** `gpui` + platform crates total **174,157 LoC** and pull in heavy transitive dependencies (`taffy`, `lyon`, `resvg`/`usvg`, `etagere`, `cosmic-text`/`swash`/`fontdb`, `font-kit`, `accesskit`, `wgpu`/`naga`, `objc2-*`/`windows`, `blade-macros`). Clean builds of `gpui` take ~25–45s on Apple Silicon M-series Max/Ultra, and incremental links without `subsecond` or `lld`/`wild` take 2–6s.
---
## 5. Warp's UI Framework (`warpui_core` + `warpui`)
### 5.1 Shared Genealogy with GPUI & Open-Source Status
In Warp's July 2021 engineering post (["How Warp Works"](https://www.warp.dev/blog/how-warp-works)), Warp explained that they partnered with **Nathan Sobo** (before he left to co-found Zed) to build a Flutter-inspired Rust UI framework on top of Metal and `SumTree`. As of 2026, `warpdotdev/warp` (`f8a9c71`) is open-source on GitHub: the terminal application is AGPL-3.0, while **`crates/warpui_core` (91,602 LoC) and `crates/warpui` (38,862 LoC) are MIT-licensed** (`crates/warpui_core/Cargo.toml:7`, `crates/warpui/Cargo.toml:7`).
Studying `warpui_core` side-by-side with `gpui` reveals that **`warpui` is the evolutionary sibling of GPUI v1**:
- Both share `App` / `AppContext`, `EntityId`, `ViewHandle<V>` / `ModelHandle<M>`, `Action`, hierarchical `Keymap` context matching, `Scene`, and `sum_tree`.
- Where Zed rewrote GPUI v1 into GPUI v2 (replacing Flutter constraints with Taffy flexbox and replacing retained `Box<dyn Element>` trees with 3-phase arena-allocated immediate/retained elements), Warp kept and evolved the original `Presenter` architecture.
### 5.2 How `warpui` Differs from GPUI v2
1. **Retained `Box<dyn Element>` per View (`Presenter`, `crates/warpui_core/src/presenter.rs:28-37, 318-381`):**
- `Presenter` holds `rendered_views: EntityIdMap<Box<dyn Element>>`.
- When a view is invalidated, `Presenter::invalidate` calls `app.render_view(window_id, view_id)` **only** on the invalidated `view_id`s and replaces their `Box<dyn Element>` in `rendered_views` (`presenter.rs:318-331`). Unchanged child views are embedded via `ChildView<T>` (`presenter.rs:282-287`) and never re-run `View::render`!
- Layout is single-pass Flutter-style box constraints (`Element::layout(&mut self, constraint: SizeConstraint, ctx: &mut LayoutContext, app: &AppContext) -> Vector2F`, `crates/warpui_core/src/elements/gui/mod.rs:109-115`), followed by `after_layout` and `paint`.
2. **Thread-Local Automatic Dependency Tracking (`Tracked<T>`, `crates/warpui_core/src/core/autotracking/mod.rs:1-200`):**
- Unlike GPUI (where forgetting `cx.observe(&model, ...)` or `cx.notify()` is a constant source of stale-UI bugs), `warpui_core` provides `Tracked<T>`.
- During `View::render`, `autotracking::render_view` sets a thread-local `CACHE.rendering_view = Some(View { window_id, view_id })` (`autotracking/mod.rs:174-192`).
- Reading a `Tracked<T>` via `Deref` automatically records `(View, TrackedId)` in a bidirectional `HashMap`. Mutating a `Tracked<T>` via `DerefMut` automatically pushes all dependent `View`s into `CACHE.invalidations`, which `App` drains alongside manual `ctx.notify()` calls!
3. **3-Primitive Renderer (`Rect`, `Image`/`Icon`, `Glyph`) + `rstar::RTree` Hit Map (`crates/warpui_core/src/scene.rs:29-123`):**
- `warpui` has **no** vector path tessellator (`lyon`) and **no** separate shadow or underline pipeline. Instead, `Rect` (`crates/warpui/src/platform/mac/rendering/metal/shaders/shaders.metal:9-43, 117-200`) evaluates drop shadow (4-step Gaussian `erf`), per-corner radius, per-edge solid/dashed border, and linear gradient inside a **single uber-fragment shader** (`rect_fragment_shader`)!
- Icons and SVGs are rasterized once via `resvg` into `TextureCache` and drawn via `image_fragment_shader`.
- Glyphs (`glyph_fragment_shader`) support horizontal alpha fades (`GlyphFade::Horizontal { start, end }`, `scene.rs:78-83`) so overflowing terminal/tab text fades out smoothly in the shader without extra mask layers.
- Each `Layer` in `Scene` builds an `rstar::RTree<Rectangle>` (`scene.rs:31`) of opaque hit rects so `EventContext::is_covered(point)` and `visible_rect(origin, size)` can test z-layer occlusion during event dispatch (`presenter.rs:246-258`).
- **Weakness:** `warpui`'s glyph atlas (`crates/warpui/src/rendering/atlas/allocator.rs:13-55`) is a naive shelf-next-fit allocator (`ATLAS_SIZE = 1024`) with **zero eviction**—when `GlyphConfig` changes it blows away all textures (`glyph_cache.rs:80-86`), otherwise it allocates new 1024×1024 `MTLTexture`s forever.
4. **Dual GUI + Ratatui TUI Runtime (`crates/warpui_core/src/presenter/tui.rs:1-150`):**
- Enabled via `--features tui` (`ratatui = "0.30"`). Allows the exact same `App`, `Model`, `EntityId`, `Action`, and `Keymap` core to render either to a GPU window (`Presenter` → `Scene`) or to a terminal screen (`TuiPresenter` → `TuiFrame` cell buffer).
5. **Platform Split:**
- macOS uses custom AppKit + raw Metal (`crates/warpui/src/platform/mac/rendering/metal/renderer.rs:1-200`), reporting **1.9 ms average redraw time (>144 FPS on 4K)** in Warp's telemetry.
- Linux, Windows, and WASM use `winit` + `wgpu` + `cosmic-text`/`swash` (`crates/warpui/src/windowing/winit/` and `crates/warpui/src/rendering/wgpu/renderer.rs:1-145`).
---
## 6. What to Steal vs. What to Avoid
### Steal (With Exact File Citations)
1. **Zed's `sum_tree` + `rope` (`Chunk` with 4× `u128` bitmaps):**
- *Source:* `zed:crates/sum_tree/src/sum_tree.rs:18-200` and `zed:crates/rope/src/{rope.rs,chunk.rs:9-102}`.
- *Why:* Self-contained (7,765 LoC combined for `sum_tree` + `rope`), zero GPUI dependency, $O(1)$ clone (`Arc`), $O(\log_{12} N)$ multi-dimensional seek across byte/char/UTF-16/`Point(row, col)`, and hardware-accelerated `popcnt`/`tzcnt` within 128-byte leaf chunks. Use it directly or vendor it verbatim for Rune's text buffers and virtualized list height prefix sums.
2. **`BoundsTree` Spatial Z-Order Assignment for Instanced Batching:**
- *Source:* `zed:crates/gpui/src/bounds_tree.rs:14-180` and `zed:crates/gpui/src/scene.rs:171-206`.
- *Why:* A ~200-line 4-ary R-tree that assigns each primitive `max_overlapping_order + 1` instead of a global counter. This turns painter's-algorithm trees (e.g. 100 list rows each drawing a background quad + icon + text) into 3 instanced GPU draw calls instead of 300.
3. **Kit's GPUI fork (`kitlangton/gpui`) (`2582af8`) Rendering & DisplayLink Fixes:**
- *Source:* `kitlangton/gpui` commit `2582af8`:
- Triangular blue-noise dithering in **both** gradients and Gaussian drop shadows (`src/platform/mac/shaders.metal:326-331, 495-503`).
- Perceptual luminance-driven 5-step CoreText glyph dilation (`src/platform/mac/text_system.rs:274-305, 514-525`).
- Explicit `kCGColorSpaceSRGB` (or `kCGColorSpaceExtendedSRGB` / `DisplayP3`) tagging on `CAMetalLayer` (`src/platform/mac/metal_renderer.rs:257-263`).
- `CVDisplayLinkCreateWithCGDisplay` → `CVDisplayLinkCreateWithActiveCGDisplays` fallback (`src/platform/mac/display_link.rs:25-60`) + complete stop when idle (`scrawl/src/native/pill/mod.rs:310-340`).
4. **Two-Generation `LineLayoutCache` + `shape_line_by_hash` + Ligature-Breaking ULP Trick:**
- *Source:* `zed:crates/gpui/src/text_system/line_layout.rs:458-560`, `zed:crates/gpui/src/text_system.rs:689-720`, `zed:crates/gpui_apple/src/text_system.rs:567-579`.
- *Why:* Swapping `current_frame` and `previous_frame` `FxHashMap`s gives zero-overhead frame-to-frame layout retention and automatic eviction of offscreen lines without LRU bookkeeping, while `px(font_size.next_up())` cleanly breaks CoreText ligatures across syntax/selection boundaries.
5. **Hit-Testing Between `prepaint` (Layout Resolved) and `paint`:**
- *Source:* `zed:crates/gpui/src/window.rs:3728-3765`.
- *Why:* Running `hit_test(mouse_position)` immediately after layout/hitbox registration—before `paint`—means hover states and cursors are always 0-frame-lag accurate even when layout shifts under the cursor.
6. **Warp's `Tracked<T>` Automatic Dependency Tracking & `GlyphFade`:**
- *Source:* `warp:crates/warpui_core/src/core/autotracking/mod.rs:1-200` and `warp:crates/warpui_core/src/scene.rs:78-89`.
- *Why:* Automatic read-tracking during `render` eliminates forgotten `cx.notify()` / `cx.observe()` bugs; shader-level horizontal `GlyphFade` clips overflowing text with a smooth gradient at zero extra draw-call or mask-texture cost.
7. **Dioxus `subsecond` Jump-Table Hot Patching Hook at View Boundaries:**
- *Source:* `zed:crates/gpui/src/hot_reload.rs:1-82` and `zed:crates/gpui/src/view.rs:344-352`.
- *Why:* Wrapping view render functions in `subsecond::HotFn::current(...)` gives sub-second Rust UI hot-reloading while preserving live `App`/entity state.
### Avoid (With Concrete Reasons)
1. **Avoid GPUI's Full-Viewport 4x MSAA Intermediate Pass per `Path` Batch:**
- *Where:* `zed:crates/gpui_apple/src/metal_renderer.rs:1100-1215`.
- *Why:* Clearing and resolving a full-window 4x MSAA texture on every interleaved path batch destroys tile memory bandwidth. Either render vector shapes via analytical SDFs / Vello / slug-style compute shaders, or scissor-clip the MSAA resolve to the tight union of the batch's `Bounds`.
2. **Avoid GPUI's `EntityMap` Remove-on-Lease Pattern Without Granular State Splits:**
- *Where:* `zed:crates/gpui/src/app/entity_map.rs:138-233`.
- *Why:* Leasing an entire view/model out of `SecondaryMap` guarantees runtime `double_lease_panic` crashes whenever nested callbacks, observers, or OS delegates fire synchronously. Fine-grained reactive signals/atoms or split state cells avoid whole-view lease panics.
3. **Avoid Animation-by-Element-Subtree-Rebuild (`AnimationElement` / `SpringElement`):**
- *Where:* `zed:crates/gpui/src/elements/animation.rs:208-246` and `zed:crates/gpui/src/spring.rs:410-465`.
- *Why:* Cloning the element subtree and re-running Taffy layout + full-window CPU/GPU draw on every 120 Hz tick wastes CPU and prevents compositor-level transform/opacity/filter animations. Springs must also preserve velocity $(\dot{x}_0 \ne 0)$ on retargeting.
4. **Avoid Lack of Offscreen Compositor Layers / Filter Passes:**
- *Where:* `zed:crates/gpui/src/scene.rs:34-46`.
- *Why:* Without offscreen layer targets (`RenderLayer` with group opacity, transform matrix, clip mask, Gaussian blur, and blend mode), you cannot build Scrawl-grade glass morphs, cross-dissolving view transitions, or glow passes without dropping down to raw `CAMetalLayer` / `CALayer`.
5. **Avoid Fragile Vector-Slice Index Caching (`reuse_prepaint` / `reuse_paint`):**
- *Where:* `zed:crates/gpui/src/window.rs:4003-4123` and `zed:crates/gpui/src/view.rs:540-642`.
- *Why:* Caching views by recording `(start_idx..end_idx)` slices into global per-frame vectors breaks whenever deferred draws or input handlers shift indices, and still forces the CPU to copy primitives and rebuild `BoundsTree` every frame. Retain per-view display lists (`RenderNode` / `Layer`) directly!
6. **Avoid Synchronous Main-Thread Glyph/Emoji Rasterization Without Prewarming/Async Staging:**
- *Where:* `zed:crates/gpui_apple/src/text_system.rs:435-537` (`launcher/docs/perf-log.md:72-97`).
- *Why:* Cold CoreText/CGContext rasterization of 50+ emojis stalls the main thread for **11–18 ms**, blowing past the 8.33 ms 120 Hz budget.
---
## 7. Recommendation for Rune
### Decisive Verdict: Build Fresh (Modular Crate Architecture) — Do NOT Fork GPUI or `warpui`
**Rune should NOT fork GPUI (neither `gpui 0.2.2` nor Zed HEAD `5447804`) and should NOT fork `warpui`.** Instead, Rune should **build a fresh, layered UI & rendering engine** while directly vendoring/adapting Zed's standalone text crates (`sum_tree`, `rope`) and porting ~1,500 lines of proven low-level algorithms (`BoundsTree`, `etagere` atlas + `LineLayoutCache`, and `kitlangton/gpui` `2582af8` shader/text refinements).
#### Why Starting Fresh Beats Forking GPUI
1. **The 4 architectural walls that forced the launcher and Scrawl off GPUI are load-bearing in GPUI's core:**
- In GPUI, `Window` (`crates/gpui/src/window.rs`, 9,979 LoC) + `App` (`crates/gpui/src/app.rs`) + `Scene` (`crates/gpui/src/scene.rs`) are tightly coupled around a **single-pass, flat-vector, full-window-clear** frame loop.
- Adding **retained compositor layers** (group opacity, 2D/3D layer transforms, offscreen blur/glow render passes like Scrawl's 3-pass HUD pill, and cross-fade view transitions like the launcher's morph), **damage-tracked partial redraws**, **velocity-preserving retargetable springs**, and **fine-grained reactive state that doesn't panic on re-entrant borrows** requires replacing `Scene`, `MetalRenderer::draw`, `ViewElementState`, `AnimationElement`, and `EntityMap`—i.e., rewriting the heart of GPUI while fighting 174,157 lines of Zed-specific coupling.
2. **Massive complexity and compile-time tax for features Rune doesn't want:**
- Upstream GPUI is 174k LoC (and growing rapidly for Zed's specific IDE needs). Maintaining a fork of GPUI (as `kitlangton/gpui` already demonstrated) means either freezing on an old snapshot (`0.2.2`, losing `gpui_wgpu`, `gpui_ios`, `gpui_web`, `AccessKit`, `subsecond`) or rebasing against thousands of Zed-internal commits per month.
3. **The highest-leverage parts of Zed are already small and separable:**
- `sum_tree` (3,327 LoC) + `rope` (4,438 LoC) have **zero** dependency on `gpui`.
- `BoundsTree` is 240 LoC; `MetalAtlas` (`etagere`) is 405 LoC; `shaders.metal` (with `2582af8` fixes) is 910 LoC; `LineLayoutCache` is ~300 LoC. You can bring all of GPUI's best engineering into Rune in **<10,000 LoC** without inheriting the 165,000 LoC of baggage.
### Rejected Alternatives & Why
1. **Rejected Alternative 1: Forking `kitlangton/gpui` (`gpui 0.2.2` + `2582af8`)**
- *Why rejected:* `gpui 0.2.2` is a 97k-LoC monolithic crate frozen before Zed's `gpui_apple`/`gpui_wgpu`/`gpui_ios`/`gpui_web`/`AccessKit`/`subsecond` work. It still suffers from the 11–18 ms cold emoji stalls, 78.8 MB idle RSS, `double_lease_panic` re-entrancy, lack of offscreen passes, and full-window redraws that forced the launcher and Scrawl to write native SwiftUI/Metal escape hatches.
2. **Rejected Alternative 2: Tracking Upstream Zed's `gpui` (`5447804`) as a Git Dependency or Rebased Fork**
- *Why rejected:* Upstream `gpui` is not published as a stable independent product—its APIs churn weekly to serve Zed, it still lacks two of Kit's `2582af8` fixes (shadow dithering and `CVDisplayLink` fallback), and its flat `Scene` + `InstanceBuffer` architecture still cannot do offscreen blur/glow passes, compositor-driven morphs, or partial-damage rendering.
3. **Rejected Alternative 3: Forking Warp's `warpui_core` + `warpui` (`f8a9c71`, MIT)**
- *Why rejected:* Although MIT-licensed and possessing nice ideas (`Tracked<T>`, 3-shader simplicity, Ratatui TUI backend), `warpui` is 130,464 LoC of 2021-era GPUI-v1 architecture with custom Flutter-style layout (no CSS Grid/Taffy), a naive shelf-next-fit glyph atlas with no eviction, no subpixel AA or luminance glyph dilation, and heavy Warp-specific telemetry/asset coupling.
---
## 8. Open Questions for Rune's Design
1. **Compositor Layer Hybrid vs. Pure GPU Scene:** Should Rune's window compositor use native `CALayer` / `CAMetalLayer` sublayers for window-level glass/morph surfaces (like the launcher and Scrawl proved on macOS via `NSGlassEffectView` + `WindowServer` `CASpringAnimation`) while running a multi-pass GPU scene graph inside each surface, or should Rune implement its own multi-pass offscreen layer compositor across all platforms?
2. **Vector Path Rendering Strategy:** Since GPUI's Lyon + 4x MSAA full-window intermediate pass is a major bottleneck and `warpui` skips arbitrary paths entirely, should Rune restrict UI primitives to analytical SDFs + `resvg` sprite caching, or adopt a tile-based GPU path rasterizer?
3. **Reactive State Model:** Should Rune adopt `warpui`-style automatic read tracking (`Tracked<T>` / fine-grained signals) so views never need manual `cx.notify()` and never hit `double_lease_panic` on re-entrant reads, or keep explicit entity handles with split read/write arenas?
4. **Text Buffer Scope:** Does Rune only need `sum_tree` + `rope` + single-buffer undo/anchors (~10k LoC), or does it also need Zed's full `multi_buffer` + 5-layer `DisplayMap` (`InlayMap` → `FoldMap` → `TabMap` → `WrapMap` → `BlockMap`) for code-editor-class views?
+274
View File
@@ -0,0 +1,274 @@
# 02 — Rust UI Ecosystem & Shared Foundation Survey (2025–2026)
## Executive Summary
- **The Rust UI ecosystem has split cleanly into a shared low-level foundation and diverging high-level paradigms.** Across otherwise competing frameworks, text, layout, geometry, and accessibility have converged onto the same crates: `taffy` (layout), `parley` + `fontique` + `harfrust` + `skrifa` (text discovery, shaping, metrics/outlines), `kurbo` + `peniko` + `color` (2D geometry and styling), and `accesskit` (platform accessibility). Even `egui` 0.37 migrated `epaint` onto `fontique` + `harfrust` + `skrifa` + `vello_cpu` (`egui/crates/epaint/Cargo.toml:88-100`).
- **Linebender pivoted Vello from compute-only to Sparse Strips (`vello_cpu` + `vello_gpu`).** In 2026, the original compute-shader renderer (`vello` 0.8.0, 26k+ LOC of WGSL/Rust) was moved into `research/vello_research/` (`vello/ARCHITECTURE.md:5-31`). The active production path is **Sparse Strips** (`vello_common` 0.3, `vello_cpu` 0.3, and `vello_gpu` 0.3—renamed from `vello_hybrid` on 2026-10-02 in `vello/vello_gpu/CHANGELOG.md:9-19`), which tiles paths into 4×N strip spans on the CPU using `fearless_simd` and rasterizes/composites via either multithreaded SIMD CPU pipelines or universal vertex/fragment GPU shaders (including WebGL2 and tile-based mobile GPUs where compute shaders hit driver bugs and memory limits).
- **Makepad 2.0 (`dev` branch, 2026) is the most relevant prior art for Rune's live-tuning and agent-driven thesis.** Makepad replaced its legacy `live_design!` macro with **Splash (`script_mod!`)**, a reactive bytecode VM (`makepad-script`, `makepad/platform/script/Cargo.toml:1-12`) whose blocks are hot-extracted directly from `.rs` source files on disk without recompiling (`makepad/platform/src/live_reload.rs:144-179`). It also shipped a built-in HTTP `--remote` agent control protocol (`/snap`, `/g`, `/gseq`, `/click`, `if_user_seq` in `makepad/platform/src/remote.rs:1-42`, `makepad/docs/agents/app-remote.md:1-120`), a live visual `/tweak` inspector that writes layout edits back to Rust source lines (`makepad/widgets/families/tweaker/src/tweaker.rs:1-50`), a GPU **Slug** quadratic-Bezier text renderer for crisp large glyphs (`makepad/draw/src/text/slug_atlas.rs:1-45`), and inertia/spring scroll physics (`makepad/widgets/src/scroll_motion.rs:1-40`).
- **GPUI v0.2 and `gpui-component` (`gpui-kit` 0.8) prove that a custom 2D UI Uber-shader beats generic vector renderers for desktop apps, but raw GPUI lacks ergonomic primitives.** GPUI renders a small fixed set of UI primitives (`Quad`, `Shadow`, `Path`, `Underline`, `MonochromeSprite`, `PolychromeSprite`) in a single batchable GPU pass (`zed/crates/gpui/src/scene.rs:1-120`) and added `subsecond` hot-reloading (`zed/crates/gpui/Cargo.toml:50-56`). Longbridge's `gpui-kit` (`gpui-base` + `gpui-component` + `gpui-shell`) supplies the missing 75+ accessible controls, headless UI integration tests, and tested AI coding recipes (`gpui-component/README.md:13-51`, `gpui-component/docs/ARCHITECTURE.md:18-48`).
- **Dioxus 0.7 / Blitz 0.3 and Subsecond changed the Rust iteration speed curve.** `subsecond` binary hot-patching is now embedded across Dioxus (`dioxus/packages/devtools/Cargo.toml:19`), GPUI (`zed/crates/gpui/Cargo.toml:55`), and Freya (`freya/crates/freya-core/Cargo.toml:62`), enabling sub-second Rust view function patching without losing state. Meanwhile, `dioxus-native` renders HTML/CSS natively via Servo's `stylo` + `taffy` + `parley` + `anyrender` (`vello_hybrid`/`vello_cpu`/`skia`) without a WebView (`dioxus/packages/native/Cargo.toml:13-88`).
- **Iced 0.14 / 0.15-dev matured its runtime and developer tooling (`comet`, `iced_test`, `lilt` animations, `cargo-hot`), while Slint 1.19 added an embedded MCP server (`SLINT_MCP_PORT`).** However, Iced still lacks merged upstream `accesskit` support in `iced` master (`iced/Cargo.toml:25-94`), and Slint's `.slint` DSL splits application logic across two languages under a dual GPLv3/commercial license (`slint/Cargo.toml:83`).
- **Animation, audio, and multi-sensory polish remain third-class citizens across almost every Rust UI crate.** Only Makepad (`Animator` + shader-driven state tracks + `scroll_motion.rs`), Iced (`iced_core::animation::Animation` backed by `lilt` 0.8), GPUI (frame-interpolated `AnimationElement`), and Floem (reactive keyframe/spring transitions) provide built-in animation primitives—and none treat interruptible 2D/3D spring velocities, layout-transition FLIP morphing, or procedural UI audio synthesis as core primitives.
- **Decisive Recommendation for Rune:** Do **not** build a font parser, shaper, bidi/line-breaker, CSS Flexbox/Grid solver, or OS accessibility bridge. Depend on **`taffy`**, **`parley`** (which brings **`fontique`**, **`harfrust`**, **`skrifa`**, **`read-fonts`**, and **`icu4x`**), **`kurbo`**, **`peniko`**, **`color`**, and **`accesskit`**. Use **`vello_cpu` / `vello_gpu`** only for complex arbitrary SVG/vector path layers (`AnyRender`-style escape hatch), while building Rune's **primary UI compositor and custom SDF/box-shadow/material/spring-animated quad pipeline directly on `wgpu`** (the GPUI / Makepad model) alongside a **Splash/Knobs-style hot-tunable parameter + agent inspection layer**.
---
## 1. The Linebender Stack (`Xilem`, `Masonry`, `Vello`, `Parley`, `Fontations`, `HarfRust`, `AccessKit`, `Kurbo`, `Peniko`)
In Q1 2026, Linebender core authors Raph Levien and Daniel McNab joined Canva while continuing open-source stewardship of the Linebender stack. By October 2026, Linebender's modular crates have become the de facto lower-half standard of the Rust UI ecosystem.
### 1.1 `Xilem` (0.4.0) & `Masonry` (0.4.0)
- **Architecture & State Model:** Linebender separates its reactive view tree (`xilem_core` / `xilem_masonry`) from its retained widget tree (`masonry_core` / `masonry`) (`xilem/ARCHITECTURE.md:1-60`).
- **`xilem_core::View`** (`xilem/xilem_core/src/view.rs:53-103`) is a lightweight, statically typed, short-lived description parameterized by `(State, Action, Context)` with two associated types—`type Element: ViewElement` and `type ViewState`—and four core methods: `build`, `rebuild(prev, view_state, ctx, element, app_state)`, `teardown`, and `message`. Because widget sequences are typed as nested tuples implementing `ViewSequence`, tree diffing is statically monomorphized with zero heap allocation or dynamic dispatch on unchanged subtrees (`memoize`).
- **`masonry_core::core::Widget`** (`xilem/masonry_core/src/core/widget.rs:140-260`) is the retained, mutable object layer stored inside `WidgetPod`s with generational `WidgetId(NonZeroU64)` handles (`widget.rs:42`). Widgets receive explicit lifecycle passes: `on_pointer_event`, `on_text_event`, `on_access_event`, `on_anim_frame`, `update`, `measure`, `layout`, `compose`, `paint`, and `accessibility` (`widget.rs:115-123`).
- **Renderer Approach:** In 2026 (`v0.4.0`), Masonry decoupled itself from hardcoding `vello` by introducing the `imaging` painter abstraction (`xilem/Cargo.toml:98-103`, `masonry_core/src/core/widget.rs:20`), allowing Masonry windows to render via `imaging_vello`, `imaging_vello_hybrid`, `imaging_vello_cpu`, or `imaging_skia`.
- **Layout:** Masonry 0.4 replaced its legacy Druid box constraints with an explicit `measure` + `layout` + `compose` pass (`widget.rs:121`). Separate `compose` passes allow scroll/transform updates to reposition children without re-running layout.
- **Accessibility & Testing:** First-class `accesskit` 0.24 integration (`xilem/Cargo.toml:90`). Every widget implements `accessibility(&mut self, ctx: &mut AccessCtx, props: &PropertiesRef, node: &mut accesskit::Node)` (`widget.rs:122`). `masonry_testing` provides a headless test harness that drives pointer/text/accessibility events and snapshots rendered output.
- **Weaknesses:** Deeply nested tuple types in `Xilem` can produce multi-screen compiler errors if `ViewMarker` / `Action` types mismatch, and `Xilem` does not yet expose declarative spring/layout-transition animations (`on_anim_frame` in `widget.rs:206-211` is manual per-frame nanosecond delta stepping).
### 1.2 `Vello` (0.8.0 Research vs. Sparse Strips `vello_cpu` 0.3.0 & `vello_gpu` 0.3.0)
The most consequential architectural shift in Rust 2D graphics during 2025–2026 occurred inside `linebender/vello`:
- **Why Linebender pivoted from Compute Vello to Sparse Strips:**
- The original **`vello`** crate (`v0.8.0`, now relocated to `research/vello_research/` per `vello/ARCHITECTURE.md:5-31`) is a full GPU compute-shader pipeline (`pathtag_reduce`, `bbox_clear`, `flatten`, `tile_alloc`, `coarse`, `fine` in `wgpu` compute shaders).
- While compute Vello excels on high-end desktop GPUs for massive vector scenes (e.g., Paris map SVG with 100k+ paths), it suffered severe production blockers for general UI and mobile/web deployment (`vello/vello_gpu/README.md:84-90`, `vello/vello_gpu/CHANGELOG.md:105-145`):
1. **Mobile GPU driver bugs & tile-memory limits:** Android Adreno and ARM Mali GPUs (e.g., Mali-G52) exhibited driver compilation failures, workgroup shared-memory exhaustion, and pipeline stalls on complex compute prefix-scans.
2. **No WebGL2 / Downlevel support:** Compute shaders require full WebGPU/Vulkan/Metal/DX12 compute queues, ruling out WebGL2 browsers and older GLES devices.
3. **Unbounded GPU buffer pre-allocation:** Complex paths could overflow fixed transient bump buffers mid-frame.
4. **Excessive shader compilation startup latency & binary footprint.**
- **The Sparse Strips Architecture (`vello_common` 0.3, `vello_cpu` 0.3, `vello_gpu` 0.3):**
- Developed from Laurenz Stampfl's 2025 ETH Zürich thesis (*High-performance 2D graphics rendering on the CPU using sparse strips*, cited in `vello/vello_cpu/README.md:169`), Sparse Strips splits rendering into:
1. **CPU Path Flattening & 4×N Strip Tiling (`vello_common`):** Flattens `kurbo::BezPath` curves and packs anti-aliased alpha coverage into compact 4-pixel-tall horizontal strip spans (`vello/vello_common/Cargo.toml:1-31`).
2. **`vello_cpu` (0.3.0):** Rasterizes and composites those strips entirely on the CPU using portable explicit SIMD via `fearless_simd` 1.0 (`NEON` on aarch64, `AVX2`/`SSE4.2` on x86_64, `wasm32` SIMD128) with two selectable pipelines: `u8_pipeline` (`RenderMode::OptimizeSpeed`) and `f32_pipeline` (`RenderMode::OptimizeQuality`), plus optional multithreaded tiling (`vello/vello_cpu/README.md:113-136`).
3. **`vello_gpu` (0.3.0, formerly `vello_hybrid` until 2026-10-02):** Performs path flattening and strip generation on the CPU, uploads the tiny strip buffer to the GPU, and performs strip rasterization, image sampling, gradients, clip masks, andblurred rounded rects in standard **vertex + fragment shaders** over `wgpu` 29 or `webgl2` (`vello/vello_gpu/README.md:29-66`, `vello/vello_gpu/CHANGELOG.md:9-48`).
4. **`glifo` (0.4.0):** Shared glyph run preparation and atlas caching crate sitting atop `vello_common` and `skrifa` (`vello/glifo/Cargo.toml:1-35`).
- **Performance & Status (Oct 2026):**
- `vello_cpu` (`u8_pipeline` + `fearless_simd`) achieves sub-millisecond to low-single-digit-millisecond frame times for typical UI scenes on Apple Silicon and x86_64 (`https://laurenzv.github.io/vello_chart/`, cited in `vello/vello_cpu/README.md:159-164`), making it fast enough that `egui` 0.37 adopted `vello_cpu` as its built-in glyph/color-emoji rasterizer (`egui/crates/epaint/Cargo.toml:41,100`).
- `vello_gpu` 0.3.0 explicitly validates against Adreno, Mali-G52 (`max_textures_per_shader_stage = 16`), Apple Silicon Metal, Vulkan, DX12, and WebGL2 (`vello/vello_gpu/CHANGELOG.md:36-46, 118-137`), though complex filter graphs and non-isolated blend modes are still unimplemented (`vello/vello_gpu/README.md:94-96`).
### 1.3 `Parley` (0.12.0), `Fontations` (`skrifa` 0.49 / `read-fonts` 0.46), and `HarfRust` (0.14.0)
- **The Pure-Rust Text Stack:**
- **`fontations` (`read-fonts` 0.46 + `skrifa` 0.49):** Google Fonts' memory-safe replacement for FreeType, shipped in production Chrome and Android (`fontations/Cargo.toml:25-73`). Provides zero-copy OpenType table parsing, variable font variation axis interpolation, TrueType/CFF hinting (`autohint`), glyph metrics, outline extraction (`kurbo`), and `COLR`v0/v1 color glyph painting.
- **`harfrust` (0.14.0):** Official HarfBuzz team port of the complete HarfBuzz OpenType shaping engine to safe Rust built directly on `read-fonts` (`harfrust/Cargo.toml:5-27`). Replaces `rustybuzz` with upstream parity and active Google Fonts backing.
- **`fontique` (0.12.0):** System font enumeration, font fallback per script/locale, and generic family resolution (`parley/Cargo.toml:45`).
- **`parley` (0.12.0):** Rich text layout engine combining `fontique`, `harfrust`, `skrifa`, and `icu4x` (`icu_properties`, `icu_segmenter`, `unicode-bidi`) for bidirectional text reordering, script segmentation, dictionary/UAX#14 line breaking (`complex-scripts` feature), inline boxes, and cursor/selection hit-testing (`parley/parley/Cargo.toml:16-51`).
- **Important 2026 Split (`parley` vs `parley_engine`):** In 0.12, Parley split out `parley_engine` and `parlance` (`parley/parley/Cargo.toml:38-39`) so frameworks that want to manage their own style caching can drive the layout engine without Parley's high-level `LayoutContext` wrapper.
### 1.4 `Kurbo` (0.13.1), `Peniko` (0.6.1), `Color` (0.3.3), and `AccessKit` (0.25.1)
- **`kurbo` (0.13.1):** `#![forbid(unsafe_code)]`, `no_std`-capable 2D curve and geometry library (`Point`, `Vec2`, `Size`, `Rect`, `RoundedRect`, `Affine`, `BezPath`, cubic/quadratic flattening, stroke expansion, dash patterns, tight bounding boxes) (`kurbo/Cargo.toml:10-36`).
- **`peniko` (0.6.1) & `color` (0.3.3):** Shared vocabulary types (`Brush`, `Gradient`, `ImageBrush`, `BlendMode`, `Fill`, `FontData`, `Blob` via `linebender_resource_handle`) plus CSS Color 4 color spaces (`Oklab`, `Oklch`, `DisplayP3`, `Srgb`, `PremulRgba8` interpolation) (`peniko/peniko/Cargo.toml:34-38`).
- **`accesskit` (0.25.1):** Cross-platform accessibility tree diffing (`TreeUpdate`, `Node`, `Role`, `ActionRequest`) with native adapters for **macOS (`NSAccessibility`)**, **iOS (`UIAccessibility`)**, **Windows (`UIAutomation`)**, **Linux (`AT-SPI` via D-Bus)**, and **Android (`AccessibilityNodeProvider`)** (`accesskit/Cargo.toml:3-14`, `accesskit/accesskit/Cargo.toml:1-30`).
---
## 2. Makepad (v1.0 crates.io / v2.0 `dev` branch, 2026)
Makepad (`makepad/makepad`, created by Rik Arends) is a full-stack GPU-rendered UI and application environment with zero dependencies on `wgpu`, `winit`, or `taffy`. Its 2025–2026 evolution on the `dev` branch (`v2.0.0`) contains the most advanced live-coding, shader-styling, and AI-agent inspection infrastructure in the Rust ecosystem.
- **From `live_design!` to Splash (`script_mod!`) & `makepad-script`:**
- In Makepad 1.0 (May 2025), UI layout and shaders were declared inside `live_design! { ... }` macros. In Makepad 2.0 (2026 `dev`), `live_design!` was completely replaced by **Splash** via `script_mod! { ... }` backed by `makepad-script` (`makepad/AGENTS.md:27-88`, `makepad/platform/script/Cargo.toml:1-12`).
- `makepad-script` is a custom, minimal-dependency dynamically typed scripting language and bytecode VM with prototype inheritance (`+WidgetBase { ... }`), reactive property propagation, closures, and embedded shader code (`makepad/platform/script/src/vm.rs`).
- **True Hot Reload Without Recompiling (`live_reload.rs`):**
- Why does Makepad embed `script_mod!` inside `.rs` files? Because at runtime (`MAKEPAD=lines cargo run` or Makepad Studio), `makepad_platform::live_reload::extract_script_mod_from_file` (`makepad/platform/src/live_reload.rs:144-179`) watches `.rs` files on disk, tokenizes the file to extract the token stream inside `script_mod! { ... }` without invoking `rustc`, re-evaluates the script module in the `makepad-script` VM, and patches widget properties, layouts, and GPU shaders in single-digit milliseconds while preserving Rust struct state.
- **Shader DSL & Rendering Pipeline (`makepad-draw`):**
- Every widget's visual primitives (`DrawQuad`, `DrawColor`, `DrawText`, custom SDF shapes) are written in Makepad's Rust-embedded shader language (`draw_bg: { pixel: fn() -> vec4 { ... } }`), which cross-compiles at runtime to **Metal MSL**, **DirectX 11 HLSL**, **OpenGL/GLES GLSL**, and **WebGL2** (`makepad/platform/src/os/`).
- Instead of CPU-tessellating vector paths for standard UI controls, Makepad draws controls as instanced quads with analytical SDF math in the fragment shader—making per-pixel animations, procedural materials, glow, and morphing effectively free on the GPU.
- **Text Stack (GPU Slug + MSDF + Raster Atlas):**
- In 2026, Makepad uses a hybrid text engine (`makepad/draw/src/text/`):
- **`slug_atlas.rs` (`makepad/draw/src/text/slug_atlas.rs:1-45`):** Implements Eric Lengyel's **Slug** algorithm, packing quadratic Bézier curves and horizontal/vertical spatial bands into GPU textures and evaluating exact winding numbers per pixel in the fragment shader. Used for large/scaled text where bitmap atlases blur or blow out VRAM.
- **Raster/SDF Glyph Atlas + `rustybuzz` (`makepad/draw/Cargo.toml:14`):** Used for small hinted body text.
- **Layout & Animation:**
- Custom single-pass turtle/flow layout engine (`Walk`, `Layout`, `Flow::Right`, `Flow::Down`, `Flow::Overlay`, `Size::fill()`, `Size::fit()`) in `makepad-draw`—very fast ($O(N)$ single pass), though less expressive than CSS Grid/Flexbox alignment edge cases.
- Built-in `Animator` state machine (`animator: { hover = { default: off, on = { from: { all: Forward { duration: 0.15 } }, apply: { draw_bg: { hover: 1.0 } } } } }`) that interpolates shader uniforms and layout properties directly, plus `ScrollMotion` (`makepad/widgets/src/scroll_motion.rs:1-40`) for flick inertia and spring bounce-back.
- **First-Class Agent Inspection, Frame Tracing & Live Tweaker (2026):**
- **`--remote` HTTP Control Protocol (`makepad/platform/src/remote.rs:1-42`, `makepad/docs/agents/app-remote.md:1-120`):** Running any Makepad app with `--remote 127.0.0.1:8123` (and optionally `MAKEPAD_HIDE_WINDOWS=1` for headless verification) exposes:
- `GET /snap` → compact semantic widget hierarchy + bounding boxes + `user_seq` counter.
- `GET /g` and `GET /gseq?frames=10&interval_ms=33` → single or multi-frame PNG screenshots of active windows without waking the OS screen.
- `POST /click`, `/scroll`, `/type`, `/key`, `/Eval` with `if_user_seq` optimistic concurrency guards so agents never click stale coordinates.
- **`/tweak` Live Tweaker (`makepad/widgets/families/tweaker/src/tweaker.rs:1-50`, `makepad/docs/agents/tweaker.md:1-90`):** Holding `Alt/Option` (or calling `GET/POST /tweak`) inspects every live `Walk`/`Layout`/`DrawQuad` value alongside its exact `file:line:col` origin and writes interactive slider drags directly back to the `.rs` file on disk.
- **Frame & Present Tracing (`makepad/platform/src/frame_trace.rs`, `present_trace.rs`):** Per-frame timing instrumentation for debugging hitches.
- **Platforms:** Custom zero-`winit` OS backends in `makepad/platform/src/os/`: **macOS / iOS / tvOS / visionOS** (`apple/`), **Windows** (`windows/`), **Linux X11/Wayland/Direct DRM** (`linux/`), **Android** (`android/`), **WebAssembly/WebGL2** (`web/`), and **Meta Quest OpenXR** (`linux/openxr*.rs`).
- **Compile Times & Binary Size:** Because Makepad avoids heavy proc-macros (`syn`/`quote`), `wgpu`, and `winit`, a clean debug build of `makepad-example-simple` compiles ~120 crates (vs 400+ for `wgpu`+`winit` stacks) in ~15–25s on Apple Silicon, with stripped release binaries around **4–7 MB** (measured/documented across Makepad builds).
- **Weaknesses:** Poor external documentation (`makepad/AGENTS.md` is actually better written for AI agents than human docs on crates.io), no `accesskit` integration (screen readers cannot read Makepad windows; verified in `blog.wybxc.cc` Aug 2026 survey), and IME preedit composition overlay positioning is incomplete.
---
## 3. Major Rust UI Frameworks (2025–2026)
### 3.1 Slint (`v1.19.0`)
- **Approach & DSL:** Uses a dedicated QML-like `.slint` declarative language (`slint/Cargo.toml:1-87`). `.slint` files can either be ahead-of-time compiled to Rust/C++ code (`slint-build` / `slint!` macro) with static vtables (`helper_crates/vtable`) and fine-grained two-way property bindings (`Property<T>`), or dynamically loaded via `slint-interpreter` (`internal/interpreter`) for live preview (`SLINT_LIVE_PREVIEW=1`).
- **Renderers:** Pluggable across four backends (`slint/api/rs/slint/Cargo.toml:210-239`):
1. **`renderer-femtovg`** (default on desktop, OpenGL or `wgpu` via `renderer-femtovg-wgpu`).
2. **`renderer-skia`** (Metal, Vulkan, D3D, OpenGL, or CPU).
3. **`renderer-software`** (`#![no_std]` capable dirty-rect scanline renderer supporting `RGB565` and `Gray8` for MCUs with <300 KB RAM).
4. **`renderer-vello` / `i-slint-renderer-anyrender`** (`slint/Cargo.toml:101`, `slint/api/rs/slint/Cargo.toml:231-238`, experimental Vello/AnyRender backend).
- **Text, Layout, Animation & Accessibility:**
- **Text:** Migrated in 1.18–1.19 to `parley` + `fontique` 0.12 + `skrifa` 0.44 + `read-fonts` 0.41 + `rustybuzz` 0.20 + `icu_*` (`slint/Cargo.toml:133, 148-172`).
- **Layout:** Built-in `HorizontalLayout`, `VerticalLayout`, `GridLayout`, and Flexbox-like stretch constraints compiled directly into property dependency graphs.
- **Animation:** Declarative `animate prop { duration: 250ms; easing: ease-in-out-back; }` and `states [ ... ]` transitions in `.slint`.
- **Accessibility & Agent Tooling:** Full `accesskit` integration (`accessibility` feature enabled by default in `slint/api/rs/slint/Cargo.toml:28, 85`), working out-of-the-box with macOS VoiceOver and IME. Notably, **Slint 1.19 added an embedded MCP server (`mcp` feature, `SLINT_MCP_PORT`)** and system-testing server (`slint/api/rs/slint/Cargo.toml:136-152`) so AI agents can inspect and drive a running Slint UI over Streamable HTTP.
- **Platforms:** Desktop (macOS, Windows, Linux X11/Wayland/KMS-DRM), Android (`backend-android-activity-06`), iOS, WebAssembly, and bare-metal MCUs (ESP32, STM32, RP2040).
- **Licensing:** Triple-licensed (`GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0`, `slint/Cargo.toml:83`)—restrictive for an MIT/Apache-2.0 open-source framework like Rune.
### 3.2 Dioxus (`v0.7.x`) & Blitz (`v0.3.0-beta.4`) + `Subsecond`
- **Architecture:** Dioxus 0.7 offers two native desktop paths:
1. **`dioxus-desktop`:** Renders `rsx!` VirtualDOM inside the OS WebView (`wry`/`tao`).
2. **`dioxus-native` (`dioxus/packages/native/Cargo.toml:1-99`):** Renders Dioxus `rsx!` HTML/CSS components natively on the GPU without a WebView via **Blitz** (`blitz-dom`, `blitz-paint`, `blitz-shell`).
- **How Blitz Works (`blitz/packages/blitz-dom/Cargo.toml:46-84`):**
- Combines **Servo's `stylo`** (`style`, `selectors`, `cssparser`) for parallel CSS cascade/selector matching with **`stylo_taffy` + `taffy` 0.15** (Flexbox, CSS Grid, Block, Float, `calc()`) for layout, **`parley` + `skrifa` + `icu4x`** for inline/rich text layout, **`accesskit`** for accessibility, and **`anyrender`** (`anyrender_vello_hybrid` by default in `dioxus/packages/native/Cargo.toml:13, 37-45`, with `vello`, `vello_cpu`, and `skia` options) for painting.
- **State Model:** Copyable arena-allocated reactive signals (`Signal<T>`, `Memo<T>`, `Resource<T>`) backed by `generational-box` (`dioxus/packages/signals/`), paired with structural `rsx!` template diffing (`dioxus-core`).
- **`Subsecond` Hot-Patching (`dioxus/packages/devtools/Cargo.toml:19`):**
- Dioxus 0.7 introduced `subsecond`, a Rust binary hot-patching runtime and linker workflow (`dx serve --hot-patch`). When a Rust function changes, `dx` compiles a tiny dynamic object containing only the modified symbols and patches a jump table in the running process—allowing arbitrary Rust view code, closures, and new widgets to hot-reload in <500ms without restarting the app or losing signal state.
- **Weaknesses:** Carrying `stylo` + full HTML DOM semantics adds substantial compile-time weight (~500+ crates) and forces desktop UI into web CSS quirks rather than purpose-built native motion/interaction primitives.
### 3.3 Iced (`v0.14.0` / `v0.15.0-dev`)
- **State Model & Runtime:** Strictly follows the Elm Architecture (`State`, `Message`, `update(&mut State, Message) -> Task<Message>`, `view(&State) -> Element<Message>`) (`iced/Cargo.toml:1-198`). In `0.14.0` (`iced/CHANGELOG.md:9-48`), Iced introduced **reactive rendering** (redrawing and re-laying out only when visual outputs change) and **`Task`** (replacing `Command` with composable async streams via `sipper`).
- **Renderer & Text:**
- Dual renderer architecture (`iced/Cargo.toml:25-31`): **`iced_wgpu`** (on `wgpu` 30, using instanced quads, `cryoglyph` glyph atlas, and `lyon` tessellation for vector canvas) with automatic fallback to **`iced_tiny_skia`** (`tiny-skia` 0.12 software rasterizer + `softbuffer`).
- Text shaping and layout use **`cosmic-text`** (`iced/Cargo.toml:206`), which wraps `swash`, `rustybuzz`, and `fontdb`.
- **Layout & Animation:**
- Custom Flexbox-inspired `Layout` and `Node` solver in `iced_core::layout` (does not use `taffy`).
- Added first-class `iced_core::animation::Animation` in 0.14 (`iced/Cargo.toml:215`), backed by the `lilt` 0.8 spring/easing transition crate, paired with `window::frames()` for smooth vsync-driven transitions.
- **2025–2026 Tooling (`comet`, `iced_test`, `cargo-hot`):**
- **`comet` & Time-Travel Debugging (`iced/Cargo.toml:46-47`):** Because all state mutations flow through `Message`, Iced 0.14 shipped `comet`, an external visual debugger with live time-travel scrubbing across message history and performance metrics (`F12`).
- **`iced_test` & `iced_tester` (`iced/Cargo.toml:50, 193-194`):** Headless `Simulator` that queries widgets by text/ID (`iced_selector`), synthesizes clicks/keys, and compares visual snapshots across `wgpu` and `tiny-skia`.
- **`cargo-hot` (`iced/Cargo.toml:48-49, 205`):** Experimental hot-reloading of `view` functions.
- **Ecosystem Adoption (System76 COSMIC):** System76's `libcosmic` fork of Iced powers the production COSMIC Linux desktop environment (and added `accesskit` + `taffy` in its fork), but upstream `iced` 0.15-dev still lacks built-in `accesskit` integration (`blog.wybxc.cc` survey, Aug 2026).
### 3.4 GPUI (`v0.2.2` in Zed) & `gpui-component` / `gpui-kit` (`v0.8.0`)
- **GPUI Architecture (`zed/crates/gpui/`):**
- Hybrid **Entity + Immediate-Element + Retained-Fiber** architecture. Application state lives in reference-counted `Entity<T>` handles owned by the `App` context (`cx.new(...)`, `cx.notify()`). Views implement `Render::render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement`.
- **Renderer (`zed/crates/gpui/src/scene.rs`):** Instead of general 2D path tessellation, GPUI sorts primitives by draw order/stacking context into a flat GPU `Scene` of `Quad` (with analytic border/corner-radius/background), `Shadow` (analytic box shadow), `Underline`, `MonochromeSprite` (text glyphs/icons), `PolychromeSprite` (images/emoji), and `Path` (rare custom shapes via `lyon` / screen-space MSAA). On macOS it renders via direct Metal (`objc2-metal` / `blade-graphics` on Linux/Windows/WebGPU), effortlessly hitting 120 FPS in Zed.
- **Layout & Text:** Uses **`taffy`** (`zed/crates/gpui/Cargo.toml:107-115`) for Flexbox/Grid layout and native platform text APIs (**CoreText** on macOS, **DirectWrite** on Windows, ** cosmic-text / font-kit** on Linux) for OS-authentic glyph rasterization and subpixel AA.
- **2026 Additions:** Added WebAssembly target support (`wasm32-unknown-unknown`), `accesskit` workspace dependency (`zed/crates/gpui/Cargo.toml:62`), `leak-detection` (`Cargo.toml:38`), and `subsecond` `hot-reload` (`Cargo.toml:50-56`).
- **Why `gpui-kit` / `gpui-component` (`v0.8.0`) Matters (`gpui-component/README.md:1-146`, `docs/ARCHITECTURE.md:1-150`):**
- Raw GPUI ships zero high-level widgets (not even a `TextInput`). Longbridge built **`gpui-kit`** (powering Longbridge Pro desktop) with a clean three-layer split:
1. **`gpui-base`:** Unstyled behavioral primitives (focus traps, popup collision `Positioner`, `InputState`, `EditorState`, `VirtualList`, `TreeState`, `DockArea`, and `AccessKit` role/action wiring).
2. **`gpui-component`:** 75+ styled Shadcn-inspired desktop controls (`DataTable`, 200k-line Tree-sitter `CodeEditor`, `Select`, `Dialog`, `Sheet`, `Calendar`, `Toast`).
3. **`gpui-shell`:** Capability-gated QuickJS (`quickjs-jit`) extension runtime for JS plugins.
- Notably, `gpui-kit` also ships **`examples/ai_recipes/`** (`gpui-component/examples/ai_recipes/README.md:1-40`)—a verified suite of executable consumer recipes and `script/check-ai` drift gates specifically designed so AI coding agents produce compiling, non-leaking GPUI code on the first attempt.
### 3.5 `egui` (`v0.37.0`)
- **Architecture:** Pure immediate-mode GUI (`ui.button("Click").clicked()`). Every frame rebuilds a flat mesh of textured triangles (`epaint::Mesh` with a single 1D feathering/gradient texture + font atlas) so the entire UI renders in a handful of draw calls on `egui_wgpu` (default in `eframe` since 0.34) or `egui_glow`.
- **2026 Text Overhaul (`egui/crates/epaint/Cargo.toml:38-42, 88-100`):** In `0.37.0`, `epaint` replaced its legacy `ab_glyph` rasterizer with **`fontique` + `harfrust` + `skrifa` + `vello_cpu`**, gaining proper OpenType shaping, system font fallback (`egui_system_font_provider`), and `COLR`/`sbix`/`CBDT` color emoji rendering!
- **Accessibility & Testing:** Strong `accesskit` 0.24 support and **`egui_kittest`** (`egui/Cargo.toml:25, 111`), which lets tests query and drive widgets semantically through their AccessKit nodes (`harness.get_by_label("Submit").click()`).
- **Why `egui` is Great for Tools and Bad for High-Craft Consumer Feel:**
- *Great for tools:* Zero state synchronization boilerplate, trivial embedding in game/3D viewports (`rerun.io`), fast compile times.
- *Bad for feel:* Immediate-mode single-pass layout requires knowing child sizes *after* placing parents (causing one-frame layout lag/flicker on dynamic content resized first frame), lacks retained per-element velocity state for interruptible spring physics or FLIP layout morphing, and forces custom look-and-feel into procedural `Painter` math rather than composable style/animation trees.
### 3.6 `Floem` (`v0.2.0`), `Freya` (`v0.5.0-beta.12`), `Vizia` (`v0.4.0`), and `Cushy` (`v0.4.0`) / `Kludgine` (`v0.11.0`)
- **Floem (`v0.2.0`, `floem/Cargo.toml:1-150`):**
- Fine-grained reactive signals (`RwSignal<T>` is `Copy`, backed by arena IDs in `floem_reactive`) where views are constructed once and closures surgical-patch styles/text without virtual DOM diffing.
- Uses **`taffy` 0.9.2** for Flexbox/Grid layout, **`parley` 0.7 + `fontique` 0.7** for text, **`ui-events` 0.3**, and J.R. Moulton's new **`understory`** crates (`understory_box_tree`, `understory_event_state`, `understory_focus`, `understory_virtual_list` in `floem/Cargo.toml:117-121`) for spatial indexing and focus management.
- Pluggable renderer trait (`floem_renderer`) with backends for `vger` (GPU SDF shaders), `vello`, `skia`, and `tiny_skia` fallback. Includes built-in reactive keyframe and spring animations (`.animation(...)`) and a rich style transition system, but in 2026 its IME and AccessKit wiring on macOS remain broken (`blog.wybxc.cc` survey).
- **Freya (`v0.5.0-beta.12`, `freya/Cargo.toml`, `freya/crates/freya-core/Cargo.toml:1-96`):**
- **Major 2025–2026 Pivot:** Freya 0.4/0.5 dropped Dioxus's VirtualDOM/RSX runtime entirely and built its own **`freya-core`** reactivity (`generational-box` signals + `pathgraph` tree + `ragnarok` event dispatch) with a clean builder API instead of HTML tags.
- Uses **`torin`** (`freya/crates/torin/`, custom Flexbox-like layout engine with caching), **`freya-skia-safe`** (`skia-safe` 0.93 for rendering and `skia::textlayout::Paragraph` for text), **`accesskit` 0.21**, **`freya-testing`** headless harness, and **`subsecond` 0.7.4** for hot-reloading.
- **Vizia (`v0.4.0`, `vizia/ARCHITECTURE.md:1-90`, `vizia/Cargo.toml:50-111`):**
- ECS-inspired retained tree (`Entity` IDs indexing sparse-set component stores for styles/layout caches) with fine-grained signals (`vizia_reactive`), CSS stylesheet parsing (`cssparser` 0.37 + `selectors` 0.39) with CSS property animations, **`morphorm` 0.9** (custom single-pass stretch layout), **`skia-safe` 0.99** (with Skia `textlayout`), **`accesskit` 0.24**, and `vizia_baseview` for VST/CLAP audio plugin windows alongside `vizia_winit`.
- **Cushy (`v0.4.0`) & Kludgine (`v0.11.0`) (`cushy/Cargo.toml:1-66`, `kludgine/Cargo.toml:1-49`):**
- Built by Khonsu Labs around a single ergonomic reactive primitive (`Dynamic<T>`), rendered on `wgpu` 24 via `kludgine` (`lyon_tessellation` + `cosmic-text` 0.12 + `etagere` atlas packer). Clean widget composition and built-in `Dynamic` easing animations, but development has been largely dormant since late 2024 and lacks `accesskit` screen-reader support.
### 3.7 `Taffy` (`v0.15.0`)
- **Status & Capabilities (`taffy/Cargo.toml:1-91`):** Maintained under `DioxusLabs/taffy` by Nico Burns, Alice Cecile, and Jonathan Kelley. `taffy` 0.15 implements **CSS Flexbox** (including CSS Flexbox Level 2 `flex-wrap: balance`), **CSS Grid**, **CSS Block**, **CSS Float (`float_layout`)**, and **`calc()`** expressions.
- **Architecture:** Exposes both a ready-to-use arena (`TaffyTree` backed by `slotmap`) and low-level traits (`TraversePartialTree`, `LayoutFlexboxContainer`, `LayoutGridContainer`) so frameworks can store layout styles directly inside their own widget tree or ECS without duplicating nodes, using a custom measure callback (`measure_function`) to invoke `parley` for inline text measurement.
- **Who Uses It:** **Zed (`gpui`)**, **Bevy (`bevy_ui`)**, **Dioxus Native / Blitz (`stylo_taffy`)**, **Floem**, **Lapce**, **System76 `libcosmic`**, **Rosin**, and **Tessera**.
### 3.8 Notable 2025–2026 Entrants (`Blinc`, `Rosin`, `Tessera`, `Ply`)
- **Blinc (`project-blinc/Blinc`, early 2026):** Reactive `wgpu`-based cross-platform UI framework targeting desktop, iOS, and Android with stateful components; early alpha with incomplete CJK font fallback, manual reactive event wiring on inputs, and no `accesskit` integration (`blog.wybxc.cc` survey, Aug 2026).
- **Rosin (`docs.rs/rosin`, 2026):** Combines top-level centralized state with fine-grained reactive lenses, CSS stylesheet styling, `vello` rendering (exposing raw `vello` canvas callbacks per node via `.on_canvas(...)`), working IME, and `accesskit` integration.
- **Tessera (`tessera-ui` 2.5.0, 2025–2026):** Declarative immediate-mode UI framework using proc-macro positional memoization (`#[tessera]`) and a pluggable `wgpu` shader pipeline (e.g., frosted glass/fluid shaders) targeting Material Design 3; still suffers from platform `wgpu` surface bugs on macOS (`blog.wybxc.cc` survey).
- **Ply (`plyx.iz.rs`, v1.0 in March 2026):** Clay-inspired immediate-mode builder UI library focused on minimal boilerplate and autocompletion-friendly layout builders, with optional `accesskit` setup.
---
## 4. Ecosystem Comparison Matrix (Oct 2026)
| Framework (Version) | Renderer Approach | Text Stack | Layout Engine | State Model | Animation Support | Accessibility (`accesskit`) | Platforms (Desktop / Mobile / Web) | Hot Reload / Live Tooling | Clean Debug Compile / Stripped Release Size |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| **Xilem / Masonry** (`0.4.0`) | `imaging` trait (`vello`, `vello_gpu`, `vello_cpu`, `skia`) | `parley` 0.12 (`fontique` + `harfrust` + `skrifa` + `icu4x`) | Masonry custom `measure` / `layout` / `compose` | Static typed `View` tree diffing (`ViewSequence`) | Manual `on_anim_frame(ns)` per widget | **Yes** (`accesskit` 0.24, built-in + `masonry_testing`) | Win, Mac, Linux, Android (`xilem_web` separate DOM crate) | None built-in (`subsecond` compatible) | ~45–60s (est.) / ~8–12 MB (est.) |
| **Makepad** (`1.0` / `2.0-dev`) | Custom GPU instanced SDF shaders (Metal, DX11, GL, WebGL2) | GPU **Slug** curve atlas (`slug_atlas.rs`) + SDF/raster + `rustybuzz` | Custom 1-pass Turtle `Walk` / `Flow` | `script_mod!` (Splash VM) + Rust `Widget` structs | Shader-driven `Animator` tracks + `ScrollMotion` springs | **No** | Win, Mac, Linux, **iOS, Android, WebGL2, visionOS, Quest** | **Best-in-class:** zero-recompile `script_mod!` reload + `/tweak` + `--remote` HTTP API | **~15–25s** / **~4–7 MB** (measured/repo) |
| **Slint** (`1.19.0`) | `femtovg` (GL/wgpu), `skia`, `software` (`no_std`), `anyrender`/`vello` | `parley` + `fontique` 0.12 + `skrifa` 0.44 + `rustybuzz` | Built-in compiled constraint/grid/flex solver | `.slint` two-way reactive `Property<T>` bindings | Declarative `animate` & `states` in `.slint` | **Yes** (default on desktop, works with VoiceOver) | Win, Mac, Linux (KMS), **Android, iOS, WASM, MCUs** | `SLINT_LIVE_PREVIEW` interpreter + VS Code preview + **`SLINT_MCP_PORT`** | ~35–50s / **~2–5 MB** (`software`/`femtovg`) |
| **Dioxus Native / Blitz** (`0.7` / `0.3-b4`) | `anyrender` (`vello_hybrid` default, `vello`, `vello_cpu`, `skia`) | `parley` + `fontique` + `skrifa` + `icu4x` | Servo `stylo` + `stylo_taffy` + **`taffy` 0.15** | Copyable arena `Signal<T>` + `rsx!` template diffing | CSS transitions (partial in Blitz) or frame signals | **Yes** (`accesskit` in `blitz-dom`) | Win, Mac, Linux, iOS/Android (experimental), WASM | **`subsecond`** binary hot-patching + RSX template hot reload (`dx serve`) | ~60–90s (`stylo` heavy) / ~15–25 MB (est.) |
| **Iced** (`0.14` / `0.15-dev`) | `iced_wgpu` (`wgpu` 30 quads + `lyon`) + `tiny-skia` CPU fallback | `cosmic-text` (`swash` + `rustybuzz` + `fontdb`) + `cryoglyph` | Custom `iced_core::layout` Flexbox solver | Elm Architecture (`State`, `Message`, `Task`) | `Animation<T>` (`lilt` 0.8 springs/easings) | **No** upstream (present in System76 `libcosmic` fork) | Win, Mac, Linux, WASM (limited mobile) | **`comet`** time-travel debugger + `cargo-hot` + `iced_test` | ~35–50s / ~8–14 MB (est.) |
| **GPUI + `gpui-kit`** (`0.2.2` / `0.8.0`) | Custom Uber-shader (`Quad`, `Shadow`, `Sprite`, `Path`) on Metal/Blade/WebGPU | Native OS (**CoreText**, **DirectWrite**) + `font-kit` | **`taffy`** (Flexbox + CSS Grid) | Retained `Entity<T>` models + immediate `Element` fiber | `AnimationElement` + `gpui-base` motion helpers | **Yes** (`accesskit` wired in `gpui-base`) | Mac, Win, Linux, **WASM** (minimal mobile) | **`subsecond`** (`hot-reload` feature) + `gpui-shell` QuickJS + Inspector | ~45–70s / ~15–30 MB (`gpui-shell` 78 MB stripped) |
| **egui** (`0.37.0`) | Immediate-mode 2D triangle mesh (`egui_wgpu` / `egui_glow`) | `fontique` + `harfrust` + `skrifa` + **`vello_cpu`** | Custom 1-pass immediate-mode cursor layout | Immediate mode + `Context` ID memory store | `ctx.animate_bool` / `animate_value_with_time` | **Yes** (`accesskit` 0.24 + **`egui_kittest`**) | Win, Mac, Linux, **WASM**, Android/iOS (via `winit`) | External only (`subsecond` / `hot-lib-reloader`) | **~20–30s** / **~5–9 MB** |
| **Floem** (`0.2.0`) | `vger` (GPU SDF), `vello`, `skia`, `tiny_skia` | `parley` 0.7 + `fontique` 0.7 + `swash` | **`taffy` 0.9.2** + `understory_box_tree` | Fine-grained `Copy` `RwSignal<T>` (no VDOM) | Built-in reactive keyframe & spring `.animation()` | Partial / broken on macOS in 0.2 | Win, Mac, Linux, WASM | Inspector overlay only | ~40–55s / ~10–15 MB (est.) |
| **Freya** (`0.5.0-beta.12`) | `freya-skia-safe` (`skia-safe` 0.93 Metal/GL/Vulkan/D3D) | Skia `textlayout::Paragraph` | Custom **`torin`** Flexbox layout engine | `freya-core` `generational-box` signals + builder views | `freya-animation` hook-based easings/springs | Wired (`accesskit` 0.21), macOS screen reader issues | Win, Mac, Linux | **`subsecond` 0.7.4** + `freya-devtools` + `freya-testing` | ~30–45s (with prebuilt Skia bin) / ~18–28 MB |
| **Vizia** (`0.4.0`) | `skia-safe` 0.99 (Metal, Vulkan, D3D, GL) | Skia `textlayout` + `unicode-bidi` | **`morphorm` 0.9** (1-pass stretch layout) | ECS sparse-sets + `vizia_reactive` signals | CSS stylesheet animations (`vizia_style`) | Wired (`accesskit` 0.24), crashes on edit signal | Win, Mac, Linux (`winit` + **`baseview`** audio plugins) | CSS stylesheet reload at runtime | ~35–50s (prebuilt Skia) / ~18–28 MB |
| **Cushy / Kludgine** (`0.4` / `0.11`) | `kludgine` on `wgpu` 24 (`lyon_tessellation`) | `cosmic-text` 0.12 | Custom `Widget` constraint layout (`figures` units) | Reactive `Dynamic<T>` values & bindings | `Dynamic` value transitions (`easing-function`) | **No** | Win, Mac, Linux, WASM | None | ~35–45s / ~9–13 MB (est.) |
---
## 5. What Rune Should Steal vs. What Rune Should Avoid
### What to Steal
1. **Steal GPUI & Makepad's "UI Uber-Shader + SDF Instanced Quad" primary renderer, NOT general path tessellation for Chrome.**
- 98% of UI frames consist of rounded rectangles with borders, gradients, inner/outer analytic shadows, clip masks, textured sprites, and glyph runs (`zed/crates/gpui/src/scene.rs`). Rendering these as instanced SDF quads in a single uber-shader pass gives 120–240 Hz performance, zero CPU tessellation cost during spring animations, and effortless shader effects (backdrop blur, noise, specular borders, liquid morphing).
2. **Steal Makepad's `--remote` Agent Protocol and `/tweak` Source Write-Back (`makepad/platform/src/remote.rs`, `makepad/docs/agents/tweaker.md`).**
- Every Rune application should compile with an optional embedded local agent/inspector server (like Makepad's `--remote` and Slint's `SLINT_MCP_PORT`) that supports:
- Headless off-screen window rendering (`RUNE_HEADLESS=1`, never waking the user's display).
- Semantic + geometric snapshot (`GET /snap`) with monotonic interaction sequence guards (`if_user_seq`).
- Multi-frame motion capture (`GET /gseq?frames=N&interval_ms=16`) and per-frame motion trace export (`frame_trace.rs`) so agents can verify spring curves and catch 1-frame layout pops deterministically.
- Live knob/style tweaking (`#[knob]` / `script_mod!`) that writes tuned constants back to the exact `file!():line!():column!()` in `.rs` source.
3. **Steal `egui_kittest` + `gpui-base`'s AccessKit-driven headless testing and AI Recipes (`egui/crates/kittest`, `gpui-component/examples/ai_recipes/README.md`).**
- Wiring `accesskit` into unstyled behavioral primitives from day one gives both real OS screen-reader accessibility and a zero-flake semantic query tree (`get_by_role`, `get_by_label`) for automated tests. Pair this with `gpui-kit`-style `check-ai` canonical consumer recipes.
4. **Steal Makepad's GPU Slug text (`makepad/draw/src/text/slug_atlas.rs`) for scale/transform-animated typography, paired with a hinted raster atlas (`skrifa` + `vello_cpu`/`glifo`) for body text.**
- Traditional bitmap glyph atlases shimmer or blur when text scales continuously during a spring transition, zoomable canvas pan, or 3D card tilt. Using hinted raster atlases for static 1x body text and Slug GPU curve evaluation (or high-res SDF) for transformed/large display text solves both crispness and kinetic typography.
5. **Steal Floem's `Copy` Arena Signals (`RwSignal<T>`) + Xilem/Masonry's `measure` / `layout` / `compose` separation (`masonry_core/src/core/widget.rs:121`).**
- Separating `layout` (expensive Taffy box calculation) from `compose` (cheap transform/scroll/spring-offset matrix update) means spring animations and scroll physics never trigger layout recalculation unless box dimensions actually depend on them.
6. **Steal `Subsecond` integration (`zed/crates/gpui/Cargo.toml:55`) + zero-recompile style/knob hot reload (`makepad/platform/src/live_reload.rs`).**
- Combine zero-recompile file watching for literal style/spring/shader blocks with `subsecond` binary jump-table patching for structural Rust code changes.
### What to Avoid
1. **Avoid C++ FFI rendering dependencies (`skia-safe`, Qt, GTK, WebView).**
- `skia-safe` (used by Freya and Vizia) bloats binary size by 15–25 MB, complicates cross-compilation to iOS/Android/WASM, and hides the GPU command encoder so you cannot seamlessly interleave custom `wgpu` shaders or 3D layers with UI widgets.
2. **Avoid building a custom DSL that replaces Rust for control flow and business logic (`.slint`, legacy Makepad `live_design!`, Ribir's `@ { pipe!(...) }` macros).**
- Custom DSLs break standard `rust-analyzer` refactoring, split state across two languages, and confuse coding agents when syntax drifts from training data (as seen in the Aug 2026 survey on Ribir and Makepad). Keep view trees in normal Rust syntax; use lightweight macros or `#[knob]` attributes only for live-reloadable literals/shaders whose values can be parsed out of `.rs` files without recompiling.
3. **Avoid Compute-only Vello (`vello` 0.8) as the primary UI renderer.**
- Even Linebender moved compute `vello` to `research/vello_research/` (`vello/ARCHITECTURE.md:27-31`) because compute pipelines struggle on mobile tile GPUs, WebGL2, and memory-constrained devices.
4. **Avoid full HTML/CSS engines (`stylo` in Blitz) for native app UI.**
- Pulling in Servo's `stylo` adds hundreds of crates and browser layout baggage without giving you interruptible springs, FLIP layout morphing, or custom GPU materials. `taffy` alone gives 100% of the Flexbox/Grid ergonomics needed at a tiny fraction of the compile cost.
5. **Avoid immediate-mode one-pass layout (`egui`, `ply`).**
- Immediate-mode layout cannot size a parent container to dynamic children without either a two-pass measure or a one-frame visual pop—fatal for Kit's motion standards.
---
## 6. Concrete Crate Dependency vs. Custom-Build Recommendation for Rune
### Crates Rune Should Depend On Directly
| Layer | Recommended Crate(s) | Version (Oct 2026) | Why Depend Instead of Build |
| :--- | :--- | :--- | :--- |
| **2D Geometry & Curves** | `kurbo` | `0.13.1` | `#![forbid(unsafe_code)]`, `no_std`, shared by `skrifa`, `parley`, `vello_common`, and `accesskit`. Zero reason to reinvent `Point`, `Rect`, `RoundedRect`, `Affine`, or `BezPath`. |
| **Color & Brush Types** | `color`, `peniko` | `0.3.3`, `0.6.1` | First-class CSS Color 4 (`Oklch`, `Oklab`, `DisplayP3`, `Srgb`) perceptual color interpolation and shared `Brush`/`Gradient`/`FontData` handles. |
| **Box Layout (Flexbox & Grid)** | `taffy` | `0.15.0` | Battle-tested in Zed, Bevy, Dioxus, and Floem; minimal dependencies (`slotmap`, `smallvec`, `grid`, `flexbox`, `block_layout`); trait-based API lets Rune run layout directly over its own retained node arena. |
| **Font Parsing, Hinting & Shaping** | `parley` (or `parley_engine` + `fontique` + `harfrust` + `skrifa` + `read-fonts`) | `parley` `0.12.0`, `skrifa` `0.49`, `harfrust` `0.14` | Google Fonts (`skrifa`/`harfrust`) + Linebender (`fontique`/`parley`) is the undisputed pure-Rust standard in 2026. Handles variable fonts, autohinting, OpenType shaping, bidi, UAX#14/CJK line breaking, and cursor hit-testing. |
| **Vector / Emoji Raster Escape Hatch** | `vello_cpu` (+ optional `vello_gpu` / `glifo`) | `0.3.0` (`glifo` `0.4.0`) | Use `vello_cpu` (just like `egui` 0.37 does in `epaint`) for color emoji (`COLR`), complex SVG icons, and CPU snapshot testing, and optionally `vello_gpu` for complex canvas vector layers. |
| **Accessibility** | `accesskit` (+ platform adapters) | `0.25.1` | Non-negotiable for macOS VoiceOver, Windows UIA, Linux AT-SPI, iOS, and Android, and doubles as the semantic backbone for headless UI testing and agent introspection. |
| **Input Event Vocabulary** | `ui-events` | `0.3.0` | W3C-aligned `PointerEvent`, `KeyboardEvent`, and modifier state types (`kurbo`-integrated), already shared by Masonry and Floem. |
| **Spatial Indexing (Optional)** | `understory_box_tree` / `etagere` | `0.1` / `0.2.8` | Proven R-tree / bounding-box hit-testing (`understory`) and shelf texture atlas packing (`etagere`, used by GPUI, Iced, and Kludgine). |
| **Hot-Patching Hook (Optional)** | `subsecond` | `0.7.10` | Proven in Dioxus, GPUI, and Freya for sub-second symbol hot-patching of Rust view functions. |
### Subsystems Rune Should Build Itself (and Why)
1. **Retained Reactivity + Explicit 4-Phase Frame Pipeline (`Update → Measure/Layout → Animate/Compose → Paint`):**
- *Why build:* None of Xilem, Iced, Floem, or GPUI treat **FLIP layout transitions** (automatically animating a node's bounds with a spring when Taffy moves it) and **interruptible velocity-preserving springs** as first-class steps between `Layout` and `Compose`. Rune needs a custom retained node graph where Taffy computes target layout boxes and the `Compose` phase applies active spring/gesture deltas before generating GPU instances.
2. **Custom `wgpu` UI Uber-Shader + Analytic Material/Shadow/SDF Pass (+ GPU Slug/SDF Text):**
- *Why build:* General 2D vector renderers (`vello_gpu`, `femtovg`, `tiny-skia`) do not natively expose per-quad analytic squircle corners, multi-layered elevation shadows, backdrop blur/refraction, or custom WGSL material shaders per widget. Building a compact ~2,500-LOC `wgpu` instanced primitive compositor (drawing on GPUI's `Scene` and Makepad's `DrawQuad` + `SlugAtlas`) gives Rune complete control over visual craft and 120Hz frame pacing.
3. **First-Class Multi-Sensory & Motion Engine (Springs, Gestures, Procedural Audio/Haptics):**
- *Why build:* No existing Rust UI framework links pointer velocity, spring physics, and sub-millisecond procedural UI audio/tactile feedback into a unified interaction primitive.
4. **Built-in Live Tuning (`knobs`) + Headless Agent Remote Protocol (`/snap`, `/gseq`, `/tweak`, Motion Trace):**
- *Why build:* Makepad proved the architecture (`remote.rs`, `tweaker.rs`, `frame_trace.rs`, `live_reload.rs`), and Rune should build a clean, pure-Rust version natively integrated with Kit's `knobs` and Scrawl's motion-trace format from day one—allowing both humans and coding agents to tune springs/styles live without recompiling and verify motion traces headlessly.
### Rejected Alternatives (and Why)
- **Forking or building directly on `Xilem` / `Masonry`:** Masonry's `Widget` trait and `imaging` abstraction are well-engineered, but Xilem's deeply nested static tuple view types create hostile compiler diagnostics for humans and agents, and Masonry's rendering model assumes a traditional 2D vector painter (`vello`) rather than a shader-first instanced compositor with FLIP layout springs and backdrop materials.
- **Building on `GPUI` or `gpui-kit`:** GPUI's macOS backend is tightly coupled to Zed's internal workspace crates (`gpui-pre` snapshots require exact `=0.3.9` pins per `gpui-component/Cargo.toml:62-71`), lacks iOS/Android support, and relies on platform-specific graphics abstractions (`blade-graphics` / raw `objc2-metal`) rather than a clean cross-platform `wgpu` pipeline.
- **Building on `Makepad`:** Makepad's custom `script_mod!` VM, custom turtle layout (no Flexbox/CSS Grid), and lack of `accesskit` or standard Rust ecosystem types (`kurbo`/`taffy`/`parley`) make it an island ecosystem rather than a composable Rust library.
- **Building on `Iced` or `Slint`:** Iced's Elm Architecture forces all component animation/gesture state through top-level messages (or opaque internal widget state) and lacks `accesskit`; Slint's `.slint` DSL and GPLv3/commercial licensing are incompatible with a permissively licensed Rust-native library.
---
## 7. Open Questions for Rune Architecture
1. **`parley` High-Level API vs. `parley_engine` Direct Integration:** Should Rune use `parley::LayoutContext` directly, or depend on the newer lower-level `parley_engine` + `fontique` + `skrifa` crates (introduced in Parley 0.12, `parley/parley/Cargo.toml:37-39`) to avoid intermediate style buffer allocations during high-frequency text layout?
2. **Text Rendering Dual-Path Threshold:** At what pixel size or transform state should Rune switch between a hinted `skrifa` + `vello_cpu` raster glyph atlas (crispest at 10–18px static UI text) and a Makepad-style GPU Slug / MSDF curve evaluator (artifact-free during spring scale/rotation/3D transforms)?
3. **Windowing Layer (`winit` 0.30/0.31 vs. Custom Platform Shells on macOS/iOS):** Is `winit` sufficient for Rune's frame-pacing (`CADisplayLink` / `CAMetalDisplayLink` 120Hz ProMotion sync, trackpad gesture phases, and transparent/vibrancy window chrome), or should Rune follow GPUI and Makepad in owning a thin native `objc2` macOS/iOS window shell while keeping `winit` as a fallback for Linux/Windows/Web?
4. **Zero-Recompile Tuning Syntax vs. `Subsecond`:** Should Rune parse `#[knob]` / style macro literals directly from `.rs` source files on disk (like `makepad_platform::live_reload::extract_script_mod_from_file` in `makepad/platform/src/live_reload.rs:144`) for sub-5ms zero-recompile parameter reloads, and pair that with optional `subsecond` binary patching when structural Rust code changes?
+763
View File
@@ -0,0 +1,763 @@
# 03 — Flutter (reach), SwiftUI/Core Animation (feel), Rive, Figma, Lottie, Compose
Research date: 2026-10-21. Sources are linked inline. Source code read from shallow clones of
`flutter/flutter` (HEAD `77f043bc`, committed 2026-10-21) and `rive-runtime` (HEAD as of 2026-10-21)
in a scratch directory. Apple claims come from WWDC transcripts and DocC JSON. Anything marked
**(inference)** is my reading and not a documented fact. Anything marked **(estimate)** is not measured.
---
## Summary
- **Flutter's reach comes from owning every pixel behind one thin C ABI**
([`embedder.h`](https://github.com/flutter/flutter/blob/main/engine/src/flutter/shell/platform/embedder/embedder.h)).
Each platform shell only supplies a surface, a vsync, input, text input and accessibility.
Web is the exception: it is a separate engine (CanvasKit/Skwasm) that skips the C++ engine and display
lists ([Impeller FAQ](https://github.com/flutter/flutter/blob/main/docs/engine/impeller/docs/faq.md)).
That fork is a cost Rune should avoid by building the same Rust renderer for wasm + WebGPU, which is
what Figma does with C++/Dawn.
- **Impeller's main lesson is to make every GPU pipeline known at build time.** Shaders are authored once
(GLSL 4.60), compiled offline to MSL, SPIR-V or GLSL ES, and reflected into C++ structs. No shader is
compiled at runtime, so there is no first-run jank. Impeller is now the only renderer on iOS, and the
default on Android, macOS, Windows and Linux as of 3.47 (Impeller
[README availability matrix](https://github.com/flutter/flutter/blob/main/engine/src/flutter/impeller/README.md)).
- **Flutter's threading converged on what GPUI already does: UI code runs on the platform main thread.**
The "great thread merge" shipped on iOS/Android in 3.29 and on macOS/Windows in 3.35. Rasterization
stays on its own thread.
- **The feel benchmark is not "the render server does everything".** Core Animation's out-of-process
render server keeps `CAAnimation`s running when the main thread blocks. But Apple's modern SwiftUI
animations do **not** create `CAAnimation`s: they evaluate springs in-process and write presentation
values directly, off the main thread for built-in effects
([WWDC24 10145](https://developer.apple.com/videos/play/wwdc2024/10145/),
[WWDC23 10156](https://developer.apple.com/videos/play/wwdc2023/10156/)). So Rune can match the feel
with an in-process animation clock that is off the main thread and has excellent frame pacing.
It does not need to lower everything to CA.
- **The spring model to copy is exactly Apple's `spring(duration:bounce:)`**: mass 1, k = (2π/d)²,
ζ = 1 − bounce for bounce ≥ 0 and 1/(1 + bounce) for bounce < 0. When an animation is retargeted it
merges and keeps its velocity. Flutter now ships the identical conversion
(`SpringDescription.withDurationAndBounce`). Gesture handoff should come from **merging interactive
springs**, not from a hand-computed initial velocity (WWDC24).
- **iOS scroll feel is known, published arithmetic.** Deceleration is 0.998/ms (normal) or 0.99/ms (fast).
The rubber band is `(1 − 1/(x·0.55/d + 1))·d`. Fling projection is `v/1000 · r/(1 − r)`. Flutter
tunes its versions by overlaying a native scroll view and fitting curves. That is a good proof loop
to steal.
- **Liquid Glass (iOS/macOS 26) cannot be honestly reproduced by a custom renderer**, because the system
material adapts continuously to what is behind it. It *can* be hosted: `UIGlassEffect` and
`NSGlassEffectView` sample whatever the render server composites beneath them, including a
`CAMetalLayer` **(inference; matches the launcher's experience, verify in a spike)**. Flutter has no
first-party Liquid Glass after 16 months
([flutter#170310](https://github.com/flutter/flutter/issues/170310)). Its apps fall back to platform
views for it.
- **Rive's renderer is the best non-Rust reference for vector quality.** It uses analytic coverage via
tessellated, signed-winding triangle patches; a "clockwise" fill rule; and pixel-local-storage or
atomic interlock modes. Its **vector feathering** computes soft edges as the integral of a Gaussian
along the real path edges, using a lookup texture, with no blur pass
([Rive blog](https://rive.app/blog/how-rive-reinvented-feathering-for-the-vectorian-era),
`renderer/src/shaders/draw_path_common.glsl:186`). This is the right primitive for Kit's "soft
gradient masks, never a hard clip".
- **Figma's lessons**: one C++ renderer compiled to both wasm and native, with Dawn underneath both. A
draw API with explicit arguments (no global binding state). Batched uniform uploads. Hot device-loss
fallback (WebGPU→WebGL mid-session). Per-PR perf tests on real hardware
([Figma WebGPU](https://www.figma.com/blog/figma-rendering-powered-by-webgpu/),
[Keeping Figma fast](https://www.figma.com/blog/keeping-figma-fast/)).
- **Animation-as-data (Lottie/Skottie, Rive state machines) gives a pure function `seek(t) → scene`.**
That is exactly what agent verification needs: deterministic frame N on demand. Flutter's test binding
does the same with a fake clock (`FakeAsync`, clock fixed at 2015-01-01) and a box-glyph test font
("Ahem"), so golden images are deterministic.
---
## 1. Flutter + Impeller (the reach benchmark)
### 1.1 Engine architecture and threads
- **Pipeline.** The framework (Dart) runs build → layout → paint and produces a `Scene` (engine-side
`LayerTree` of container, transform, clip, opacity, backdrop-filter and picture layers). Picture
layers hold **DisplayLists**, Flutter's recorded command buffers. The Animator posts the layer tree into
a pipeline. The Rasterizer on the raster thread runs `Preroll` + `Paint` over the layers, and those
dispatch DisplayList ops to Impeller (or Skia)
([Life of a Flutter Frame](https://github.com/flutter/flutter/blob/main/docs/engine/Life-of-a-Flutter-Frame.md)).
Display lists are the seam where renderers can be swapped: "the engine has Skia and Impeller
dispatchers for display lists"
([Impeller FAQ](https://github.com/flutter/flutter/blob/main/docs/engine/impeller/docs/faq.md)).
- **Layout** is a single depth-first pass: constraints go down, sizes go up, O(n) for the initial layout
and sublinear for updates thanks to relayout boundaries
([architectural overview](https://docs.flutter.dev/resources/architectural-overview),
[Inside Flutter § Sublinear layout](https://docs.flutter.dev/resources/inside-flutter)).
- **Threads.** Historically there were four task runners: platform (OS main), UI (Dart), raster and IO.
**Thread merge:** from 3.29, Dart runs on the platform thread on iOS and Android ("the UI thread is
removed"). macOS and Windows followed in 3.35
([breaking-change doc](https://docs.flutter.dev/release/breaking-changes/macos-windows-merged-threads),
[flutter#150525](https://github.com/flutter/flutter/issues/150525)). A secondary source says Linux
is still opted out by default
([Medium](https://medium.com/easy-flutter/flutters-great-thread-merge-what-it-means-for-your-apps-1f712d6b253d)).
The stated reason was that split threads "prevented Flutter apps and plugins from using Dart FFI to
interoperate with native APIs that must be called on the platform thread". The raster thread is still
separate. *Relevance:* Rune (Rust UI on the main thread + a render thread) matches where Flutter
ended up. Synchronous native calls on the UI thread are a feature, not a bug.
- **Warm-up frame.** Before the first vsync, the framework builds, lays out and paints once so that the
first real frame is cheap (Life of a Flutter Frame § Warm-up frame).
### 1.2 Why Impeller replaced Skia
- **The problem was shader compilation jank.** Skia generated and compiled shaders lazily, when a draw
type was first seen, so the first animation stuttered. The old fix (SkSL warm-up capture) was brittle.
- **Impeller's objectives**
([README](https://github.com/flutter/flutter/blob/main/engine/src/flutter/impeller/README.md)):
- "All shader compilation and reflection is performed offline at build time. All pipeline state
objects are built upfront. Caching is explicit."
- Every GPU resource is labelled ("Instrumentable").
- Portable across backends.
- Spreads a frame across threads when needed.
- **Shader pipeline:** GLSL 4.60 → SPIR-V via `impellerc` → MSL, Vulkan SPIR-V or GLSL ES 1.00 → a single
blob embedded in the binary. A reflector emits C++ structs for the uniform and vertex layouts, so
"changes to the shader interface lead to compile time errors". This idea maps directly onto Rust:
WGSL/naga reflection into `#[repr(C)]` structs at build time.
- **Layering:** `renderer` (backend-agnostic HAL) → `entity` (2D renderer, pass-rewriting/eliding
optimizations) → `display_list` (DisplayList dispatcher) → `typographer` (glyph atlases only; "Impeller
does **not** do any text layout or shaping"). It also has a `playground` test harness that opens any
test case in a window or attaches a frame debugger. Impeller-level golden tests live in
`impeller/golden_tests`.
- **Anti-aliasing:** 4× MSAA everywhere. SDF rendering for primitives is on by default on desktop and
off by default on mobile ([Impeller AA](https://docs.flutter.dev/perf/antialiasing)). This is weaker
than Rive's or Vello's analytic coverage. For example, MSAA gives four coverage levels per pixel
unless SDFs are used.
- **Status in 2026** (README matrix, 3.47 stable):
- iOS: ⭐ exclusive. Skia removed in 3.29.
- Android: ✅ default, Vulkan first with a fallback to Impeller-GLES. The 2026 roadmap aims to remove
Skia on Android 10+ entirely
([Roadmap 2026](https://github.com/flutter/flutter/blob/master/docs/roadmap/Roadmap.md)).
- macOS, Windows, Linux: ✅ default as of 3.47. They were preview or experimental through 3.44.
- Web: 🚫. CanvasKit/Skwasm remain. The FAQ says porting the web engine to Impeller is a non-goal,
although WGSL compilation was sanity-checked.
- Skia pieces still in use: SkParagraph for text layout, and the Skia-wrapped image codecs (attempts
to replace them with system decoders stalled, flutter#144438 and #177863).
- **Flutter GPU** is a Dart API over Impeller's HAL (`engine/src/flutter/lib/gpu`) for custom renderers,
with Flutter Scene for 3D. In 2026 it is still "early preview… switching to the master channel is
strongly recommended"
([Flutter-GPU.md](https://github.com/flutter/flutter/blob/main/docs/engine/impeller/Flutter-GPU.md)).
### 1.3 Platform views (the cost of hosting native views)
- **Android**
([docs](https://docs.flutter.dev/platform-integration/android/platform-views)) has three modes:
- **Texture Layer:** the native view renders to a texture that Impeller composites. It is "janky during
quick scrolling" and breaks SurfaceView, accessibility and the magnifier.
- **Hybrid Composition:** the native view stays in the Android hierarchy and Flutter renders into
`ImageReader`-backed overlays. It "causes thread merging of raster & platform, which degrades
Flutter FPS". Before Android 10 it also copied every frame.
- **HCPP (experimental):** both Flutter and the native view render to native Surfaces, and
SurfaceFlinger composites them using native transaction sync. It requires API 34+, Vulkan and
Impeller.
- **iOS** uses hybrid composition only. Flutter slices its output into extra overlay Metal layers above
and below each `UIView` (`FlutterPlatformViewsController.mm`, `overlay_layer_pool.mm`). Mutators
(clips, transforms, opacity) are replayed onto the UIView. `ShaderMask` and `ColorFiltered` are not
supported over platform views, and `BackdropFilter` is limited
([iOS platform views](https://docs.flutter.dev/platform-integration/ios/platform-views)). The docs
even suggest screenshotting the native view into a texture while animating.
- **macOS:** the raster thread must synchronize with the platform thread, so "any slow or blocking
operations on the platform thread can negatively impact Flutter graphics performance"
([macOS platform views](https://docs.flutter.dev/platform-integration/macos/platform-views)).
- **Lesson:** hosting native views inside a self-drawn surface is a compositing-synchronization problem
(the GPU frame and the OS layer transaction must land in the same vsync). It is not a drawing problem.
The correct primitive is atomic present-with-transaction:
- iOS/macOS: `CAMetalLayer.presentsWithTransaction` or IOSurface contents in a `CATransaction`.
- Android: SurfaceControl transactions, which is what HCPP does.
- Windows: DirectComposition commit.
### 1.4 Semantics (accessibility)
The framework builds a parallel **SemanticsNode** tree (labels, actions, flags, rects) and sends deltas
to the engine. Each embedder maps the tree onto native accessibility:
- iOS: `SemanticsObject.mm` creates `UIAccessibilityElement`s, plus `TextInputSemanticsObject` for
fields and `FlutterSemanticsScrollView` for scroll containers.
- Android: `AccessibilityNodeInfo`.
- Web: a DOM shadow tree.
Test pumps default to `EnginePhase.sendSemanticsUpdate`, so semantics are exercised in every widget test
(`flutter_test/lib/src/binding.dart:1454`). *Steal:* make the semantics tree a first-class output of
every frame. It doubles as the agent-queryable inspector tree.
### 1.5 Text
- **Layout/shaping:** `txt/` wraps **SkParagraph** (Skia's paragraph module over HarfBuzz + ICU). It
replaced the original libtxt, a fork of Android's Minikin (`engine/src/flutter/txt/src/skia/paragraph_skia.cc`).
- **Rasterization:** Impeller's typographer has a single backend, `typographer/backends/skia`, which
rasterizes glyphs into atlases.
- **Text editing is the weak spot.** On iOS, Flutter implements `UITextInput` on a hidden proxy view and
draws caret, selection and handles itself. `FlutterTextInputPlugin.mm` is 3,403 lines and handles:
- marked text (`kInvalidFirstRect` hacks to hide or show IME candidates);
- the floating cursor;
- `UITextInteraction` for some modes;
- `UIEditMenuInteraction` for the native edit menu;
- dictation placeholders;
- Scribble (`UIIndirectScribbleInteraction`).
Every new iOS text feature has to be re-implemented, and parity always lags.
### 1.6 Hot reload (why it works and what it can't do)
- **Mechanism** ([docs](https://docs.flutter.dev/tools/hot-reload)):
1. The tool recompiles only the changed libraries, plus the path from `main` to them, into Dart
**kernel** files.
2. It ships them over the VM service.
3. The VM reloads the libraries in place. The heap and all objects stay alive, and "so far no code is
re-executed".
4. The framework then calls `reassemble`, which rebuilds, relayouts and repaints every widget.
The docs show "Reloaded 1 of 448 libraries in 978ms". In practice it is often 200–800 ms
**(estimate)**. It works over USB/Wi-Fi to physical iPhones in debug (JIT) builds.
- **Why it works so well:**
- The JIT VM can swap function bodies and class shapes under a live heap.
- UI is a pure function of state (`build`), so re-running `build` everywhere shows the new code with
the old state.
- State lives in `State` objects and Elements keyed by tree position, which survive the reload.
- **What it can't do:**
- `main()` and `initState()` are not re-run.
- Global and static field initializers are treated as state, so they are not re-evaluated (const is
the exception).
- Changing an enum to a class or vice versa needs a restart, as do generic arity changes and native
code changes.
- `CupertinoTabView` builders don't reload.
- Release builds are AOT and can't reload at all. The 2026 roadmap explores "interpreted bytecode in
the Dart runtime" for ephemeral code.
- **Rust implication:** there is no VM, so the equivalent has to come from:
1. view and state code in a dylib that is reloaded, or a wasm module, or an interpreted UI DSL;
2. state held outside the reloaded code (an arena keyed by stable ids or tree position);
3. a framework `reassemble()` that rebuilds everything.
Flutter's failure cases show the design rule: **anything evaluated once at startup won't reload**, so
keep configuration in getters or rebuild paths.
### 1.7 Tooling and tests
- **DevTools** talks to the VM service (JSON-RPC over WebSocket) and offers a widget inspector (tree,
layout explorer), a performance view (UI/raster frame bars, timeline), a CPU profiler and memory views
([DevTools](https://docs.flutter.dev/tools/devtools)). In 2025–26 the same service is exposed to
agents through the Dart/Flutter **MCP server** (roadmap 2026, [docs](https://docs.flutter.dev/ai/mcp-server)).
- **Goldens:** `matchesGoldenFile` does an exact pixel comparison (`LocalFileComparator`) and writes
master/test/diff/masked-diff images on failure (`flutter_test/lib/src/_goldens_io.dart`).
`--update-goldens` regenerates them. Determinism comes from:
- the **Ahem** test font (every glyph is a square), via `--use-test-fonts`;
- `FakeAsync` with a fixed clock (`DateTime.utc(2015)`, `binding.dart:2687-2689`);
- `pump(duration)`, which advances virtual time.
- **Device tests:** `integration_test` runs widget-test APIs on a real device. It replaced most
`flutter_driver` use, which was a remote-control protocol.
- **Impeller playground:** any test fixture can open interactively or attach Xcode/RenderDoc captures.
### 1.8 What made Flutter reach six platforms
1. **It owns the pixels.** One renderer and one text stack give identical output everywhere, so a new
platform means implementing an embedder, not a widget set.
2. **A stable C embedder API** (`embedder.h`). Third parties ship their own embedders (automotive,
embedded Linux, flutter-pi), and the 2026 roadmap wants new platforms to be authored "out-of-tree".
3. **The same Dart in two compilation modes:** JIT for development (hot reload) and AOT for release.
4. **Platform channels and FFI** for native APIs. After the thread merge, FFI calls into main-thread-only
APIs are synchronous.
5. **Adaptive but self-drawn design systems** (Material, Cupertino), which are now being decoupled into
separate packages (roadmap 2026).
### 1.9 What still feels non-native
- **Scroll physics are approximations.** `BouncingScrollPhysics` is fitted by overlaying a native
scroll view (`scroll_physics.dart:908`, "Use … platform_tests/scroll_overlay to test with Flutter and
platform scroll views superimposed"):
- friction 0.135 = 0.998¹⁰⁰⁰ (`scroll_simulation.dart:50-53`);
- overscroll resistance `0.52·(1 − overscroll/viewport)²` (`scroll_physics.dart:826`), which is not
Apple's 0.55 formula;
- momentum carry `0.000816·|v|^1.967` (`:921`).
- **Gesture thresholds:** `kTouchSlop` = 18 logical px and `kMinFlingVelocity` = 50 lp/s
(`gestures/constants.dart:65,90`). iOS's swipe hysteresis is "usually 10 points"
([WWDC18 803](https://developer.apple.com/videos/play/wwdc2018/803/)).
- **Text selection, IME, magnifier, context menus.** Re-implemented, as above. `SystemContextMenu` now
uses the native menu on iOS.
- **Keyboard sync.** iOS has no per-frame keyboard callback, so Flutter animates a *hidden UIView* with
the keyboard's curve and samples its `presentationLayer` every vsync
(`KeyboardInsetManager.swift:22-36`). This is a clever, reusable trick for following any system
animation.
- **New system design arrives late or never.** There is still no first-party Liquid Glass (flutter#170310).
Packages such as `adaptive_platform_ui` and `cupertino_native` embed real UIKit controls as platform
views.
- **ProMotion needs `CADisableMinimumFrameDurationOnPhone`** on iPhone. Flutter sets the
`CADisplayLink.preferredFrameRateRange` to `[max/2, max]` (`VSyncClient.swift:89-104`,
`DisplayLinkManager.swift:45-49`). It also replaced `CAMetalLayer` with **`FlutterMetalLayer`**, a
custom IOSurface-backed `CALayer` that presents by setting `contents` inside a `CATransaction` on the
main thread (`FlutterMetalLayer.h:10-15`, `.mm:325-363`). The comment reads "This is needed otherwise
frame gets skipped on touch begin / end. Go figure." Even Google couldn't get stock `CAMetalLayer`
pacing right.
### 1.10 Startup and binary size
- Old official numbers:
- A 2021 FAQ measured a minimal release APK at about 4.3 MB (arm32) and 4.8 MB (arm64)
**(older, from memory of the 2021 FAQ; the current FAQ only says "a few megabytes compressed")**
([FAQ](https://docs.flutter.dev/resources/faq#how-big-is-the-flutter-engine)).
- The iOS demo app in Flutter 1.17 was 5.4 MB download and 13.7 MB installed
([app size](https://docs.flutter.dev/perf/app-size)).
- The engine tracks `hello_world_{android,ios}__compile/release_size_bytes` in CI
([Engine disk footprint](https://github.com/flutter/flutter/blob/main/docs/engine/Engine-disk-footprint.md)).
I found no current public numbers for size or for cold-start time. Engine init plus isolate start is
expensive enough that add-to-app docs recommend pre-warming a `FlutterEngine`
([docs](https://docs.flutter.dev/add-to-app/performance)).
---
## 2. SwiftUI + Core Animation (the feel benchmark)
### 2.1 The render loop and render server
- The five phases ([Explore UI animation hitches](https://developer.apple.com/videos/play/tech-talks/10855/)):
1. **event**
2. **commit**: the app updates the layer tree and "submits that to the render server"
3. **render prepare**: in "a separate process called the render server" (backboardd on iOS,
WindowServer on macOS)
4. **render execute**: on the GPU
5. **display**
Frames are double-buffered, with a triple-buffer fallback that gives the render server an extra frame.
- **Why CA animations survive a blocked main thread:** a `CAAnimation` is committed once as a
description (from/to/timing). The render server interpolates it every frame in its own process. The
model layer holds the final value, and the presentation layer reflects the in-flight value.
- **Kit's launcher experience** (a 120 Hz glass morph moved to CA) is explained by this. Anything expressed
as CA layer animations is immune to app-side hitches.
### 2.2 Implicit, additive and interruptible animation (UIKit/CA)
- **Implicit actions:** setting a layer property inside a `CATransaction` creates a default animation.
UIView suppresses these outside animation blocks.
- **Additive by default since iOS 8**
([WWDC14 236 notes](https://wwdcnotes.com/documentation/wwdc14-236-building-interruptible-and-responsive-interactions/)).
A new UIView animation on a property that is already animating no longer snaps or replaces. It adds a
relative animation (from old target to new target) on top of the running one, so the presentation
value stays continuous. That is how UIKit got interruptibility without reading presentation state.
- **`UIViewPropertyAnimator`** (iOS 10,
[WWDC16 216](https://developer.apple.com/videos/play/wwdc2016/216/)) is interruptible, scrubbable
(`fractionComplete`) and reversible, and continues with new timing parameters.
`UISpringTimingParameters(initialVelocity:)` takes a *unit-relative* velocity (points/s ÷ distance).
- **`CASpringAnimation`:** iOS 17 added `init(perceptualDuration:bounce:)`, and
`UIView.animate(duration:bounce:)` gives UIKit the same parameterisation
([WWDC23 10158](https://developer.apple.com/videos/play/wwdc2023/10158/)).
### 2.3 SwiftUI's Animation/Transaction model
- **Transactions.** State changes happen inside a `Transaction`, which carries the `Animation` and
flags such as `disablesAnimations`. `withAnimation` sets it explicitly, and `.animation(_:value:)`
sets it implicitly for a subtree. iOS 17 added custom `TransactionKey`s and completion criteria
(`.logicallyComplete` uses the perceptual duration, not the settling time).
- **Animatable attributes vs. animations**
([WWDC23 10156](https://developer.apple.com/videos/play/wwdc2023/10156/)). The animatable data is a
`VectorArithmetic` value. The animation is a function `(target, elapsed, context) → value?`. The
`CustomAnimation` protocol (iOS 17) has `animate`, `velocity` and `shouldMerge`.
- **Merging.** When `shouldMerge` returns true, the new animation inherits the previous one's state and
elapsed time and replaces it. Springs merge and **preserve velocity**. The default (false) runs both
animations and combines their results, which is additive like UIKit
([shouldMerge docs](https://developer.apple.com/documentation/swiftui/customanimation/shouldmerge(previous:value:time:context:))).
Docs for `spring(duration:bounce:blendDuration:)`: "each spring animation will be replaced by their
successor, preserving velocity from one animation to the next."
- **Where the evaluation happens:**
- "For built-in animatable attributes like scaleEffect, SwiftUI … is able to do this work off the
main thread and without calling into any of your view code."
- A custom `Animatable` view "will run body for every frame of the animation" (WWDC23 10156).
- "The SwiftUI animation does not create a CAAnimation, but instead animates the view's layer's
presentation values directly" (WWDC24 10145, on using SwiftUI `Animation` with UIKit in iOS 18).
**So the state of the art is in-process, per-frame spring evaluation on a non-main animation thread.**
It is not render-server keyframes.
- **Velocity handoff from gestures** (WWDC24 10145). During a drag, each change event starts an
`.interactiveSpring` that retargets the previous one. On release, a normal spring is merged in, and
"uses the velocity from the interactiveSprings, to carry the animation forward with continuous
velocity". There is no manual velocity computation. iOS 18 brought the same behaviour to UIKit and
AppKit (`UIView.animate(_ animation: Animation)`).
- **`matchedGeometryEffect`** (iOS 14) synchronizes geometry for views that share an id in a
`@Namespace`. When one view is inserted and another removed in the same transaction, SwiftUI
"interpolate[s] their frame rectangles in window space" ([docs](https://developer.apple.com/documentation/swiftui/view/matchedgeometryeffect(id:in:properties:anchor:issource:))).
It links geometry only; the enter and exit rendering are normal transitions. Liquid Glass's
`glassEffectID` is the same idea applied to glass morphing.
### 2.4 Springs: duration + bounce
Apple's conversion is on the "Spring Parameter Conversion" slide of WWDC23 10158. The transcript's text
version is garbled, so the formula below is derived and matches Flutter's implementation:
```
mass = 1
stiffness k = (2π / duration)²
damping c = 4π(1 − bounce) / duration bounce ≥ 0 (ζ = 1 − bounce)
c = 4π / (duration · (1 + bounce)) bounce < 0 (ζ = 1/(1+bounce))
```
- "duration" is a **perceptual duration**. It is roughly the settle time, and for very bouncy springs it
is the oscillation period. It is deliberately not the settling duration, which is unpredictable.
- Bounce ranges from −1 to 1. The default is 0 (critically damped), which is "what you get if you don't
specify the bounce".
- Springs have been the default `withAnimation` animation since iOS 17.
- Presets: `.smooth` (no bounce), `.snappy` (small bounce), `.bouncy` (more bounce). Each takes
`duration:` and `extraBounce:`.
- Flutter's identical implementation is in `physics/spring_simulation.dart:70-82`. Its doc comment says
"This constructor produces the same result as SwiftUI's `spring(duration:bounce:blendDuration:)`".
Reference values (computed):
| spec | k | c / ζ |
|---|---|---|
| d=0.5, b=0 | 157.9 | 25.13 / 1.0 |
| d=0.5, b=0.15 | 157.9 | 21.36 / 0.85 |
| d=0.5, b=0.3 | 157.9 | 17.59 / 0.7 |
| Compose default `spring()` (k=1500, ζ=1) | 1500 | ≡ d≈0.162 s, b=0 |
| M3 Expressive default spatial (k=380, ζ=0.8) | 380 | ≡ d≈0.322 s, b=0.2 |
### 2.5 Scroll physics
- **Deceleration:** `UIScrollView.DecelerationRate.normal` = 0.998 and `.fast` = 0.99. Each is the
velocity multiplier per millisecond (Flutter's comment confirms 0.998, `scroll_simulation.dart:50`).
Velocity follows v(t) = v₀·rᵗᵐˢ.
- **Projection** (WWDC18 803 sample code): `project(v) = (v/1000)·r/(1 − r)`. With r = 0.998, a
1000 pt/s fling travels about 499 pt. With 0.99 it travels about 99 pt. Use it to pick snap targets
from the *projected* position, not the release position.
- **Rubber band:** `b = (1 − 1/(x·c/d + 1))·d` with c = 0.55 and d = the viewport dimension. This was
reverse-engineered ([gist](https://gist.github.com/originell/6961057)) and is widely reused. On an
844 pt iPhone, 100 pt of drag gives about 51.6 pt of movement and 400 pt gives about 174.5 pt. The
release springs back with an overdamped-ish spring.
- **Scroll edge effects.** In iOS 26 the system applies a "subtle blur and fade" under bars
(`scrollEdgeEffectStyle`, [WWDC25 323](https://developer.apple.com/videos/play/wwdc2025/323/)). That
is Apple formalising Kit's "no hard clipped edges".
### 2.6 ProMotion frame pacing
- **`CADisplayLink.preferredFrameRateRange`** (iOS 15+) takes a min/max/preferred range. On iPhone,
rates above 60 Hz need `CADisableMinimumFrameDurationOnPhone = true` in Info.plist (Flutter
`DisplayLinkManager.swift:45-49`). CA animations get their rates from the system automatically.
- **`CAMetalDisplayLink`** (iOS 17, macOS 14,
[docs](https://developer.apple.com/documentation/quartzcore/cametaldisplaylink)) is made for Metal
renderers that "need more control over the timing window":
- its delegate receives an update containing a drawable and a `targetPresentationTimestamp`
("update your animations based on the time difference between this timestamp and the previous
timestamp");
- `preferredFrameLatency` accepts only 1 or 2 frames, and "may be bigger … for windowed modes on
macOS".
- Caveat: Rive reported that `CAMetalDisplayLink` "is currently causing crashes on _some_ iOS
devices" and fell back to `CADisplayLink`
([rive-ios#349](https://github.com/rive-app/rive-ios/issues/349)).
- **Adaptive-Sync on Mac** ([WWDC21 10147](https://developer.apple.com/videos/play/wwdc2021/10147/)):
use `presentAfterMinimumDuration` / `presentAtTime` for even pacing on VRR displays. Relying on
drawable back-pressure gives uneven frames.
- **Rule for Rune:** always animate against the *target presentation time*, not the callback time.
The animation clock must advance by actual presented intervals, so that a dropped frame produces a
bigger step rather than a stall. That is what keeps motion on its curve.
### 2.7 Liquid Glass (iOS/macOS 26)
- **What it is** ([WWDC25 219](https://developer.apple.com/videos/play/wwdc2025/219/)):
- a material defined by **lensing** (refraction of the content behind it);
- layers that "continuously adapt based on what's behind it" (shadow, tint, dynamic range,
independent light/dark flipping);
- morphing between control states.
- Its rules: no glass on glass, and Regular and Clear variants are never mixed.
- **APIs:**
- SwiftUI: `glassEffect(_:in:)`, `GlassEffectContainer`, `glassEffectID`.
- UIKit: `UIVisualEffectView` + `UIGlassEffect` / `UIGlassContainerEffect`.
- AppKit: `NSGlassEffectView` (`contentView`) / `NSGlassEffectContainerView` (`spacing`).
- These are OS 26+ only ([glassEffect docs](https://developer.apple.com/documentation/swiftui/view/glasseffect(_:in:))).
- **Mechanics that matter for hosting:**
- "This effect is achieved by sampling content from an area larger than itself. However, glass can
not sample other glass" (WWDC25 323).
- AppKit: put content in `contentView` so that the system applies vibrancy and legibility treatment.
"Avoid placing the NSGlassEffectView behind your content as a sibling view"
([WWDC25 310](https://developer.apple.com/videos/play/wwdc2025/310/)).
- **Can a custom renderer reproduce it?** It could approximate it: an SDF capsule, backdrop
blur/refraction with a displacement map, a rim highlight, adaptive tint from backdrop luminance. Rive
feathering or a WGSL backdrop shader could get close. It will not track Apple's per-release tuning,
accessibility settings (Reduce Transparency, Increase Contrast) or system-wide light response. Flutter
contributors argue it would "not 100% match" and would lag behind
([flutter#170310 comment](https://github.com/flutter/flutter/issues/170310#issuecomment-2958004370)).
- **Can it host it? Yes, with constraints (inference; spike needed).**
- The glass is a CA layer subtree. The render server samples whatever is composited below it, and a
`CAMetalLayer`/IOSurface layer is ordinary composited content, so a Rune surface *under* a native
glass view should refract correctly.
- Content *on* the glass (labels, icons) must be inside the glass's `contentView` to get vibrancy. That
means either native views, or a second Rune surface (a Metal layer) placed inside `contentView`,
with legibility treatment applied by Rune rather than the system.
- Glass geometry (position, size, morph) must be animated with CA or SwiftUI in the *same transaction*
as Rune's frame. Otherwise glass and content drift by a frame. This is the same sync problem as
Flutter's platform views.
- In practice: drive glass shapes from Rune's layout, and commit them through `CATransaction` with
the Metal present (`presentsWithTransaction`, or IOSurface `contents` like `FlutterMetalLayer`).
Use the system's `GlassEffectContainer` morphing where possible.
### 2.8 What a non-Apple framework must replicate to feel native on iOS
The full checklist is in "What Rune must match" below. The core is:
- continuity of position and velocity on every interruption;
- spring-default motion with duration/bounce;
- gesture → animation handoff by merging;
- the exact scroll constants;
- 120 Hz pacing against the presentation timestamp;
- native text input and accessibility;
- system materials and transitions hosted rather than faked.
---
## 3. Rive, Figma, Lottie/Skottie
### 3.1 Rive renderer (`rive-runtime/renderer`, MIT)
- **Design.** It is a vector and raster renderer "custom-built for Rive content, for animation, and for
runtime". Backends: Metal, Vulkan, D3D11/12, GL/WebGL2, WebGPU (`renderer/src/{metal,vulkan,d3d11,d3d12,gl,webgpu}`).
`RenderContext` "manages all the GPU buffers… required for Rive's pixel local storage path rendering
algorithm" (`include/rive/renderer/render_context.hpp:86-88`).
- **Paths.** Béziers are tessellated *on the GPU* (`shaders/tessellate.glsl`) into triangle patches
around the edges. The antialiasing is described in the
[feathering blog](https://rive.app/blog/how-rive-reinvented-feathering-for-the-vectorian-era):
"triangle-based coverage interpolation… Depending on whether a triangle naturally falls clockwise or
counterclockwise, it contributes positive or negative coverage to a pixel."
- **Interlock modes** (`include/rive/renderer/gpu.hpp:1073-1088`):
- `rasterOrdering`: pixel local storage / raster order groups on Apple and Android tile GPUs;
- `atomics`;
- `clockwise` and `clockwiseAtomic`: these override fill rules with "clockwise" (only positive
winding fills), which makes atomics usable without barriers;
- `depthStencil` (MSAA fallback).
Gradients go into a 512-wide ramp texture (`constants.glsl:61`). Advanced blend modes are implemented
in-shader.
- **Vector feathering** (shipped February 2025):
- "Instead of an anti-aliasing ramp that's one pixel wide, we could extend it to any width… shape that
transition based on a normal distribution curve." The feather opacity "is the integral of the normal
distribution function", centred on the true edge.
- Corners and curves need a 2D integral. The shader uses a separability trick plus a precomputed
**Gaussian-integral 1D texture** (`constants.glsl:64-73`, `GAUSSIAN_INTEGRAL_TEXTURE_STDDEVS = 3`)
and evaluates per-corner coverage in `eval_feathered_fill` (`draw_path_common.glsl:186-204`).
- Large feathers go through a feather atlas (`FEATHER_ATLAS_BLIT`).
- It needs the Clockwise fill rule. NoesisGUI notes it is "tightly coupled to their own custom
renderer" ([forum](https://www.noesisengine.com/forums/viewtopic.php?t=3718)).
- **Text:** HarfBuzz + SheenBidi shaping (`premake5_v2.lua:97-98`, `src/text/`). Glyphs render as paths
through the same analytic AA, which is "Perfect text… crisp at any size".
- **The runtime is quietly becoming a UI framework.** It has:
- Yoga layout (`dependencies/premake5_yoga_v2.lua`, `src/layout/`);
- state machines with layers, blend states and transitions;
- listeners for pointer, keyboard, focus, gamepad, plus `semantic_listener_group.cpp`;
- data binding / view models (`src/viewmodel`);
- Luau scripting (`src/lua`, `scripting/`);
- a threaded command queue/server (`command_queue.cpp`, `command_server.cpp`).
Rive's state machine is declarative animation-as-data: inputs (bool/number/trigger) or view-model
properties drive transitions with conditions and blend durations. It is evaluated by
`advance(dt)`, which is deterministic.
### 3.2 Figma renderer
- **Architecture** (2015, [Evan Wallace](https://www.figma.com/blog/building-a-professional-design-tool-on-the-web/)):
- a C++ editor compiled with Emscripten (asm.js, then wasm);
- all memory in one typed array, so there are no GC pauses;
- a "highly-optimized **tile-based** engine with support for masking, blurring, dithered gradients,
blend modes, nested layer opacity";
- "our own DOM, our own compositor, our own **text layout engine**", because browser text layout
"is inconsistent between browsers… and even… platforms". Their biggest web pain was "lack of access
to glyph outlines and kerning tables".
- **WebGPU migration** (shipped September 2025,
[Figma rendering: Powered by WebGPU](https://www.figma.com/blog/figma-rendering-powered-by-webgpu/)):
1. They redesigned the graphics interface **before** touching WebGPU. Draw calls take explicit
arguments, `context->draw(vertexBuffer, framebuffer, {texture}, material, …)`, instead of global
binds. This "fixed a handful of bugs in our WebGL renderer before we even touched WebGPU".
2. Uniforms are batched: `encodeDraw(uniforms, material)…submit()` uploads all uniform data to one
buffer with offsets.
3. Shaders stay in WebGL1 GLSL. A custom preprocessor upgrades them, then **naga** (wgpu's
translator) emits WGSL, and layouts are reflected for the app.
4. The same C++ renderer goes to wasm (browser WebGPU through Emscripten bindings, moving to Dawn's
`emdawnwebgpu`) and to native x64/arm64 (server-side rendering, tests, debugging) via **Dawn**.
5. Readback is async-only in WebGPU, so load-blocking GPU self-tests became impossible. Instead there
is a **dynamic mid-session fallback** from WebGPU to WebGL, modelled on context-loss handling, plus
device blocklists keyed by fallback rate.
6. Results: "a performance improvement… on some classes of devices… neutral on others, but no
regressions". Next up are compute-shader blur, MSAA and RenderBundles.
- **Perf process** ([Keeping Figma fast](https://www.figma.com/blog/keeping-figma-fast/)): every PR runs
perf scenarios in under 10 min, in parallel, on GPU VMs plus a targeted real-hardware farm. They
rejected counting CPU instructions because the bottleneck is sometimes the GPU or I/O.
### 3.3 Lottie and Skottie: animation as data
- **Lottie** is JSON exported from After Effects (Bodymovin, 2015). It is now an open spec stewarded by
the Lottie Animation Community, with a published spec, a validator and compliance tests
([lottie.github.io](https://lottie.github.io/)).
- **Skottie** (Skia's player, `modules/skottie/include/Skottie.h`) does the following:
- `Animation::Builder` parses the JSON once into an **sksg scene graph** (`sk_sp<sksg::RenderNode>`)
plus a list of animators;
- `seek(t)` / `seekFrame` / `seekFrameTime(t, InvalidationController*)` run the animators to mutate
node properties and collect damage rects;
- `render(canvas)` draws.
- Hooks: `PropertyObserver` for runtime overrides, `MarkerObserver`, `PrecompInterceptor`,
`ExpressionManager` (AE expressions), and a pluggable text shaper.
- **Why it matters for Rune:**
1. The output is a pure function of t, so any frame can be rendered headlessly, which makes goldens
of motion trivial.
2. Designers author and engineers bind.
3. Damage tracking falls out of property invalidation.
Rive goes further with interactive state machines. Lottie is timeline-only.
---
## 4. Jetpack Compose (the Android feel reference, briefly)
- **Runtime.** A compiler plugin turns `@Composable` functions into calls against a **slot table**: a
gap buffer holding groups, remembered values and keys, with positional memoization
([Under the hood of Compose, 2020](https://medium.com/androiddevelopers/under-the-hood-of-jetpack-compose-part-2-of-2-37b2c20c6cdd), older).
Snapshot state tracks reads per scope, and recomposition reruns only the scopes that read changed
state, skipping when inputs are stable. **New in 2026:** an opt-in linked-list slot table
(`ComposeRuntimeFlags.isLinkBufferComposerEnabled`, default false) "designed to improve performance
primarily when deleting, moving, and reordering" ([source](https://github.com/androidx/androidx/blob/androidx-main/compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/ComposeRuntimeFlags.kt)).
- **Phases:** composition → layout (measure, then place, with separate restart scopes) → draw
([docs](https://developer.android.com/develop/ui/compose/phases)). **Deferred state reads** inside
`Modifier.offset { }` or `graphicsLayer { }` lambdas skip composition and remeasure. That is how
per-frame animations stay cheap, and it is a key pattern for Rune: animated values should
invalidate *paint/transform only*, never rebuild.
- **Animation:**
- `Animatable` (a coroutine-based single value): `animateTo` "continu[es] the current value and
velocity", and `animateDecay` handles flings.
- `animate*AsState` and `updateTransition` default to `spring()`, which "guarantees the continuity of
velocity when target value changes" ([docs](https://developer.android.com/develop/ui/compose/animation/customize)).
- `Spring` constants (`animation-core/api/current.txt:681-690`): `DampingRatioNoBouncy` 1.0,
`LowBouncy` 0.75, `MediumBouncy` 0.5, `HighBouncy` 0.2. `StiffnessHigh` 10000, `Medium` 1500
(the default), `MediumLow` 400, `Low` 200, `VeryLow` 50.
- Material 3 Expressive `MotionScheme` tokens: default spatial k=380, ζ=0.8; fast spatial k=800,
ζ=0.6; effects ζ=1 (`ExpressiveMotionTokens.kt`).
- Compose parameterises springs by stiffness and damping ratio. Apple's duration/bounce is the more
designer-legible API, and the two convert losslessly (table in §2.4).
- **The RenderThread analogue.** Android's HWUI RenderThread can run `RenderNodeAnimator`s, as ripples
do, while the UI thread is blocked. That is a partial equivalent of CA's render server.
---
## What Rune must match to feel native on iOS/macOS
1. **120 Hz, paced to presentation time.**
- iPhone needs `CADisableMinimumFrameDurationOnPhone` and a `preferredFrameRateRange` up to the
maximum.
- Animate against `targetPresentationTimestamp` (`CAMetalDisplayLink` on iOS 17+/macOS 14+, with a
`CADisplayLink` fallback given Rive's crash report).
- Use frame latency 1 when possible.
- Drop to lower rates when idle.
2. **Present atomically with CA transactions.** If any native layer, glass or system view moves with
Rune content, the Metal present and the CA geometry change must commit together. Learn from
`FlutterMetalLayer`: IOSurface pool, `contents` swap inside `CATransaction`, skip stale-size frames.
3. **Springs exactly like Apple's:**
- `spring(duration, bounce)` with default bounce 0, the formula in §2.4, perceptual-duration
completion, and the presets smooth/snappy/bouncy.
- Per-property independent springs that start and stop at different times.
4. **Retargeting that preserves position and velocity on every interruption:** merge semantics (springs
replace and inherit velocity) and additive semantics for non-mergeable curves.
5. **Gesture handoff by merging:** interactive springs during a drag (short duration, tracking), then a
final spring that inherits velocity. Choose snap targets by projected position
(`v/1000·r/(1−r)`). Swipe hysteresis is about 10 pt.
6. **The scroll view, bit for bit:** deceleration 0.998/0.99 per ms, the 0.55 rubber band, momentum
carry on repeated flings, the overscroll spring, paging, scroll-edge soft fade. Verify by overlaying a
real `UIScrollView` and comparing traces (Flutter's `scroll_overlay` method).
7. **An animation clock off the main thread** for transform, opacity, clip, colour and filter, like
SwiftUI's built-in animatable attributes. A main-thread stall should cost layout updates, not motion.
Optionally, lower trivially describable animations to `CAAnimation` for full immunity.
8. **Layout animation with identity:** matched-geometry-style interpolation in window space across
insert and remove, with transitions for enter and exit. Nothing pops.
9. **Soft edges as a primitive:** analytic feathered fills and masks (Rive-style Gaussian-integral
coverage). Make scroll-edge fades and clip feathering cheap enough to be the default.
10. **Native text input and accessibility.** Implement `UITextInput`/`NSTextInputClient` properly,
including marked text, dictation, Scribble, the floating cursor and edit menus. Expose a semantics
tree to `UIAccessibility`/`NSAccessibility`. Follow system keyboard animations; Flutter's hidden-view
`presentationLayer` sampling is a usable trick.
11. **Hosting, not faking, system materials and controls:** Liquid Glass via
`UIGlassEffect`/`NSGlassEffectView` positioned by Rune's layout; system menus, sheets and share UI.
## What to steal from Flutter's reach strategy
- **Own the pixels behind a tiny embedder contract**: surface, vsync with timestamps, input, IME,
accessibility tree, clipboard, windows. Write it down as a Rust trait plus a C ABI so third parties
(and agents) can add platforms out of tree.
- **Precompile every pipeline** (Impeller). Use WGSL or Slang compiled at build time, reflected into
Rust structs, with no runtime shader compilation.
- **A display-list seam** between UI and renderer, so recorded frames can be replayed headlessly,
diffed, serialised for bug reports, and dispatched to multiple backends.
- **Semantics as a first-class frame output.** It is also the queryable inspector tree for agents.
- **Deterministic test mode:** a fake clock, a box-glyph test font option alongside real-font goldens,
`pump(duration)`, exact-pixel goldens with diff and masked-diff artifacts, `--update-goldens`.
- **Hot reload with state kept outside the reloaded code** and a full `reassemble()` rebuild. Flutter's
documented failure list (startup initializers, statics, type-shape changes) is the spec for what to
design around.
- **One renderer on the web too.** Figma's architecture (same code on native and wasm, Dawn/wgpu under
both) rather than Flutter's separate web engine.
- **Labelled GPU resources and a "playground" harness** that opens any test in a window or attaches a
frame capture.
## What to avoid
- **Re-implementing text editing and selection.** This is Flutter's longest-running parity gap (3,400
lines of `UITextInput` shim on iOS alone). Use the platform's text input protocols and system menus.
Render glyphs yourself but delegate behaviour.
- **Platform views as an afterthought.** Thread merging, extra overlay layers per native view, and
unsupported filters over native views all come from not designing for atomic CA/SurfaceControl
composition up front.
- **Approximate scroll physics hand-tuned per platform** without a measurement loop. Constants should be
either exact (Apple's are known) or fitted against an overlay test.
- **MSAA-only antialiasing** for UI vectors (Impeller defaults to 4× MSAA). Use analytic coverage.
- **A separate web engine.**
- **Imitating system design languages** (Cupertino imitating UIKit). They drift every year, as Liquid
Glass shows. Host system components where "native" matters, and make Rune's own design language
first-class everywhere else.
- **Stock `CAMetalLayer` assumptions.** Flutter needed a custom layer to avoid skipped frames, and Rive
saw `CAMetalDisplayLink` crashes. Budget a pacing spike with frame traces on real devices.
---
## Recommendation for Rune
1. **Animation model.** Adopt Apple's semantics exactly:
- `Spring { duration, bounce }` as the only user-facing spring type, with a stiffness/damping escape
hatch;
- merge-with-velocity for springs, additive composition for curves;
- interactive-spring gesture tracking with merge-on-release;
- perceptual-duration completion.
Evaluate on a dedicated animation and render thread that reads a snapshot of the animatable
properties. The main thread only commits targets. This reproduces SwiftUI's built-in behaviour and
keeps motion alive through UI-thread hitches.
2. **Frame pacing.**
- Darwin: `CAMetalDisplayLink` (latency 1) with a `CADisplayLink` fallback.
- Present through a Flutter-style IOSurface `CALayer` *or* `CAMetalLayer` with
`presentsWithTransaction` when native layers must stay in sync. Decide by spike with Instruments
hitch traces on an iPhone Pro and a Mac with ProMotion.
3. **Renderer quality bar.** Analytic AA plus a feathered-edge primitive (Rive's approach) as table
stakes. Feathered masks are the default clip style.
4. **Native integration.** Build first-class "host layer" nodes, whose CA layers are placed and
animated in the same transaction as Rune frames, from day one. Spike Liquid Glass hosting (Metal
content under `UIGlassEffect`, Rune-driven glass geometry) before committing to any custom glass.
5. **Testing.** Deterministic headless mode (fake clock, seekable animations, display-list dumps,
golden PNGs with diff artifacts) plus a scroll/spring overlay harness that compares Rune traces
against `UIScrollView` and `CASpringAnimation` traces numerically.
**Rejected alternatives**
- *Lower all motion to Core Animation (CA-as-renderer).* It gives perfect hitch immunity, but it ties
the renderer to Apple, prevents custom shaders and feathering inside animated content, and doesn't
port. Apple's own SwiftUI no longer works this way.
- *Wrap Flutter or Impeller.* Brief says own the stack. Impeller's MSAA/SDF quality is below the bar,
and Dart is the wrong language.
- *Use Rive's renderer directly.* It is MIT and high quality, but it is C++ and specialised for `.riv`
content. Port the algorithms (clockwise fill, analytic feathering) into Rune's Rust renderer, or
compare against Vello (see other reports).
- *A Cupertino-style imitation widget set.* Ruled out by the Liquid Glass lesson.
## Open questions
1. Does a `CAMetalLayer` (or IOSurface layer) under `UIGlassEffect`/`NSGlassEffectView` refract with
full fidelity, and can glass geometry be animated in lockstep with Metal presents at 120 Hz?
(Spike on iOS 26 and macOS 26.)
2. How stable is `CAMetalDisplayLink` on current iOS (26.x)? Is the Rive crash still reproducible?
3. Does SwiftUI's off-main-thread evaluation survive a fully blocked main thread, or does it only avoid
calling view code? Measure with a deliberate 200 ms main-thread stall during `.spring` scaleEffect,
versus a `CASpringAnimation`.
4. Are Apple's exact rubber-band and paging constants unchanged in iOS 26? Measure by tracing
`UIScrollView.contentOffset` per frame and fitting.
5. What is the cost of analytic feathering vs. a separable blur at UI scale (hundreds of soft-edged
rects at 120 Hz on an A-series GPU)? Benchmark Rive's renderer `path_fiddle` vs. Vello on a reserved Mac.
6. Hot reload on a physical iPhone without a JIT: is a wasm UI module, an interpreted DSL, or dylib
reload viable under iOS code-signing rules in debug builds? (Flutter relies on the Dart VM's JIT in
debug.)
+332
View File
@@ -0,0 +1,332 @@
# 04 — Language, GPU API, 2D Renderer Design & Input-to-Photon Latency
## 1. Executive Summary
Rune’s foundational bet is **Rust + a thin custom GPU HAL (~1,800 LOC per native backend) over raw Metal (macOS/iOS) and `wgpu` (Linux/Windows/WebGPU), paired with a hybrid Core Animation compositor host (`NSGlassEffectView`/`UIVisualEffectView` + `CAMetalLayer`) and an uber-primitive instanced SDF + Sparse-Strips/Slug renderer**.
1. **Language — Rust (with thin Swift/ObjC2 platform shims and Dioxus `subsecond` hot-patching):** Rust remains the only systems language in 2026 that simultaneously gives zero-GC deterministic frame times, production-grade text/layout/accessibility crates (`taffy`, `parley`, `harfrust`, `fontations`, `swash`, `accesskit`), fearless multi-threaded background work, and top-tier LLM/agent synthesis reliability (compiler diagnostics + strict type/borrow checking catch hallucinations before runtime). Its historical weakness—1–3 s incremental UI iteration—is solved in 2025–2026 by **ThinLink + jump-table binary hot-patching (`subsecond`)** (<200–500 ms stateful UI patches) plus `-Zthreads=8`, `-Zshare-generics=y`, and `mold`/`wild`/Apple `ld_prime`.
2. **GPU API — Custom Thin HAL (`RuneGpu`) with First-Class Raw Metal on Apple + `wgpu` 28+ Elsewhere:** Neither pure `wgpu` everywhere nor four hand-written native backends is optimal. On macOS/iOS, raw Metal (`objc2-metal`) combined with a shallow `CALayer` host tree is mandatory for zero-copy `IOSurface` video/camera surfaces, `NSGlassEffectView` liquid glass backdrops, `CATransaction`-synchronized window resizing (`presentsWithTransaction`), programmable tile/framebuffer fetch, and EDR headroom. On Linux, Windows, and Web, Zed’s February 2026 migration from `blade-graphics` to `wgpu` ([zed#46758](https://github.com/zed-industries/zed/pull/46758), cutting median CPU draw time from 301 µs to 236 µs) proves `wgpu` is now fast enough and eliminates thousands of lines of Vulkan/D3D12 driver-quirk maintenance while giving WebGPU for free.
3. **2D Renderer — Single-Pass Uber-SDF Primitives + Public-Domain `Slug` (Large/Transformed Text & Icons) + `vello_gpu` Sparse Strips (Complex Vector Art):**
- **95% of UI** (rounded boxes, per-corner radii, elliptical inner borders, analytic 4-sample `erf` Gaussian drop/inner shadows, bevel/specular surface materials, Oklab gradients with Jimenez IGN triangular dithering, and **analytic 4-edge soft-clip masks**) renders in a **single instanced uber-shader pass** with zero geometry tessellation and zero intermediate passes.
- **Text** uses a dual-path pipeline: crisp hinted grayscale/subpixel raster atlas (`R8Unorm`/`RGBA8Unorm`) for body/code text (`≤ 32 px` axis-aligned), switching seamlessly to **Eric Lengyel’s Slug algorithm** (dedicated to the public domain in March 2026, [EricLengyel/Slug](https://github.com/EricLengyel/Slug), and already proven in Makepad’s `draw_text.rs`) for zoomable canvas text, large headings, rotated/sheared labels, and monochrome vector icons.
- **Arbitrary vector paths** (charts, complex SVGs, strokes) use Linebender’s 2026 **`vello_gpu` Sparse Strips** pipeline (4×4 pixel blocks after SIMD CPU flattening) rather than heavyweight full-GPU compute `vello` or CPU triangle tessellation (`lyon`).
4. **Latency — Event-Driven Unthrottled Input Fast-Path + `CADisplayLink` Animation Pacing (< 6 ms p50 on 120 Hz ProMotion):** Waiting for a display link callback before processing input or acquiring a drawable adds 16–49 ms of pipeline lead (measured at 41.5 ms / 5 refreshes in windowed `CAMetalDisplayLink` on 120 Hz macOS). Rune decouples discrete input from `CADisplayLink`: keystrokes, clicks, and trackpad scrolls immediately wake the UI thread, update state, encode a <0.4 ms Metal pass into a `maximumDrawableCount = 2` ring, and present on the very next scanout (~4–8 ms input-to-photon on 120 Hz ProMotion), engaging `CADisplayLink` (`preferredFrameRateRange`) only while springs or timeline animations are in flight.
---
## 2. Detailed Findings by Topic
### Topic 1: Programming Language Evaluation (2026 Landscape)
#### Comparative Matrix
| Dimension | Rust (2024 Ed. / 1.86+) | Swift 6.3 / 6.4 | Zig 0.15 / 0.16-dev | C++23 / C++26 | Odin / Jai / Mojo |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **Runtime Perf & Tail Latency** | **A+** (No GC, no pervasive ARC atomic traffic, SIMD via `wide`/`std::simd`) | **B+** (ARC retain/release traffic & existential boxing unless carefully annotated) | **A+** (Manual allocators, `@Vector` SIMD, zero hidden control flow) | **A+** (Zero-cost abstractions, mature intrinsics) | **A** (Odin/Jai manual memory; Mojo focused on AI kernels) |
| **Platform Reach (macOS, iOS, Win, Linux, Android, Web)** | **A+** (Tier-1 native everywhere + `wasm32-unknown-unknown` <1 MB) | **B** (macOS/iOS A+; Android SDK added in 6.3; Wasm 6.2+ still bulky; Linux/Win GUI immature) | **A** (Cross-compiles everywhere; mobile/Web bindings require manual C glue) | **A** (Everywhere via CMake/Emscripten, painful packaging) | **C** (Odin/Jai weak on iOS/Android/Web; Mojo has no GUI targets) |
| **UI Ecosystem (Text, Layout, A11y)** | **A+** (`taffy`, `parley`, `harfrust`, `fontations`, `swash`, `accesskit`, `kurbo`) | **C** (Apple-only `CoreText`/`NSAccessibility`; zero cross-platform equivalents) | **C** (Wraps C libraries: `harfbuzz`, `freetype`, `stb_truetype`; no `accesskit`) | **A-** (`HarfBuzz`, `Skia`, `DirectWrite`, `Yoga`, `ICU` — heavy C++ deps) | **D** (Must bind C libraries from scratch) |
| **Incremental Compile Speed** | **B** (0.8–2.5 s cold-ish crate rebuild; **<0.4 s** with `subsecond` ThinLink) | **B-** (Swift Build 6.4 fast for small modules, slow on heavy generics/macros) | **A+** on Linux x86_64 (<150 ms via `Elf2`); **C+** on macOS arm64 (Mach-O incremental WIP) | **C** (Header/module bloat; 2–10 s incremental link) | **A+** (Odin ~0.3 s; Jai <0.2 s full builds) |
| **Hot-Reload Friendliness** | **A-** (`subsecond` jump-table binary patching + dylib state preservation) | **A-** (`@_dynamicReplacement` + Mach-O `-bundle_loader`, ~100–300 ms on macOS) | **B+** (Clean C ABI `dlopen` state reload) | **B** (Live++ on Windows; fragile `dlopen` on macOS) | **A** (Odin/Jai trivial DLL reload) |
| **Agent-Writability (LLM Synthesis)** | **A+** (Exhaustive `rustc`/Clippy errors guide autonomous self-repair; huge corpus) | **B+** (Swift 6 strict concurrency region errors frequently trip LLMs) | **C+** (0.14→0.15→0.16 stdlib/build.zig churn causes stale LLM syntax) | **B** (Template SFINAE errors and UB escape compiler checks) | **D** (Small training corpus; Jai closed beta) |
| **Memory & Thread Safety** | **A+** (`Send`/`Sync` compile-time race freedom; `unsafe` quarantined to FFI) | **A** (Swift 6 data-race safety + ARC, but Reference Cycles leak) | **C** (Spatial checks in Debug, manual lifetime/thread discipline) | **D** (Use-after-free, iterator invalidation, data races) | **C** (Manual memory management) |
#### Deep Dive on the Contenders
1. **Rust’s Compile-Time & Hot-Reload Reality in 2026:**
- **Compiler & Linker Gains:** The [2025 Rust Compiler Performance Survey](https://blog.rust-lang.org/2025/09/10/rust-compiler-performance-survey-2025-results) identified single-crate incremental rebuilds and `cargo check`/`cargo build` cache splitting as top pain points. In 2026, enabling the parallel frontend (`-Zthreads=8`), `-Zshare-generics=y`, `-Cdebuginfo=line-tables-only`, and fast linkers (`ld_prime` on macOS, `mold` or incremental [`wild`](https://github.com/davidlattimore/wild) on Linux) cuts workspace incremental rebuilds by 30–45%.
- **Cranelift (`rustc_codegen_cranelift`):** Per the [February 2026 Rust Project Goal](https://goals.rust-lang.org/2026/improve-cg_clif-performance.html), on a 16-core machine building Zed incrementally, Cranelift is currently **12% faster than LLVM** with `-Cdebug-info=line-tables-only` (and 10–15% faster across the `rustc` benchmark suite), with an active 2026 roadmap for an in-memory machine-code caching daemon targeting a 2× backend speedup.
- **Subsecond (`subsecond` 0.7) Binary Hot-Patching:** Built by Dioxus ([`docs.rs/subsecond/0.7.10`](https://docs.rs/subsecond/0.7.10/subsecond/)), `subsecond` introduces **ThinLinking** (automatic dynamic linking of workspace dependencies + object-file diffing + runtime jump tables). When a developer or agent edits a UI view function, only the modified functions are recompiled into a tiny patch object and redirected via jump tables without restarting the process or losing app state, shrinking Rust incremental UI iteration to **< 500 ms** (typically 150–350 ms for leaf view edits).
- **Architecture Discipline for Compile Times:** GPUI’s slow compile times in Zed come primarily from monomorphizing massive view trees (`Div::child(impl IntoElement)`) and putting 100k+ LOC inside single monolithic crates. Keeping Rune’s element tree type-erased at container boundaries (`SmallVec<[AnyElement; 4]>`) and splitting widget crates cleanly keeps standard incremental `cargo build` under 1.2 s even without hot-patching.
2. **Zig (0.15 / 0.16-dev in 2026):**
- Ghostty proved Zig + Metal + AppKit/SwiftUI (`libghostty`) can ship a wonderful macOS/Linux terminal.
- **Why Zig loses for Rune:** First, Zig’s flagship incremental compilation (`-fincremental` + in-place binary patching) works on `x86_64-linux` (`Elf2`), but on `aarch64-macos` (our primary target) the self-hosted `aarch64` backend and Mach-O incremental in-place linker remain incomplete in 2026 ([ziglang/zig#21165](https://github.com/ziglang/zig/issues/21165)). Second, Zig would force Rune to abandon the entire pure-Rust Linebender/AccessKit stack (`taffy`, `parley`, `harfrust`, `fontations`, `accesskit`) and revert to C FFI over `HarfBuzz`/`FreeType` plus writing a cross-platform accessibility tree from scratch. Third, LLMs routinely hallucinate Zig `build.zig` and `std.Io` APIs due to breaking changes between 0.13, 0.14, 0.15, and 0.16.
3. **Swift (Swift 6.3 / 6.4 in 2026):**
- Swift has made real cross-platform strides: [Swift 6.3](https://www.swift.org/blog/swift-6.3-released/) shipped an official Android SDK, [Swift 6.4](https://www.swift.org/blog/) defaulted to the unified `Swift Build` engine, and `JavaScriptKit` optimized Wasm bridges. Kit’s own `hot-reload-kit` demonstrates 100–300 ms hot-reloading on macOS via `@_dynamicReplacement` and `-bundle_loader`.
- **Why Swift loses as core language (but wins as Apple host glue):** Outside Apple platforms, Swift has no cross-platform GUI/text/accessibility ecosystem; Wasm binaries carry heavy runtime weight unless restricted to Embedded Swift; and pervasive ARC reference counting across dense retained/immediate UI trees introduces atomic retain/release traffic and accidental closure reference cycles. However, using ~500 lines of Swift/Objective-C via `objc2` for macOS/iOS system integration (e.g., `NSGlassEffectView`, menu bars, `RPSystemBroadcastPickerView`, share sheets, as done in `launcher/native/LauncherView.swift`) is effortless and strongly recommended.
4. **C++23/26, Odin, Jai, Mojo:**
- **C++** lacks memory safety, suffers from header/build fragmentation, and makes fearless multi-threaded UI state scheduling hazardous.
- **Odin** and **Jai** compile fast and excel at standalone games, but have near-zero accessibility, international text shaping, or mobile/web platform infrastructure, and tiny LLM training corpora.
- **Mojo** is specialized for heterogeneous AI/tensor compute and has no desktop/mobile windowing or UI ecosystem.
---
### Topic 2: GPU API & Compositor Integration
#### The Contenders Analyzed
1. **Raw Metal (`objc2-metal`) on macOS & iOS:**
- **Evidence from GPUI, Scrawl, and Makepad:**
- GPUI’s original macOS renderer (`kitlangton/gpui/src/platform/mac/metal_renderer.rs:1-850`) is **850 lines of Rust**.
- Kit’s production recording pill renderer in Scrawl (`scrawl/src/native/pill/mod.rs:1-420` + `pill.metal:1-369`) is **~790 lines total**, directly driving a 3-pass separable Gaussian blur + SDF capsule pipeline on a `CAMetalLayer` over an `NSGlassEffectView`.
- Makepad’s direct Metal backend (`makepad/platform/src/os/apple/metal.rs:1-1100`) gives direct `IOSurface` cross-process texture sharing and exact `MTLCommandBuffer` GPU start/end timestamps (`GPUStartTime`/`GPUEndTime`, lines 318–326).
- **Capabilities `wgpu` hides or complicates on Apple:**
- **Programmable Framebuffer Fetch / Tile Memory (`[[color(0)]]`, `[[imageblock_data]]`, `[[raster_order_group(0)]]`)**: Apple Silicon is a Tile-Based Deferred Renderer (TBDR). Rive’s Metal shaders (`rive-runtime/renderer/src/shaders/metal.glsl:301-450`) read and write 4 pixel-local planes (`colorBuffer`, `clipBuffer`, `scratchColorBuffer`, `coverageCountBuffer`) directly in on-chip tile SRAM (`[[color(IDX)]]`) at zero system memory bandwidth cost. `wgpu` does not expose multi-plane tile memory / programmable blending on Metal.
- **Zero-Copy Video & Camera (`CVMetalTextureCache` / `IOSurface`)**: GPUI’s `surface_fragment` (`shaders.metal:874-890`) samples bi-planar `Y` (`R8Unorm`) and `CbCr` (`RG8Unorm`) `IOSurface` planes directly from `CVPixelBuffer` hardware decoders without CPU/GPU copies.
- **Live Resize Synchronization (`presentsWithTransaction`)**: Both GPUI (`zed/crates/gpui_macos/src/window.rs:3202,3328`) and Scrawl (`scrawl/src/native/pill/mod.rs:403-417`) toggle `layer.setPresentsWithTransaction(true)` inside `CATransaction` during window resize/frame changes so Metal content never lags behind the window border.
- **Precompiled `.metallib` Instant Startup**: `xcrun metal` compiles `.metal` at `build.rs` time into a binary `.metallib`. `newLibraryWithData` loads in **< 0.5 ms** at startup, versus 15–60 ms for runtime WGSL→Naga→MSL string translation + `newLibraryWithSource`.
2. **`wgpu` (v28+ in 2026) vs `blade-graphics`:**
- Historically, `wgpu` had heavy state-tracking and validation overhead, prompting Zed to adopt Kvark’s lighter `blade-graphics` for Linux/Windows.
- **Crucial 2026 Update:** In February 2026, Zed merged [PR #46758 ("Migrate from blade-graphics to wgpu")](https://github.com/zed-industries/zed/pull/46758) (`zed/crates/gpui_wgpu/src/wgpu_renderer.rs`). Benchmarks in that PR showed **`wgpu` reduced median CPU draw time from 301.29 µs to 235.67 µs (-21.8%)** compared to `blade-graphics`, while adding `wgpu::Features::DUAL_SOURCE_BLENDING` for subpixel text AA (`wgpu_renderer.rs:781-795`), pipeline disk caching (`PipelineCache`), Vulkan/Wayland stability fixes, and a WebGPU/WebGL2 target.
- **Tradeoffs:** `wgpu` + `naga` adds ~2.5–3.8 MB to stripped binary size and translates WGSL to backend shaders. That is an unacceptable tax on Apple-specific capabilities if used as the *only* backend on macOS/iOS, but an **overwhelming win** for Linux (Vulkan), Windows (D3D12/Vulkan), Android, and Web (WebGPU).
3. **SDL3 `SDL_gpu`, Google `Dawn`, and Flutter `Impeller`:**
- **`SDL_gpu` (shipped in SDL 3.2+):** Clean C API, ~400 KB binary footprint, good for games, but lacks `wgpu`’s Rust safety, storage buffer ergonomics, dual-source blending portable setup, and WebGPU browser integration.
- **Dawn:** Powers Chromium’s WebGPU; C++ build (CMake/GN + `tint` + `spirv-tools`) adds 8–15 MB to binaries and heavy C++ build times.
- **Flutter Impeller:** Proves the value of **100% AOT-compiled shaders** (`impellerc`) to eliminate runtime PSO compilation hitching—a lesson Rune must steal via build-time `.metallib` / SPIR-V / DXIL / WGSL validation.
4. **Hybrid Core Animation (`CALayer` Tree + Custom Metal) vs Pure Single-Drawable:**
- **How macOS/iOS actually works:** The WindowServer compositor is already a hardware-accelerated `CALayer` tree evaluator with direct display-controller scanout planes.
- **What `CALayer` does better than custom shaders:**
- **System Materials & Liquid Glass (`NSGlassEffectView` / `NSVisualEffectView`):** Private WindowServer backdrop filters blur and refract windows *behind* the app at zero app-GPU cost. Both Zed (`gpui_macos/src/window.rs:301,3810`) and Scrawl (`scrawl/src/native/pill/mod.rs:348-380`) place an `NSVisualEffectView` / `NSGlassEffectView` behind a transparent `CAMetalLayer`.
- **Out-of-process HDR Video & WebViews (`AVSampleBufferDisplayLayer`, `WKWebView`):** Composited directly by WindowServer hardware planes without waking the UI render pass.
- **What `CALayer` does poorly (Avoid 1-Layer-Per-Widget):** Allocating hundreds of `CALayer`s for normal buttons/rows causes Core Animation IPC serialization overhead, layout-to-GPU desynchronization, and breaks cross-platform behavior.
- **The Sweet Spot ("Shallow Compositor Host"):** 1 root `NSGlassEffectView`/`NSVisualEffectView` + 1 primary `CAMetalLayer` for all 2D UI + optional sibling native `CALayer`s only for hardware video/camera/WebView cutouts.
---
### Topic 3: 2D UI Renderer Design
#### 3.1 Instanced SDF Primitives & Analytic Surface Shading
- **GPUI’s Baseline (`kitlangton/gpui/src/platform/mac/shaders.metal:102-545`):**
- Draws `Shadow`, `Quad`, and `Underline` as instanced 4-vertex unit quads reading per-instance structs from storage/constant buffers (`[[buffer(QuadInputIndex_Quads)]]`).
- `quad_fragment` evaluates an exact outer rounded-box SDF (`quad_sdf_impl`, line 1065) and an inner border SDF (`quarter_ellipse_sdf`, line 440) that handles non-uniform border widths (`top != left`), plus perimeter-parameterized dashed borders (`dash_alpha`, line 421).
- **Limitation in GPUI:** Because `Shadow`, `Quad`, and `Border` are separate primitive batches in `scene.rs` (`zed/crates/gpui/src/scene.rs:88-115`), a button with a drop shadow, background fill, inner highlight, and border emits multiple draw instances or requires batch-breaking z-order sorts.
- **Makepad’s Analytic `Material` Breakthrough (`makepad/draw/src/shader/surface.rs:27-165`):**
- Evaluates **bevel profile & normal (`m_normal`)**, **wrapped Lambert diffuse + Blinn-Phong specular (`m_lit`)**, **edge ambient occlusion (`m_ao`)**, **rim lighting (`m_rim`)**, **sky-box gloss (`m_gloss`)**, and **4-sample `erf` Gaussian inner/outer shadow (`box_cov`)** purely as a function of the signed distance `d` inside a *single* fragment pass!
- **Analytic Drop & Inner Shadows:**
- Both GPUI (`shaders.metal:525-542,1087-1104`) and Makepad (`sdf.rs:10-76`) use Evan Wallace’s separable formulation: exact closed-form 1D Gaussian integral along X via a polynomial `erf()` approximation (`blur_along_x`), integrated across Y with a 4-step midpoint quadrature clamped to `[-3σ, +3σ]`.
- **Crucial detail to steal from GPUI (`shaders.metal:541,1170-1177`):** 8-bit `BGRA8Unorm` framebuffers visibly band in the `[0.0, 0.02]` alpha tail of soft shadows and Oklab gradients. GPUI adds **Jimenez Interleaved Gradient Noise (IGN) with a 2-tap triangular PDF (`±1/255` amplitude)** modulated by `smoothstep(0.0, 0.02, alpha) * smoothstep(1.0, 0.98, alpha)`, completely eliminating shadow and gradient mach banding at 3 ALU instructions per pixel.
- **Rune’s Uber-Primitive Upgrade:**
- Combine Rounded/Squircle (G2 continuous $L^p$ superellipse option) Box + Border + Inner Shadow/Bevel/Rim + Outer Shadow into a single 128-byte `UberQuad` instance struct so an entire styled card renders in **1 instance** with **1 SDF evaluation**.
#### 3.2 Vector Paths & Curves: The 2026 Showdown
| Technique | Representative Engine | How It Works | CPU Cost | GPU Cost & Memory | Verdict for Rune |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **CPU Triangle Tessellation** | `lyon`, Iced fallback, GPUI legacy | Ear-clipping / sweep-line on CPU → indexed triangles | **High** (0.5–4 ms for complex paths; poor for animated morphs) | Low fragment, high vertex count, requires 4× MSAA | **Avoid** (CPU bottleneck on dynamic vector UI) |
| **Loop-Blinn + 4× MSAA Intermediate** | GPUI (`shaders.metal:737-838`) | CPU triangulates hull; fragment shader solves $u^2 - v$ into full-viewport 4× MSAA texture, then blits | Medium (CPU earcut hull) | **High** (allocates full-window 4× MSAA texture + resolve + blit pass) | **Avoid** (Massive memory & bandwidth waste for small icons) |
| **Full Compute Pipeline** | `vello` (classic compute) | 9+ compute stages (pathtag, bbox, flatten, bin, tile, backdrop, coarse, fine) | Very Low | **High baseline** (~0.4–0.8 ms dispatch overhead even for 1 path; complex shaders) | **Avoid** (Linebender moved it to `research/` in 2026) |
| **Sparse Strips (Hybrid CPU+GPU)** | `vello_gpu` / `vello_hybrid` (`vello/ARCHITECTURE.md`) | SIMD CPU flattening + tiling into 4×4 pixel alpha strips; simple instanced GPU raster pass | Low (~50–200 µs via NEON/AVX) | **Very Low** (Simple vertex/fragment shader, zero compute dispatch overhead) | **Steal for general vector art / charts / complex SVGs** |
| **Direct GPU Quadratic Bézier Winding** | **Slug** ([EricLengyel/Slug](https://github.com/EricLengyel/Slug), `makepad/.../draw_text.rs:42-350`) | Curves stored once in `curve_texture` + horizontal/vertical `band_texture`; fragment shader raycasts exact roots | **Zero per frame** (static em-space upload once per glyph/icon) | **Low** (Exact analytical AA at any scale/rotation/perspective; zero atlas invalidation) | **Steal for large/transformed text & vector icons!** |
| **PLS / Atomic Analytical Coverage** | Rive (`draw_raster_order_path.frag`) | Cubic tessellation in vertex shader + exact winding accumulation in tile memory (`[[color(n)]]`) | Low | Ultra-fast for 10,000-path animations; requires tile-memory/ROV shader variants | Optional plugin for embedded `.riv` files |
- **Why the March 2026 Slug Public-Domain Dedication Changes Everything:**
- On March 17, 2026, Eric Lengyel dedicated US Patent `#10,373,352` (Slug GPU Bézier rendering) to the public domain ([`github.com/EricLengyel/Slug`](https://github.com/EricLengyel/Slug)).
- Makepad immediately integrated Slug in `makepad/draw/src/text/slug_atlas.rs:1-200` and `draw_text.rs:41-350`.
- In Slug, a glyph or SVG icon’s quadratic Bézier curves (cubics split once via `CUBIC_TO_QUAD_TOLERANCE = 0.05`) are uploaded **once** in em-space into an append-only `RGBA32F`/`RGBA16F` `curve_texture` and indexed into horizontal and vertical spatial bands (`band_texture`). The vertex shader dilates the bounding quad by 0.5 px in screen space (`slug_dilate`), and the fragment shader scans only the curves intersecting the pixel’s horizontal/vertical band (`scan_horizontal_list`, `scan_vertical_list`), using Lengyel’s bit-shift root eligibility code `(u32(11892) >> shift) & u32(257)` (`draw_text.rs:237`) to avoid numerical edge dropouts.
- **Result:** Infinite zoom, rotation, 3D perspective, and scale animations on text and UI icons with **zero CPU re-rasterization and zero glyph-atlas thrashing**.
#### 3.3 Text Rendering: Hybrid Raster Atlas + Slug
- **Why not Slug for *all* text?** At body sizes (`11–18 px` on 2× Retina = `22–36` device px), an `R8Unorm` texture sample costs 1 texture fetch (~2 GPU cycles) and preserves platform-specific stem darkening / optical hinting (`CoreText` on macOS, `DirectWrite` on Windows, `fontations`+`swash` autohinting on Linux). Slug requires 4–10 texel fetches + quadratic root math per pixel.
- **Subpixel vs Grayscale AA on Retina (2026):**
- On macOS, Apple removed subpixel LCD layout from CoreGraphics in Mojave, and all modern Macs/iPhones ship ≥2× Retina panels (many OLED or mini-LED with non-RGB-stripe subpixel layouts on iPad Pro M4 / iPhone). However, CoreText still applies **font smoothing / stem darkening** (`CGContextSetAllowsFontSmoothing`).
- As proven in `scrawl/src/native/pill/atlas.rs:133-201`, rasterizing glyphs with CoreText into an `R8Unorm` shelf-packed atlas (with 2×2 subpixel bin positioning for fractional X offsets) uses 4× less VRAM than `RGBA8` and blends in a single pass.
- For Windows/Linux 1× external monitors, `wgpu::Features::DUAL_SOURCE_BLENDING` (as implemented in `zed/crates/gpui_wgpu/src/wgpu_renderer.rs:781-795`) enables proper per-channel RGB subpixel alpha blending in a single draw call.
- **Rune’s Hybrid Text Rule:**
- **Axis-aligned text `≤ 32 pt` with static scale:** Shelf-packed `R8Unorm` (macOS/iOS Retina) or `RGBA8` dual-source subpixel (1× Windows/Linux) glyph atlas, keyed by `(FontId, GlyphId, FontSizeFixed, SubpixelBinX)`.
- **Text `> 32 pt`, any rotated/skewed/3D-transformed text, or text undergoing continuous zoom/scale animation:** Rendered directly via **Slug** (`SlugAtlas`), eliminating the infamous "blurry scaled atlas" or "100 MB atlas eviction storm during pinch-to-zoom".
#### 3.4 Blur, Backdrop Filters & Peak-Alpha Legibility
- **Window-Level Backdrop Blur (Zero App GPU Cost):** Delegated to `NSGlassEffectView` (macOS 26+) / `NSVisualEffectView` (macOS 14–15) / `UIVisualEffectView` (iOS) / `DwmEnableBlurBehindWindow` / `Mica` (Windows).
- **In-App Element Backdrop Blur (`backdrop-filter: blur()`):**
- **Dual Kawase Pyramid** for large radii (`σ > 6 px`): Downsample 2× per pass (4-tap bilinear offset `(±1, ±1)`) for $N$ levels (typically 2–3 levels down to 1/4 or 1/8 resolution), then upsample 2× per pass (8-tap tent filter) restricted strictly to the dirty/clipped bounding rect of the blurring element. At 1/4 resolution, blurring a 400×300 popover takes **< 60 µs** on Apple M-series GPUs.
- **Separable 1D Gaussian + Peak-Alpha Boost** for animated morphs & small blurs (`σ ≤ 6 px`): Steal directly from Kit’s `scrawl/src/native/pill/pill.metal:208-360`. When blurring UI elements (like morphing pill labels or crossfading icons), standard Gaussian blur reduces peak alpha and makes text look washed out. Scrawl’s `composite_fragment` (`pill.metal:326-349`) computes `boost = 1.0 + smoothstep(0.0, 0.35, b) * 2.5` and `pow(a, 1.0 / boost)`, keeping blurred text crisp and luminous throughout the transition.
#### 3.5 Cheap Soft-Edge Gradient Masks at Every Clip Edge
- **The Problem:** Traditional UI engines clip scroll views and containers using either hardware `glScissor`/`setScissorRect` (hard pixel edge, axis-aligned only), hardware `[[clip_distance]]` planes (GPUI `shaders.metal:56,80`, hard edge), or an offscreen mask texture (expensive render pass switch). When content scrolls under a header or a pill morphs width, hard clips look abrupt; developers want a 6–16 px soft alpha fade at the top/bottom/left/right clip edge without allocating an offscreen layer.
- **The Zero-Pass Solution (Analytic Soft-Clip Mask + Room Gating):**
1. **Per-Fragment Analytic Rounded-Clip & 4-Edge Feather:** Every draw instance carries a `clip_index: u32` indexing into a compact `ClipStackBuffer` on the GPU. Each `ClipNode` (32 bytes) stores:
- `bounds: float4` (`origin.xy, size.zw`)
- `corner_radii: float4` (`tl, tr, br, bl`)
- `edge_feather: half4` (`top, right, bottom, left` feather distances in scaled pixels; `0.0` = crisp 1px antialiased SDF clip; `> 0.0` = smooth gradient mask fade over `edge_feather` px!).
In the fragment shader, evaluating the clip costs ~8 ALU instructions:
```metal
// Signed distance to the rounded clip rect (negative inside, positive outside)
float clip_sdf = quad_sdf(frag_pos, clip.bounds, clip.corner_radii);
float hard_aa = saturate(0.5 - clip_sdf);
// Directional 4-edge soft gradient fade inside the clip rect
float4 dist_to_edges = float4(
frag_pos.y - clip.bounds.origin.y, // top
(clip.bounds.origin.x + clip.bounds.size.x) - frag_pos.x, // right
(clip.bounds.origin.y + clip.bounds.size.y) - frag_pos.y, // bottom
frag_pos.x - clip.bounds.origin.x // left
);
float4 edge_alpha = saturate(dist_to_edges / max(float4(clip.edge_feather), float4(1e-4)));
// Hermite smoothstep across each feathered edge
edge_alpha = edge_alpha * edge_alpha * (3.0 - 2.0 * edge_alpha);
float clip_mask = hard_aa * edge_alpha.x * edge_alpha.y * edge_alpha.z * edge_alpha.w;
color *= clip_mask; // Premultiplied alpha modulation
```
2. **Per-Element SDF Room Gating (Steal from `scrawl/src/native/pill/model.rs:146-184`):** When an item sits inside a morphing container (e.g., a pill or collapsing sidebar), evaluating `box_clearance` (the container’s analytic SDF clearance around the child’s bounding box) on the CPU or vertex shader produces a continuous `presence = smoothstep((room + feather) / feather)` multiplier that drives both opacity and subtle scale/blur before the child ever touches the border.
3. **Result:** Every scroll view, overflow container, rounded card, and morphing pill gets arbitrary rounded-corner clipping **and** independent top/right/bottom/left soft gradient fade masks with **zero offscreen textures, zero stencil buffers, and zero render-pass breaks**.
#### 3.6 Layers, Offscreen Caching & Group Opacity
- **When Offscreen Passes Are Needed:** Only for (a) true group opacity (`0.0 < opacity < 1.0` on a container with *overlapping* children, where per-element alpha would show internal seams), (b) container-wide `backdrop-filter` / `filter: blur()`, or (c) explicitly cached complex subtrees (`will_change` / `cache_layer`).
- **Tile-Local Group Opacity Shortcut on Apple Silicon:** When a group with `opacity < 1.0` fits within a single pass and does not require blur, Metal programmable blending (`[[color(0)]]` scratch plane in tile memory, like Rive’s `scratchColorBuffer` in `draw_raster_order_path.frag:10`) can composite the group in on-chip tile memory and blend it onto the main color plane without ever allocating or bandwidth-flushing an offscreen texture!
- **Transient Texture Pool:** For effects that do cross pixel neighborhoods (blur), maintain a power-of-two / bucketed `MTLTexture` / `wgpu::Texture` pool with frame-age eviction (evict after 120 idle frames).
#### 3.7 Damage Tracking, Partial Present & 120 Hz Power Cost
- **The 120 Hz Power Reality:**
- Running a full-window 4K/5K Metal render pass at 120 Hz consumes 4–9 W of package power even if only a 2×18 px text cursor is blinking.
- At complete rest (zero dirty views, zero active springs), Rune **must draw 0 frames/sec** (0% CPU, 0% GPU).
- **Partial Present & Damage Tracking on Metal vs D3D12/Vulkan:**
- Metal’s `CAMetalLayer` does **not** expose an equivalent to `EGL_KHR_swap_buffers_with_damage` or `IDXGISwapChain1::Present1(DirtyRects)`—when you present a `CAMetalDrawable`, WindowServer treats the drawable as a full surface, and because `nextDrawable` cycles through a ring of 2–3 buffers (`maximumDrawableCount`), rendering only a dirty scissor rect directly into `nextDrawable()` leaves stale content from 2–3 frames ago outside the scissor rect!
- **How to Make Damage Tracking Actually Work on Metal:**
1. **Persistent Backing Texture + Scissored Dirty Render:** Render the UI scene into a single persistent `MTLTexture` (`StorageModePrivate`, `BGRA8Unorm` / `RGBA16Float`) using `MTLLoadActionLoad` and `setScissorRect(dirty_bbox)` so Apple Silicon’s TBDR GPU only shades tiles overlapping `dirty_bbox`. Then encode a single hardware blit (`MTLBlitCommandEncoder::copyFromTexture`) or scissored copy into the `CAMetalDrawable`. On Apple Silicon unified memory, a tile-aligned blit of a 5K buffer takes ~80 µs while saving 95%+ of fragment shader execution on partial updates (like typing or cursor blink).
2. **ProMotion Dynamic Frame Rate Scaling (`preferredFrameRateRange`):** Use `CADisplayLink`’s `CAFrameRateRangeMake(min, max, preferred)` ([Apple ProMotion Docs](https://developer.apple.com/documentation/quartzcore/optimizing-iphone-and-ipad-apps-to-support-promotion-displays)):
- Interactive scroll, drag, or fast spring velocity: `CAFrameRateRangeMake(80, 120, 120)` (8.33 ms).
- Settling spring tail (`velocity < threshold`) or subtle spinner/pulse: `CAFrameRateRangeMake(30, 60, 60)` or `24–48 Hz`.
- Cursor blink / static timer: **Display link paused**, scheduled via timer only on blink transitions.
#### 3.8 Wide Color (Display P3), EDR/HDR, Linear Blending & Dithering
- **Color Pipeline:**
- Authoring colors in sRGB, Display P3, or **Oklab / Oklch** (perceptually uniform lightness/chroma).
- Gradients interpolate in **Oklab** (like GPUI `shaders.metal:950-988,1225`) or linear Display P3, with Jimenez IGN triangular dithering (`±1/255`).
- **Surface Format:** Default `MTLPixelFormatBGRA8Unorm` with `CGColorSpaceCreateWithName(kCGColorSpaceDisplayP3)` on wide-gamut displays (50% less memory bandwidth than `RGBA16Float`), upgrading dynamically to `MTLPixelFormatRGBA16Float` with `wantsExtendedDynamicRangeContent = YES` only when an HDR/EDR surface or specular HDR highlight (> 1.0 headroom) is mounted in the scene.
---
### Topic 4: Input-to-Photon Latency Architecture
#### 4.1 Real-World Latency Measurements (macOS & iOS, 2025–2026)
| System / Benchmark | Display Rate | Measured Input-to-Photon (p50 / p99) | Architectural Cause |
| :--- | :--- | :--- | :--- |
| **Hardware + OS Compositor Floor** (Windowed macOS ProMotion) | 120 Hz (8.33 ms) | **~4.2–8.5 ms** | USB/SPI keyboard scan (~1 ms) + AppKit event delivery (~0.5 ms) + GPU render (<0.5 ms) + WindowServer next scanout (0–8.33 ms) |
| **Blackbird Terminal** ([`vtebench-2026-04-20.md`](https://github.com/conjfrnk/blackbird/blob/main/docs/benchmarks/vtebench-2026-04-20.md)) | 120 Hz ProMotion | **p50 ≤ 6 ms, p99 ≤ 20 ms** (CI-gated) | Direct event-triggered render without waiting for display-link lead |
| **Alacritty 0.17** ([`komsit37/ghostty-input-latency`](https://github.com/komsit37/ghostty-input-latency), Jul 2026) | 60 Hz (16.67 ms) | **p50 17.9 ms** (~4 ms above 14 ms capture floor) | Immediate redraw on PTY/key event; `maximumDrawableCount = 2` |
| **Ghostty 1.3.2** ([`komsit37/ghostty-input-latency`](https://github.com/komsit37/ghostty-input-latency), Jul 2026) | 60 Hz (16.67 ms) | **p50 58.6 ms** (~40 ms slower than Alacritty) | Queued frame scheduling / multi-refresh display-link pipeline lead |
| **`CAMetalDisplayLink` Windowed** ([`rrva/metal-display-link-pacing`](https://github.com/rrva/metal-display-link-pacing), 2026) | 60 Hz / 120 Hz | **66.5 ms (60 Hz) / 41.5 ms (120 Hz)** callback → screen | Windowed `CAMetalDisplayLink` targets **3 refreshes (49.8 ms at 60 Hz)** or **5 refreshes (41.5 ms at 120 Hz)** ahead of its callback! |
| **Zed (`gpui_macos`)** | 120 Hz ProMotion | **~12–20 ms** | `CVDisplayLink` io-thread → GCD `DispatchSource` → main thread `step()` (`display_link.rs:122-160`), adds 1 refresh vs direct input draw |
#### 4.2 Why `CAMetalDisplayLink` and `CVDisplayLink` Add Latency if Misused
1. **The `CAMetalDisplayLink` Trap:** Apple introduced `CAMetalDisplayLink` in macOS 14 / iOS 17 with `preferredFrameLatency` (accepting only `1.0` or `2.0`). However, Apple’s documentation notes: *"The final latency may be bigger if the system needs more time, such as for windowed modes on macOS."* Independent 2026 empirical measurements ([`rrva/metal-display-link-pacing`](https://github.com/rrva/metal-display-link-pacing)) prove that in **windowed mode on macOS**, `CAMetalDisplayLink` schedules its callback **5 refreshes (41.5 ms) ahead of scanout on 120 Hz panels** and **3 refreshes (49.8 ms) ahead on 60 Hz panels**. That guarantees smooth 120 fps throughput for heavy 3D games, but adds **33–50 ms of input lag** to a UI framework if input waits for `CAMetalDisplayLinkUpdate`!
2. **The `CVDisplayLink` Trap:** As documented in Zed’s `zed/crates/gpui_macos/src/display_link.rs:1-52`, `CVDisplayLink` runs on a separate high-priority CoreVideo I/O thread, has broken teardown semantics (`CVDisplayLinkStop` races with in-flight callbacks, causing segfaults in `CVHWTime::reset`), lacks `preferredFrameRateRange` for ProMotion power saving, and requires cross-thread signaling (`dispatch_source_merge_data`) to wake the main runloop.
#### 4.3 Rune’s Zero-Wait Input-to-Photon Pipeline (< 6 ms p50 on 120 Hz)
To achieve sub-frame (~4–6 ms p50) input-to-photon latency while maintaining butter-smooth 120 Hz animations:
1. **Two Distinct Frame Triggers (Input-Immediate vs DisplayLink-Paced):**
- **Path A — Discrete Input Fast-Path (KeyDown, MouseDown, Trackpad Scroll phase, Direct Manipulation):** When `NSEvent` / `UIEvent` arrives on the main runloop and no frame has been presented in the current VSync interval (`now - last_present_time > 0.75 * refresh_period`), **do not wait for the next `CADisplayLink` tick**. Coalesce any pending events currently in the runloop queue, run incremental layout/paint (< 0.4 ms), acquire `layer.nextDrawable()`, encode and `commit()` immediately. Because a UI render pass takes ~0.2–0.4 ms on Apple Silicon, the drawable finishes rendering well before the compositor’s next VSync deadline and scans out on the **immediately upcoming refresh** (0–8.33 ms away, **p50 ~4.8 ms**).
- **Path B — Continuous Animation Pacing (`CADisplayLink` on Main `NSRunLoop`):** When springs, physics scroll momentum, or shaders are actively animating, `CADisplayLink` (macOS 14+ / iOS) drives frame ticks on `NSRunLoopCommonModes` using `targetTimestamp` to step analytical springs (`model.rs` exact closed-form `spring(duration, bounce)`) to the exact display presentation time, eliminating dt-jitter.
2. **Double Buffering (`maximumDrawableCount = 2`) with Completion Pacing:**
- Triple buffering (`maximumDrawableCount = 3`) allows the CPU to run 2 full frames ahead of the display, adding 8.3–16.6 ms of latency during continuous trackpad dragging.
- Set `CAMetalLayer.maximumDrawableCount = 2` (or bound in-flight frames to 1 via an `MTLSharedEvent` / `dispatch_semaphore_t` signaled in `commandBuffer.addCompletedHandler`), ensuring `nextDrawable()` never queues stale frames.
3. **Live Window Resize Without Jitter (`presentsWithTransaction`):**
- Keep `presentsWithTransaction = false` during normal operation (so asynchronous commits never block the main thread).
- Inside `setFrameSize:` / `displayLayer:` (`zed/crates/gpui_macos/src/window.rs:3327-3340`, `scrawl/src/native/pill/mod.rs:403-417`), temporarily set `presentsWithTransaction = true`, call `commandBuffer.commit()`, `commandBuffer.waitUntilScheduled()`, and `drawable.present()`, then restore `presentsWithTransaction = false`.
---
## 3. What to Steal vs. What to Avoid
### What to Steal
1. **Zed (`gpui_macos` & `gpui_wgpu`):**
- **Oklab gradient interpolation + Jimenez IGN 2-tap triangular dithering** (`±1/255`) in `kitlangton/gpui/src/platform/mac/shaders.metal:950-988,1170-1177` to eliminate 8-bit banding in shadows and gradients.
- **Quarter-ellipse inner border SDF** and **perimeter-parameterized dashed borders** (`shaders.metal:194-449`).
- **`wgpu` backend architecture for Linux/Windows/Web** with storage buffers + dual-source subpixel blending (`zed/crates/gpui_wgpu/src/wgpu_renderer.rs:781-795`).
- **Zero-copy bi-planar `Y`/`CbCr` `IOSurface` video rendering** (`surface_fragment` in `shaders.metal:874-890`).
2. **Kit’s Scrawl (`scrawl/src/native/pill/`):**
- **Peak-alpha boost during Gaussian blur** (`boost = 1.0 + smoothstep(0.0, 0.35, b) * 2.5`, `scrawl/src/native/pill/pill.metal:326-349`) so morphing/blurring text stays crisp and legible.
- **Analytic SDF `box_clearance` room gating** (`scrawl/src/native/pill/model.rs:146-184`) to smoothly fade/scale child elements as container bounds morph.
- **Hybrid `NSGlassEffectView` + `CAMetalLayer` host** (`scrawl/src/native/pill/mod.rs:348-380`).
3. **Makepad (`makepad/draw/src/shader/`):**
- **Public-domain Slug GPU Bézier text & icon renderer** (`makepad/draw/src/shader/draw_text.rs:41-350` and `slug_atlas.rs:1-200`).
- **Single-pass analytic SDF `Material` shading** (bevel, wrapped Lambert diffuse, Blinn-Phong specular, rim light, inner shadow coverage, `makepad/draw/src/shader/surface.rs:27-165`).
4. **Linebender (`vello_gpu` / `parley` / `harfrust` / `fontations`):**
- **Sparse Strips (`vello_gpu`)** 4×4 pixel alpha tile strips (`vello/vello_gpu/src/render/wgpu/mod.rs`) for complex multi-contour vector paths and strokes.
5. **Rive (`rive-runtime/renderer/src/shaders/`):**
- **Apple Silicon programmable framebuffer fetch (`[[color(IDX)]]`)** (`rive-runtime/renderer/src/shaders/metal.glsl:396-450`) for zero-bandwidth tile-local group opacity and blending.
6. **Dioxus (`subsecond`):**
- **ThinLink + jump-table hot-patching** ([`docs.rs/subsecond`](https://docs.rs/subsecond/0.7.10/subsecond/)) for <400 ms stateful Rust UI hot-reloading.
### What to Avoid
1. **Avoid GPUI’s 4× MSAA Full-Window Intermediate Texture for Paths** (`kitlangton/gpui/src/platform/mac/metal_renderer.rs:195-235`): Allocating a full-window 4× MSAA texture and running a separate resolve + sprite-blit pass just to draw a few SVG icons wastes tens of megabytes of VRAM and breaks batching. Use **Slug** for icons/curves and **`vello_gpu` Sparse Strips** for complex vector art.
2. **Avoid `CVDisplayLink` on macOS 14+** (`zed/crates/gpui_macos/src/display_link.rs:1-52`): Deprecated, lacks ProMotion `preferredFrameRateRange`, and has unsafe thread teardown races. Use `CADisplayLink` on the main `NSRunLoop` combined with an immediate input-triggered draw fast-path.
3. **Avoid Windowed `CAMetalDisplayLink` for Latency-Critical Input**: Its 3–5 refresh lead (41–50 ms on macOS windowed mode) makes typing and dragging feel sluggish.
4. **Avoid Full Compute `vello`**: Moved to `research/` by Linebender in 2026 because its 9-stage compute pipeline has too high a baseline dispatch cost for low-latency 120 Hz UI frames.
5. **Avoid Maintaining Custom Vulkan & D3D12 Backends (`blade-graphics` / `gpui_windows`)**: Zed’s 2026 migration to `wgpu` proved that `wgpu` is faster on Linux/Windows while saving thousands of lines of driver-workaround code.
---
## 4. Decisive Recommendation & Renderer Architecture Sketch
### Decisive Stack Choice
- **Core Language:** **Rust (2024 Edition)** with thin `objc2` / Swift 6 host shims on Apple platforms and `subsecond` jump-table hot-patching in dev builds.
- **GPU Layer (`rune-gpu`):** A ~400-line internal trait (`GpuDevice`, `RenderPass`, `BufferSlice`, `TextureHandle`) with **two backends**:
1. **`rune-metal` (macOS & iOS):** Direct `objc2-metal` (~1,600 LOC) with build-time `.metallib`, `IOSurface` zero-copy textures, programmable framebuffer fetch (`[[color(0..1)]]`), and `CAMetalLayer` + `NSGlassEffectView` host integration.
2. **`rune-wgpu` (Linux, Windows, Android, WebGPU):** `wgpu` 28+ (~1,200 LOC) sharing the exact same scene buffer layout.
### Threading & Latency Architecture
```
┌─────────────────────────────────────────────────────────────────────────┐
│ MAIN / UI THREAD (NSRunLoop / UIEventLoop) │
│ 1. Input Fast-Path (NSEvent/UIEvent) OR CADisplayLink(targetTimestamp) │
│ 2. Step analytical springs (exact closed-form at targetTimestamp) │
│ 3. Reactive view diff -> Taffy incremental layout -> SceneBuilder │
│ 4. Pack flat GPU instance buffers (UberQuad, GlyphRun, Slug, Strip) │
└───────────────────────────────┬─────────────────────────────────────────┘
│ Lock-free triple-buffered SceneArena
▼
┌─────────────────────────────────────────────────────────────────────────┐
│ GPU SUBMISSION (Inline on Main Thread <250 µs, or Dedicated Render Q) │
│ • Acquire persistent backing texture + dirty scissor bbox │
│ • Upload dirty glyph/Slug/strip pages via UMA mapped ring buffer │
│ • Encode RenderPass -> Blit to CAMetalDrawable -> commit() │
└─────────────────────────────────────────────────────────────────────────┘
▲
┌───────────────────────────────┴─────────────────────────────────────────┐
│ BACKGROUND WORKER POOL (Rayon / Async Executor) │
│ • Async image decoding -> staging ring buffer │
│ • Large text paragraph shaping (Parley + HarfRust) │
│ • Heavy SVG / chart flattening into vello_gpu Sparse Strips │
└─────────────────────────────────────────────────────────────────────────┘
```
### Frame Graph (Typical Frame = 1 Render Pass + 1 Scissored Blit)
```
[Pass 0: Atlas Upload (Blit Encoder, only when new glyphs/icons/strips added)]
└── Append dirty R8/RGBA8 glyph tiles, Slug curve/band texels, or Sparse Strip alphas
[Pass 1: Backdrop Blur Pyramid (Only if scene contains active in-app BackdropBlur)]
└── Scissored Dual-Kawase 2x downsample (2 levels) -> 2x tent upsample
[Pass 2: Main UI Uber-Pass (Single RenderCommandEncoder, Scissored to Dirty Union)]
├── DrawBatch::UberQuad (Rounded/Squircle box, border, outer/inner erf shadow,
│ analytic surface material, Oklab gradient + IGN dither)
├── DrawBatch::AtlasSprite (Hinted body text R8/dual-source RGB + raster images)
├── DrawBatch::SlugVector (Large/rotated/zooming text + crisp SVG icons via Slug)
├── DrawBatch::SparseStrips (Complex multi-color vector paths via vello_gpu 4x4 strips)
└── DrawBatch::NativeSurface(Zero-copy YCbCr / RGBA IOSurface video & camera frames)
* Every primitive evaluates `ClipStackBuffer[instance.clip_id]` in-shader for
rounded-rect clipping + 4-edge analytic soft-gradient masks (zero mask passes!).
* On Apple Silicon, non-blurred group opacity uses tile-local `[[color(1)]]` scratch
plane without breaking Pass 2!
[Pass 3: Present]
└── Copy/present persistent backing texture to `CAMetalDrawable` (`maximumDrawableCount = 2`)
```
### Core GPU Primitive Set (6 Primitives Total)
| Primitive | Instance Size | Responsibilities |
| :--- | :--- | :--- |
| `ClipNode` (GPU Buffer Table) | 32 B | `bounds`, `corner_radii`, `edge_feather (top, right, bottom, left)`, `parent_clip_id`, `transform_id`. Indexed by all primitives. |
| `UberQuad` | 128 B | Fill (Solid / Linear/Radial/Angular Oklab Gradient / Noise), per-corner radii + squircle exponent, border widths/style/color, analytic 4-sample `erf` outer/inner shadow, optional Makepad-style `Material` (bevel/rim/gloss). |
| `AtlasSprite` | 64 B | Monochrome (`R8Unorm`), Subpixel (`RGBA8` dual-source), or Polychrome (`RGBA8`) atlas tile + tint + rounded corner radii + transformation ref. |
| `SlugInstance` | 64 B | Em-space quad bounds, `curve_offset`, `curve_count`, `band_offset`, `band_count`, fill rule, color/gradient ref. |
| `SparseStripInstance` | 32 B | `vello_gpu` 4×4 pixel strip header (`x, y, width, alpha_offset, paint_id`) for arbitrary stroked/filled vector art. |
| `BackdropEffect` | 64 B | Kawase blur radius, saturation/contrast matrix, peak-alpha legibility boost (`pill.metal`), tint, and rounded-rect mask. |
---
## 5. Open Questions for Prototyping
1. **Uber-Shader Branching vs. Specialized PSOs on Low-End Integrated GPUs:** On Apple M1–M4, evaluating the unified `UberQuad` shader with uniform early-out branches (`if (quad.shadow_sigma == 0 && quad.bevel == 0)`) has near-zero divergence cost within 32-thread SIMD-groups. On older Intel/Qualcomm integrated GPUs via `wgpu`, should `UberQuad` split into `SimpleQuad` (64 B, flat/rounded + border) and `RichQuad` (128 B, shadow + gradient + material) pipelines?
2. **Slug Crossover Threshold on 2× vs 3× Retina:** At what exact pixel size (`24 px` vs `32 px` vs `48 px`) does Slug’s fragment raycasting match CoreText’s stem-darkened optical weight on macOS Retina displays without needing synthetic stem dilation in the Slug vertex shader?
3. **Persistent Texture Blit vs. Direct Drawable Rendering Threshold:** When >60% of the window area is dirty (e.g., full-window scrolling), rendering directly into `CAMetalDrawable` saves the 80 µs blit copy. What dirty-area ratio (e.g., `dirty_area / window_area > 0.35`) is the optimal hysteresis threshold to switch between persistent-texture partial redraw and direct-drawable full redraw?
+440
View File
@@ -0,0 +1,440 @@
# 05 — Text, IME, Accessibility, and Layout
*Research date: 2026-10-21*
## Executive Summary
- **Pure-Rust text shaping and font parsing are production-ready in 2026 (`harfrust` + `skrifa` + `fontique`).** Google Fonts' `harfrust` (`v0.14.0`, Oct 2026) has reached HarfBuzz 14.5.1 parity, uses zero-copy `fontations`/`read-fonts` tables directly (`ShaperData` + `ShaperInstance`), and runs 10–15% faster than `rustybuzz` while supporting variable-font variation coordinates, AAT (`morx`/`kerx`/`trak`), and shape plans. Pair it with `skrifa` (`v0.42.0`) for TrueType/CFF hinting + COLRv1 and `fontique` (`v0.8.0`) for font enumeration and script/locale fallback.
- **Keep OS font metrics on Apple (`CTFont`) while using `harfrust` + `parley` for cross-platform shaping and line breaking.** On macOS and iOS, system UI fonts (`SF Pro`, `SF Compact`, `.AppleSystemUIFont`) rely on optical-size (`opsz`) tracking tables (`trak`) and OS-specific ascent/descent rules. Use `parley` (`v0.12.0`, built on `parley_engine` + `fontique` + `harfrust` + `skrifa` + `icu4x`) for bidirectional paragraph layout, mixed inline runs, and cursor/selection geometry, augmented with GPUI's two-tier unwrapped-vs-wrapped `LineLayoutCache` (`zed/crates/gpui/src/text_system/line_layout.rs:523-698`) so container resizes only recompute wrap boundaries without re-shaping.
- **Luminance-quantized glyph dilation solves light-on-dark thin text on Apple displays without subpixel LCD fringes.** Subpixel LCD rendering is incompatible with transparent layers and GPU transforms. Instead, steal Kit's GPUI fork (`kitlangton/gpui`) luminance glyph dilation (`kitlangton/gpui/src/platform/mac/text_system.rs:42-81, 470-564`, commit `2582af8ad0`): quantize text color relative luminance ($0.2126R + 0.7152G + 0.0722B$) into 5 cache buckets (`0..=4`), pad `raster_bounds` by `1px`, and rasterize with `set_should_smooth_fonts(true)` at that gray fill level when `AppleFontSmoothing != 0`, paired with linear-space (`sRGB` framebuffer) alpha blending.
- **Never re-rasterize hinted glyphs on every frame of a spring transform.** Vello's `glifo` (`vello/glifo/src/glyph.rs:1702-1731`) folds uniform transform scale into `draw_font_size` and hashes `size.to_bits()`, thrashing the glyph atlas and causing stem-hinting pop on every frame of a 120 Hz spring animation. During active transforms, lock glyphs to unhinted/linear-metrics outlines rasterized at the target (or octave-stepped) scale and sample bilinearly, or promote large/hero animated text (`> 28px` or explicitly tagged) to Rive-style per-glyph vector paths (`rive-runtime/src/text/text.cpp:544-592`).
- **Use a unified `SumTree`-backed rope + display map for all text editing, from single-line inputs to multi-megabyte buffers.** Zed's concurrent B+ tree `SumTree` (`zed/crates/sum_tree/src/sum_tree.rs`, `TREE_BASE = 6`) maintains UTF-8 bytes, UTF-16 code units (required by Apple/Windows/Web IME), UTF-32 chars, line breaks, and soft-wrap display rows in $O(\log N)$ time with zero-copy `Arc` snapshots.
- **Implement native platform IME protocols directly on desktop and iOS, with a sliding-window `<textarea>` + `EditContext` hybrid on Web.** Direct `NSTextInputClient` (macOS), `UITextInput` + `UIEditMenuInteraction` subclass (iOS, stealing GPUI's deferred `reconcileTextInput` in `gpui_ios/src/ios/text_input.rs:197-318`), `ITfThreadMgr`/`ImmGetCompositionStringW` (Windows), and `zwp_text_input_v3` (Wayland) avoid hidden-native-widget desynchronization while preserving marked text, candidate window anchoring, Dictation, and Apple Writing Tools.
- **AccessKit (`v0.24` / 2026) is the clear winner for cross-platform accessibility and doubles as Rune's agent-inspector tree.** AccessKit now covers macOS (`accesskit_macos`), Windows (`accesskit_windows`), Linux AT-SPI (`accesskit_unix`), Android (`accesskit_android`), and iOS (`accesskit_ios`, `accesskit/adapters/ios/src/node.rs`). Building a single retained `accesskit::TreeUpdate` per frame gives VoiceOver/TalkBack/NVDA and AI testing/automation agents (`cua-driver`) one canonical semantic tree with roles, bounds, values, and deterministic `ActionRequest` dispatch.
- **Adopt a two-path layout architecture: `Taffy` (`v0.9.x`) for general Flexbox/CSS Grid UI + a `SumTree`-indexed height cache for virtualized lists + first-class layout interpolation hooks.** `Taffy` is heavily optimized (1.6 ms for 1,000 nodes vs Yoga's 1.5 ms on M1 Pro; 59 ms vs 84 ms on 100k Twitter feed nodes) and matches CSS mental models that LLMs write fluently, whereas `Pretext` + `SumTree` prefix-sum heights eliminate the 106.4 ms SwiftUI `sizeThatFits` bottleneck (a private iOS layout benchmark), dropping 500-paragraph resize passes to 2.6 ms.
---
## 1. Text Shaping & Fonts
### 1.1 `harfrust` vs `rustybuzz` vs OS Shapers (CoreText / DirectWrite)
| Dimension | `harfrust` (`v0.14.0`, Oct 2026) | `rustybuzz` (`v0.20.x`) | CoreText (`CTLine`/`CTTypesetter`) | DirectWrite (`IDWriteTextAnalyzer`) |
|---|---|---|---|---|
| **HarfBuzz parity** | HarfBuzz 14.5.1 (`harfrust/CHANGELOG.md:9`) | Trails HarfBuzz ~6–12 months | Apple AAT + OpenType engine | Microsoft OpenType engine |
| **Font table backend** | Native `read-fonts` (`fontations`), zero-copy via `ShaperData` | Bundled `ttf-parser` | `CGFont` / `CTFont` | `IDWriteFontFace` |
| **Performance** | ~10–15% faster than `rustybuzz`; caches reusable `ShaperData` & `ShaperInstance` | Fast CPU, re-parses tables per face | Fast, but Objective-C/CF allocation overhead per run | Fast, COM call overhead |
| **Apple `trak` / AAT (`morx`, `kerx`)** | Supported (`harfrust` ports HarfBuzz AAT tables) | Partial AAT support | Reference implementation (including optical size `opsz` tracking) | No AAT `morx` |
| **Cross-platform determinism** | 100% identical glyph IDs & advances across all OSes | 100% identical across all OSes | Apple-only | Windows-only |
**Source findings:**
- **`harfrust` has superseded `rustybuzz` across the Linebender and Servo ecosystems.** Originally started by Simon Cozens and Behdad Esfahbod (`harfrust/CHANGELOG.md:201-215`), `harfrust` is maintained directly under the HarfBuzz organization with Behdad Esfahbod and Chad Brokaw actively porting HarfBuzz algorithmic improvements (`harfrust/CHANGELOG.md:7-55`).
- **Pre-parsed table caching (`ShaperData`) and variation instance caching (`ShaperInstance`):** In `harfrust/src/hb/ot_shaper.rs` and `parley/parley/src/shape.rs:146-172`, `ShaperData::new(&font_ref)` pre-validates font tables once, while `ShaperInstance::from_variations(&font_ref, coords)` caches variation-axis coordinate lookups and feature stores. Shaping a run reuses a thread-local `harfrust::UnicodeBuffer` (`parley/parley/src/shape.rs:424-449`) with zero per-run heap allocations.
- **CoreText vs `harfrust` tradeoff on Apple:** GPUI currently calls `CTTypesetterCreateWithAttributedString` and `CTLineGetGlyphRuns` directly on macOS and iOS (`zed/crates/gpui_apple/src/text_system.rs:477-568`). While CoreText automatically applies Apple's undocumented optical tracking for `.AppleSystemUIFont` (`SF Pro`), allocating `CFAttributedString` and `CFDictionary` per text run costs measurable CPU time: in a private iOS layout benchmark, cold `CTFramesetter` measurement across 500 chat paragraphs takes **17.8 ms** (35.5 µs/msg), and SwiftUI `Text.sizeThatFits` takes **106.4 ms** (212.9 µs/msg).
### 1.2 Font Loading, Parsing, Hinting, and Fallback (`fontations`/`skrifa`, `swash`, `fontique`)
- **`fontations` (`read-fonts` + `skrifa` v0.42.0) vs `swash`:**
- Google's `fontations` workspace (`skrifa` + `read-fonts`) is now the standard Rust font stack used by Chrome (replacing FreeType in Chromium), Parley, Vello (`glifo`), and Bevy.
- `skrifa` (`fontations/skrifa/src/outline/mod.rs:1-148`) provides a complete TrueType bytecode interpreter, CFF/CFF2 hint engine, and a FreeType-derived Latin/CJK **autohinter** (`HintingOptions { engine: Engine::AutoFallback, target: Target::Smooth { mode: SmoothMode::Lcd | Normal, symmetric_rendering: true, preserve_linear_metrics: false } }`).
- `swash` is effectively unmaintained upstream; Parley removed `swash` entirely in `v0.4.0` (`parley/CHANGELOG.md:191-215`) in favor of `harfrust` + `skrifa`.
- **`fontique` (`v0.8.0`) for system font discovery and fallback:**
- `fontique` (maintained inside `parley/fontique`) handles cross-platform system font collection (`CoreText` on macOS/iOS, `DirectWrite` on Windows, `fontconfig` on Linux, `Android` XML/NDK font configuration) plus app-registered memory fonts (`register_fonts`).
- During shaping (`parley/parley/src/shape.rs:212-345`), `fontique` partitions text by `icu_properties::CodePointMapData::<Script>`, queries the family list first, and only falls back to `font_ctx.collection.fallback_families(FallbackKey::new(script, locale))` for `.notdef` (`glyph_id == 0`) sub-clusters, preserving variable font variation coordinates across fallback faces.
### 1.3 Variable Fonts, OpenType Features, and Emoji
- **Variable fonts (`wght`, `opsz`, `wdth`, `slnt`, custom axes):** `skrifa::MetadataProvider::axes()` resolves user axis tags into normalized `F2Dot14` design-space coordinates shared identically between `harfrust::ShaperInstance` (for `GPOS`/`GSUB` feature variations and `HVAR`/`MVAR` advances) and `skrifa::outline::OutlineGlyphCollection` (for `gvar`/`CFF2` interpolated glyph outlines).
- **OpenType features:** `harfrust::Feature` supports arbitrary 4-byte OpenType tags (`liga`, `calt`, `dlig`, `tnum`, `onum`, `zero`, `ss01`–`ss20`, `cv01`–`cv99`, `kern`) scoped by byte range (`parley/parley/src/shape.rs:178-206`).
- **Emoji (`COLRv0`/`COLRv1`, `sbix`, `CBDT`/`CBLC`):**
- Apple Color Emoji uses **`sbix`** (embedded PNG strips per strike ppem).
- Google Noto Color Emoji (Android/Linux/Web) uses **`COLRv1`** (vector paint graphs with linear/radial/sweep gradients, blend modes, and `VARC` variable composites) or **`CBDT`/`CBLC`** (embedded PNG bitmaps).
- Windows Segoe UI Emoji uses **`COLRv0`/`COLRv1`**.
- Vello's `glifo` (`vello/glifo/src/glyph.rs:289-424` and `vello/glifo/src/colr.rs`) inspects glyph tables in priority order: `skrifa::color::ColorGlyphCollection` (`COLRv0`/`COLRv1`) -> `sbix`/`CBDT` bitmap strikes (`image::load_from_memory_with_format(..., ImageFormat::Png)`) -> standard monochrome outline.
---
## 2. Text Layout
### 2.1 `parley` vs `cosmic-text` vs GPUI's Text System
| Engine | Shaping / Bidi / Line-Break Stack | Strengths | Weaknesses |
|---|---|---|---|
| **`parley` (`v0.12.0`, Oct 2026)** | `harfrust` + `skrifa` + `fontique` + `icu4x` (`icu_segmenter`, `parley_bidi`) | Clean split between `parley_engine` (core layout) and `fontique`; supports inline boxes (`InlineBox`), text-indent (`IndentOptions`), cluster/cursor geometry, `Alignment::Justify`, zero allocations on warm `LayoutContext`. | Does not include a built-in cross-frame unwrapped-vs-wrapped line cache out of the box (expects host UI to cache `Layout`). |
| **`cosmic-text`** | `rustybuzz` + `swash` + `fontdb` + `unicode-bidi` | Battle-tested in System76 COSMIC; includes a basic shape cache (`ShapeLine` vs `LayoutLine`). | Stuck on legacy `swash`/`rustybuzz`; weaker inline-box and CSS-aligned typography model than `parley`. |
| **GPUI (`gpui` + `gpui_apple` / `gpui_wgpu`)** | Platform `LineWrapper` + `layout_line` (`CoreText` on Apple, `DirectWrite` on Windows, `cosmic-text` on Linux/Web) | Best-in-class two-tier `LineLayoutCache` (`line_layout.rs:523-698`) with frame-epoch eviction and bulk `reuse_layouts`. | Fragmented per-OS shaping leads to subtle cross-platform line-break and fallback differences; manual boundary wrapper (`LineWrapper::wrap_line`) rather than full UAX #14. |
### 2.2 Bidirectional Text, Mixed Inline Runs, and Line Breaking
- **Bidirectional layout (UAX #9):** `parley` uses `parley_bidi` (`parley/CHANGELOG.md:27`) to resolve embedding levels per paragraph and reorders visual runs per wrapped line *after* line breaking (as required by UAX #9 Section 3.4), ensuring hit-testing (`Cursor::from_point`) and selection rectangles (`Selection::geometry_with`) remain accurate across mixed RTL/LTR/numeric runs.
- **Line breaking (UAX #14) & hyphenation:** `parley` uses `icu_segmenter::LineSegmenter` for locale-aware UAX #14 line break opportunities (handling CJK kinsoku shori, Thai dictionary breaking, and emergency `WordBreakStrength::BreakAll` / `KeepAll`).
- **Inline boxes (pills, badges, icons, inline code):** `parley::LayoutBuilder::push_inline_box(InlineBox { id, index, width, height })` (`parley/parley/src/layout.rs`) participates directly in line breaking, baseline alignment, and cursor navigation as an atomic cluster—essential for chat UIs with `@mention` pills, file chips, and inline status badges.
### 2.3 Truncation, Ellipsis, and SwiftUI/TextKit 2 Soft Fade Masks
- **Why ellipsis (`…`) layout is expensive when naively implemented:** Shaping an ellipsis string and re-shaping the truncated line tail on every resize requires mutating the glyph stream. GPUI (`zed/crates/gpui/src/text_system/line_wrapper.rs`) measures the ellipsis width once per font/size and truncates at cluster boundaries, while SwiftUI/TextKit 2 (`NSTextLayoutManager`) supports both glyph-replacement ellipsis and visual fade masks.
- **Soft fade masks instead of `…`:** In modern streaming chat and card UIs (and animated label containers), hard `…` glyph substitution causes jarring character popping as width animates or tokens stream in. Rendering the full shaped line clipped to the container rect with a **horizontal alpha gradient mask** over the trailing `16–24px` (in linear alpha space, direction-aware for LTR/RTL) requires **zero re-shaping during width animations**, never pops glyphs, and signals overflow cleanly. Rune should support both `Overflow::Ellipsis` (cached ellipsis cluster substitution on `max_lines`) and `Overflow::FadeMask { tail_px: f32 }` (shader-evaluated edge ramp in the text quad primitive).
### 2.4 Caching Shaped Lines Across Frames (Zed's `LineLayoutCache` & `Pretext`)
- **Zed's two-tier `LineLayoutCache` (`zed/crates/gpui/src/text_system/line_layout.rs:523-698`):**
1. **Unwrapped tier (`lines`):** Keyed by `(SharedString, font_size: Pixels, SmallVec<[FontRun; 1]>, force_width: Option<Pixels>)`. Stores `Arc<LineLayout>` containing shaped glyph positions and UTF-8 indices.
2. **Wrapped tier (`wrapped_lines`):** Keyed by `(SharedString, font_size, runs, wrap_width: Option<Pixels>)`. When `wrap_width` changes (e.g., dragging a split pane or rotating a phone), `layout_wrapped_line` (`line_layout.rs:639-644`) hits the cached `unwrapped_layout` and only runs `compute_wrap_boundaries` over pre-shaped advances.
3. **Two-frame epoch eviction + bulk reuse:** `LineLayoutCache` holds `current_frame` and `previous_frame` hash maps (`FxHashMap`). Views that do not re-layout call `reuse_layouts(range: Range<LineLayoutIndex>)` (`line_layout.rs:523-566`), which moves used entries from `previous_frame` to `current_frame` by index slice without even hashing keys. At `finish_frame()` (`line_layout.rs:586-600`), the maps swap and stale entries from `previous_frame` are dropped.
- **`Pretext` validation (a private iOS layout benchmark):**
- Across 500 mixed markdown/code chat messages on iOS, re-measuring height on viewport width change took **106.44 ms** with SwiftUI `sizeThatFits`, **17.75 ms** with cold `CTFramesetter`, **2.60 ms** with cached `CTFramesetter` frames, and **0.23 ms** with Pretext's pre-segmented width table (a **462x** speedup over SwiftUI `sizeThatFits`, though Pretext's naive whitespace Collapse had a 29% height mismatch against TextKit 2's hyphenation/kerning). Using **exact glyph-run advances** from the unwrapped `LineLayout` cache gives Pretext-class resize speed (**< 1 ms for 500 paragraphs**) with **0% height drift**.
---
## 3. Glyph Rendering
### 3.1 Glyph Atlas (Grayscale vs Subpixel AA) vs GPU Vector Outlines
| Technique | Crispness at 10–16pt (2x Retina / 1x LoDPI) | Memory & Bandwidth | Arbitrary 2D/3D / Spring Scale Cost | Verdict for Rune |
|---|---|---|---|---|
| **Grayscale Mask Atlas + Luminance Dilation (`kitlangton/gpui`)** | Excellent on 2x Retina and 1x with `skrifa` hinting + 5-level luminance dilation | Low (`R8Unorm` 1 byte/px; `RGBA8` 4 bytes/px for emoji) | Fast at fixed scale; thrashes atlas if re-rasterized per scale frame | **Primary UI text path** |
| **Subpixel LCD Atlas (`RGB` ClearType/FreeType LCD)** | Sharpest on 1x non-Retina horizontal RGB panels | 3–4x atlas memory; requires dual-source blending (`blend_src1`) | Breaks under rotation, scale, non-RGB subpixel layouts (OLED), or unpremultiplied compositing | **Avoid** (dead on macOS since Mojave, broken on OLED/mobile/rotated layers) |
| **SDF / MSDF Atlas** | Poor at 11–14pt UI sizes (rounded corners, stem weight distortion on CJK/kanji) | Medium (offline or slow generator per glyph) | Smooth infinite zoom | **Avoid for UI text** |
| **Slug (Lengyel GPU Bezier evaluation)** | Exact unhinted outlines at any zoom | Compact curve/band textures | Zero atlas thrashing under zoom/3D; higher fragment shader ALU per covered pixel; no stem hinting at 11–13pt | Optional hero/3D/canvas text path (patent entered public domain / open-sourced in 2026, or via `glifo`/Vello compute) |
| **Vello / `glifo` CPU-cached Atlas (`vello/glifo/src/glyph.rs`)** | Good (`skrifa` hinted outlines rasterized via `vello_common::kurbo` strip generator into shelf-packed `AtlasPage`) | Low (`PlainMask` + `Color` atlases) | Currently absorbs transform `t_d` into `draw_font_size` (`glyph.rs:1702-1731`), thrashing cache on scale animations | Steal `glifo`'s `skrifa` + `COLRv1` + `sbix` pipeline, **fix** its transform-scale key behavior |
| **Rive Direct Vector Path (`rive-runtime/src/text/text.cpp:544-592`)** | Exact unhinted vector curves tessellated/rasterized by GPU path renderer | Zero glyph atlas | Native per-glyph `TextModifierGroup` affine transforms + variable-font axis keyframing at 120 Hz | **Use for hero / animated / path-warped text (`TextRenderMode::Vector`)** |
### 3.2 macOS Font Smoothing, Stem Darkening, and Kit's GPUI fork (`kitlangton/gpui`) Luminance Glyph Dilation
**Why text in naive GPU renderers looks "too thin" or "washed out" on macOS:**
1. **Gamma blending error:** Blending a linear coverage mask $\alpha$ directly in non-linear sRGB space computes $C_{\text{out}} = \alpha C_{\text{fg}} + (1 - \alpha) C_{\text{bg}}$ in sRGB, which darkens mid-tones and makes light text on a dark background lose ~20–30% of its perceived stroke weight compared to dark text on a light background.
2. **CoreGraphics `AppleFontSmoothing` behavior in alpha-only contexts:** When rasterizing glyphs into a single-channel `kCGImageAlphaOnly` bitmap (`gpui_apple/src/text_system.rs:429-434`), calling `CGContextSetShouldSmoothFonts(cx, true)` tells CoreGraphics to apply **stem darkening (synthetic bolding/dilation)**—but CoreGraphics modulates the dilation strength by the *luminance of the active fill color* in the `CGContext`! If a GPU renderer rasterizes glyphs once into an alpha-only atlas with a fixed white (`1.0`) or black (`0.0`) fill color, either dark-on-light text looks overly heavy or light-on-dark text looks spindly.
**How Kit's GPUI fork (`kitlangton/gpui`) Luminance Glyph Dilation works (`kitlangton/gpui/src/platform/mac/text_system.rs`, commit `2582af8ad0`):**
- **5-bucket relative luminance quantization (`text_system.rs:42-69`):**
```rust
pub(crate) const GLYPH_DILATION_LEVELS: u8 = 5;
pub(crate) fn glyph_dilation_for_color(color: Hsla) -> u8 {
if !font_smoothing_enabled() {
return 0;
}
let rgba = color.to_rgb();
let luminance = 0.2126 * rgba.r + 0.7152 * rgba.g + 0.0722 * rgba.b;
(luminance * (GLYPH_DILATION_LEVELS - 1) as f32)
.round()
.clamp(0.0, (GLYPH_DILATION_LEVELS - 1) as f32) as u8
}
```
- **System default detection (`text_system.rs:71-81`):** Reads macOS `NSUserDefaults::standardUserDefaults().integerForKey("AppleFontSmoothing")` once via `OnceLock`; enabled when `!= 0` (matching macOS default `2`).
- **Cache key & bounds padding (`text_system.rs:470-499`):** `RenderGlyphParams` includes `dilation: u8` (`0..=4`). When `font_smoothing_enabled()` is true, `raster_bounds` adds `1px` padding on all four sides (`origin - (1, 1)`, `size + (2, 2)`) so dilated glyph stems never clip at the atlas tile boundary.
- **Rasterization (`text_system.rs:537-564`):** Inside `rasterize_glyph`, when `params.dilation > 0`:
```rust
let luminance = params.dilation as f64 / (GLYPH_DILATION_LEVELS - 1) as f64;
cx.set_should_smooth_fonts(true);
cx.set_gray_fill_color(luminance, 1.0);
```
This feeds CoreGraphics the exact 25%-stepped gray luminance (`0.0, 0.25, 0.50, 0.75, 1.0`), producing authentic macOS stem weight across both light and dark themes while capping atlas growth to at most the active foreground luminance buckets (typically 2 buckets per theme: primary text + muted text).
- **Cross-platform equivalent on `skrifa`/FreeType (`Windows`/`Linux`/`Android`):** When using `skrifa` + CPU/GPU outline rasterization off Apple, apply FreeType/Adobe CFF **stem darkening** in outline space (`darken_x = 0.025 * ppem`, modulated by foreground-vs-background luminance contrast) or a linear-space coverage gamma adjustment ($\alpha' = \alpha^{1.0 / \gamma_{\text{contrast}}}$) in the glyph fragment shader.
### 3.3 Why SDF / MSDF Fails for Small UI Text
- **Single-channel SDF** cannot preserve sharp corners (a single distance value rounds every corner when reconstructed at scales different from the raster grid), making `11–14pt` sans-serif stems (`I`, `l`, `m`, `n`) look mushy or blob-like.
- **Multi-channel SDF (MSDF)** preserves sharp 2-edge corners by encoding signed distances to two edge segments in R/G/B channels and taking `median(r, g, b)`. However:
1. Complex glyphs with >2 converging edges per texel (common in `11–14pt` CJK ideographs, `@`, `%`, `&`, and serif joins) suffer from **false edge artifacts (spikes and dropouts)** unless the MSDF texel resolution is high (`32x32` to `64x64` per glyph).
2.Generating an MSDF on the CPU on demand for newly encountered CJK/Unicode glyphs is **10–30x slower** than scanline coverage rasterization.
3. MSDF operates on unhinted outlines, losing pixel-grid stem alignment at `10–15pt` on 1x/2x displays.
### 3.4 Subpixel Positioning (`4` Horizontal × `1` Vertical Phases)
- Without subpixel positioning, snapping glyph origins to integer device pixels causes uneven inter-glyph kerning ("dancing letters" when slowly scrolling or adjusting tracking).
- Both GPUI (`zed/crates/gpui/src/text_system.rs`, `SUBPIXEL_VARIANTS_X = 4, SUBPIXEL_VARIANTS_Y = 1` on Retina) and Vello's `glifo` (`vello/glifo/src/glyph.rs:437-465`, `SubpixelAxis::Four` = `0.0, 0.25, 0.5, 0.75`) quantize the fractional device-pixel X coordinate into **4 horizontal subpixel phases** (`u8` `0..=3`) and **1 vertical phase** (since horizontal text baselines align vertically to rows).
- **Important optimization from `glifo/src/glyph.rs:444-465`:** Above a font size threshold (`OPTICAL_SIZE_THRESHOLD` ~ `24–32px` device pixels), subpixel phase quantization is reduced to `SubpixelAxis::Two` or `One` (integer pixel snapping), preventing atlas bloat on large headings where a `0.25px` shift is imperceptible.
### 3.5 Animated Text Under Spring Transforms (Why Text Jitters & How Apple / Figma / Rive Solve It)
**The bug in naive atlas renderers (including Vello `glifo`):**
- In `vello/glifo/src/glyph.rs:1702-1731` (`GlyphScaleProperties::new`), when a draw transform has uniform or axis-aligned scale (`t_a`, `t_d`), `glifo` folds `t_d` directly into `draw_font_size = font_size * t_d` and keys the glyph cache by `size: draw_font_size.to_bits()` (`u32`, `glyph.rs:480-523`).
- During a 120 Hz spring scale animation (e.g., `scale: 0.92 -> 1.02 -> 1.00`), `draw_font_size` takes 60+ distinct `f32` bit patterns in 500 ms. Worse, if hinting or integer advance rounding is enabled, stems jump between pixel columns ("swimming / jittering letters") and the glyph atlas thrashes on every frame.
**How production engines solve animated text:**
1. **Apple CoreAnimation / SwiftUI (`CATextLayer`, `.drawingGroup()`, `NSStringDrawingOptions`):**
- For standard layer transforms (`scaleEffect`, modal spring entrance), CoreAnimation caches the text layer at its **target (`1.0x`) contentsScale** (or highest octave scale) and applies the spring transform in the GPU compositor with bilinear texture filtering + linear metric advances (`CTFontCreateWithFontDescriptor` with `kCTFontLinearMetricsAttribute` / subpixel positioning).
- For SwiftUI `matchedGeometryEffect` / variable font transitions, Apple interpolates between two pre-rasterized scale snapshots or switches to unhinted subpixel-positioned outlines (`preserve_linear_metrics: true`).
2. **Figma (WebGL / WebGPU canvas renderer):**
- Figma renders text via cached glyph textures while stationary at a discrete zoom level, and during continuous zoom/spring animations either samples the nearest higher power-of-two mip octave from the glyph atlas with linear metrics or renders vector glyph meshes on the GPU.
3. **Rive (`rive-runtime/src/text/text.cpp:544-592`, `text_modifier_group.cpp`):**
- Rive never uses a bitmap glyph atlas for scene text. Every shaped glyph outline is extracted as an unhinted `RawPath` in normalized em-space (`rive-runtime/src/text/text.cpp:544-592`) and rendered directly by Rive's GPU vector renderer (PLS / atomic feathering) under per-glyph `Mat2D` transforms (`TextModifierGroup::transformGlyph` supporting per-character opacity, rotation, scale, position, and variable font axis keyframing at 120 Hz with zero atlas re-rasterization).
**Rune's hybrid rule for animated text:**
- **Static & scrolling UI text (`<= 28pt`, no active scale/rotation animation):** Hinted (`skrifa` `preserve_linear_metrics: false` on 1x, unhinted/light-hinted `preserve_linear_metrics: true` on $\ge 2\text{x}$ Retina) + 4x horizontal subpixel phase + 5-level luminance dilation in the glyph atlas.
- **Text inside an active scale/rotation spring transform:** Automatically switch the text primitive to **transform-invariant atlas sampling**: rasterize once at `ceil_octave(max_expected_scale) * font_size` with `preserve_linear_metrics: true` and fractional GPU quad positions (do **not** snap glyph quads to integer device pixels while transforming!), sampling with bilinear filtering + mild sharpening.
- **Hero / kinetic typography (`> 28pt`, or explicit `.textRenderMode(.vector)` / per-glyph `TextModifier`):** Bypass the bitmap atlas and emit unhinted `skrifa` outlines directly into Rune's GPU vector path pipeline (Vello/Slug-style curve evaluation), enabling Rive-class per-character spring choreography and variable-font weight/width animations with zero atlas traffic.
---
## 4. Text Editing (Single-Line Input through Rich Code/Prose Editor)
### 4.1 Selection, Caret, Bidirectional Cursor Movement, and Affinity
- **Selection representation:** Every selection is an ordered or directional pair `Selection { start: usize, end: usize, reversed: bool, goal_column: Option<f32> }` in UTF-8 byte offsets, accompanied by `Affinity::{Upstream, Downstream}` (`parley/parley/src/cursor.rs`).
- **Why `Affinity` is mandatory:** At a soft line wrap boundary, byte offset $k$ corresponds to **two distinct screen positions**: the end of line $i$ (`Affinity::Upstream`) and the start of line $i+1$ (`Affinity::Downstream`). Likewise, at an LTR/RTL bidi boundary, a single byte offset maps to two split-caret visual X positions. `parley::Cursor` encodes `(index: usize, affinity: Affinity)` directly and computes visual geometry via `Cursor::geometry(&layout, size)`.
- **Grapheme and word navigation (UAX #29):**
- Left/Right arrow movement steps by **extended grapheme clusters** (`icu_segmenter::GraphemeClusterSegmenter` or `unicode-segmentation`), so multi-codepoint emoji (family ZWJ sequences `👨‍👩‍👧‍👦`, skin-tone modifiers, flag pairs) and combining marks move and delete (`Backspace` vs `Delete`) correctly.
- Option+Left/Right (macOS) / Ctrl+Left/Right (Windows/Linux) and double-click word selection use UAX #29 word boundaries customized with character-class tables (`Alphanumeric`, `Punctuation`, `Whitespace`, plus configurable `word_characters` like `_` or `$` for code inputs).
- Triple-click selects the logical paragraph (or visual line with modifier), dragging extends selection by word (double-click-drag) or line (triple-click-drag) by anchoring the initial word/line range (`gpui_ios/src/ios/text_input.rs` / `zed/crates/editor`).
### 4.2 Buffer Data Structures: Ropes vs Zed's `SumTree`
| Data Structure | Memory / Node | Concurrent Snapshot | Multi-Coordinate Indexing (UTF-8, UTF-16, Lines, Display Wrap) | Used By |
|---|---|---|---|---|
| **`String` / Gap Buffer** | Contiguous `Vec<u8>` | Requires full clone | $O(N)$ scan for UTF-16 or line numbers | Naive single-line inputs |
| **`ropey`** | B-tree of UTF-8 chunks | Clone-on-write (`Arc`) | UTF-8, chars, lines; UTF-16 conversion added but no custom summary dimensions | Helix, cosmic-text |
| **Zed `SumTree` + `Rope` (`zed/crates/sum_tree/src/sum_tree.rs`, `zed/crates/rope`)** | `Arc`-backed B+ tree (`TREE_BASE = 6`, up to 12 children/node) | $O(1)$ lock-free `Clone` | Arbitrary `Summary` trait + multiple simultaneous `Dimension` types (`usize` bytes, `Point`, `PointUtf16`, `OffsetUtf16`, `Chars`) | Zed (`Buffer`, `DisplayMap`, `WrapMap`, `FoldMap`, `BlockMap`) |
**Why Rune should steal Zed's `SumTree` + `Rope` pattern (`zed/crates/sum_tree/src/sum_tree.rs:1-140`):**
- Every node in `SumTree<T>` stores an aggregated `T::Summary`. For `Rope::Chunk`, `TextSummary` tracks `len: usize` (UTF-8), `len_utf16: OffsetUtf16`, `lines: Point` (row/col), `first_line_chars`, `last_line_chars`, and `longest_row`.
- Converting between **UTF-8 byte offsets** (used by Rust/`harfrust`/`parley`) and **UTF-16 code-unit offsets** (mandated by macOS `NSRange`, iOS `UITextPosition`, Windows `ImmGetCompositionStringW`, and Web `EditContext`/`HTMLTextAreaElement`) is a single $O(\log N)$ B+ tree traversal (`rope.offset_to_offset_utf16(byte_offset)`), eliminating the #1 source of UTF-16 surrogate-pair crashes in emoji-heavy inputs!
- Even better, the **exact same `SumTree` crate** powers both text buffers and **virtualized list prefix-sum heights** (Section 7).
### 4.3 Undo/Redo Grouping, `DefaultKeyBinding.dict`, and System Text Services
- **Undo/Redo transaction grouping:** Group consecutive character insertions within a `300 ms` typing window (broken by whitespace/newline, paste, cursor jump, or backspace transitions) into a single undo transaction storing `(transaction_id, timestamp, selection_before, selection_after, Vec<Edit>)`.
- **macOS `DefaultKeyBinding.dict` bug in GPUI and how to fix it:**
- In `zed/crates/gpui_macos/src/window.rs:3513-3531`, GPUI implements `doCommandBySelector:` as:
```rust
// We ignore which selector it asks us to do because the user may have
// bound the shortcut to something else.
extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) { ... }
```
Because GPUI drops the `selector: Sel` argument and simply replays `keystroke_for_do_command` into its own keymap, any custom user binding in `~/Library/KeyBindings/DefaultKeyBinding.dict` (such as mapping a key chord to `deleteWordBackward:`, `moveToBeginningOfParagraph:`, `yank:`, `setMark:`, `swapWithMark:`, or a multi-selector array) is ignored!
- **Fix for Rune:** First check if the application keymap explicitly binds the raw keystroke. If not (or if `NSTextInputContext` synthesized one or more `NSStandardKeyBindingResponding` selectors from `DefaultKeyBinding.dict`), dispatch the actual `Sel` (`insertNewline:`, `deleteBackward:`, `deleteWordBackward:`, `moveWordForward:`, `moveToBeginningOfLine:`, `transpose:`, `yank:`, etc.) to the focused text input handler.
- **Spellcheck, Autocorrect, Dictation, and Apple Writing Tools (macOS 15+ / iOS 18+):**
- **Spellcheck & Autocorrect:** On macOS, query `NSSpellChecker.sharedSpellChecker` asynchronously on background worker threads per edited paragraph (`checkSpellingOfString:startingAt:language:wrap:inSpellDocumentWithTag:wordCount:`) and render wavy/dotted underlines as a text decoration layer; on iOS, `UITextInputTraits.spellCheckingType` and `autocorrectionType` are driven natively by `UITextInteraction`.
- **Dictation:** On both macOS (`NSTextInputClient`) and iOS (`UITextInput`), system Dictation streams tentative transcriptions via `setMarkedText:selectedRange:replacementRange:` and commits via `insertText:replacementRange:` (plus `insertDictationResult:` on iOS).
- **Apple Writing Tools (macOS 15+ / iOS 18+):** Conforming to `NSWritingToolsCoordinatorDelegate` (macOS) or `UIWritingToolsCoordinatorDelegate` / `UITextInput` (iOS) allows Apple Intelligence Writing Tools to read context ranges, animate proofreading/rewrite highlights, and apply replacements with built-in undo support.
---
## 5. IME (Input Method Editors) Per Platform
### 5.1 Architecture Matrix Across All 6 Platforms
| Platform | Native Protocol / API | Coordinate Unit | Composition / Marked Text | Candidate Window Positioning | Context / Recon Strategy |
|---|---|---|---|---|---|
| **macOS** | `NSTextInputClient` on `NSView` + `NSTextInputContext` (`gpui_macos/src/window.rs:236-298, 2700-2780, 3368-3532`) | UTF-16 `NSRange` | `setMarkedText:selectedRange:replacementRange:`; `unmarkText` | `firstRectForCharacterRange:actualRange:` (screen coordinates, bottom-left origin!) | Synchronous query into `InputHandler` during `handleEvent:` |
| **iOS** | Custom `UIView <UITextInput, UIKeyInput>` + `UITextInteraction` + `UIEditMenuInteraction` (`gpui_ios/src/ios/text_input.rs:197-1150`; `FlutterTextInputPlugin.mm:180-1100`) | Abstract `UITextPosition` wrapping UTF-16 index | `setMarkedText:selectedRange:`; `unmarkText` | `firstRectForRange:` + `caretRectForPosition:` + `selectionRectsForRange:` | **Deferred coalesced `reconcileTextInput`** (`dispatch_async` to main queue) to prevent UIKit feedback loops |
| **Android** | `View.onCreateInputConnection` -> `BaseInputConnection` + `InputMethodManager` | UTF-16 `Editable` / offsets | `setComposingText`, `setComposingRegion`, `finishComposingText` | `CursorAnchorInfo.Builder` (`setInsertionMarkerLocation`, `addCharacterBounds`) | State push via `imm.updateSelection` + `imm.updateCursorAnchorInfo` |
| **Web (2026)** | Primary: **Sliding-Window Hidden `<textarea>`** (`gpui_web/src/ime_mirror.rs:1-450`, `CONTEXT_CHARS = 512`) + progressive enhancement to **`EditContext` API** on Chromium/Edge | UTF-16 DOM offsets | `compositionstart`, `compositionupdate`, `compositionend`, `beforeinput` (`insertFromComposition`) | CSS positioning of `<textarea>` at `bounds_for_range` (`ime_mirror.rs:412-448`) or `EditContext.updateCharacterBounds` | Sliding 1,024-char window synced after every frame |
| **Windows** | `WM_IME_STARTCOMPOSITION`, `WM_IME_COMPOSITION` (`ImmGetCompositionStringW` with `GCS_COMPSTR`, `GCS_COMPATTR`, `GCS_CURSORPOS`, `GCS_RESULTSTR`) + TSF (`ITfThreadMgr` / `ITfContext`) (`gpui_windows/src/events.rs:654-790, 1710-1760`) | UTF-16 (`WCHAR` slice) | Clause-attributed composition (`ATTR_TARGET_CONVERTED`, `ATTR_CONVERTED`, `ATTR_INPUT`) | `ImmSetCompositionWindow` + `ImmSetCandidateWindow` (`CFS_CANDIDATEPOS`) | Per-window `ImmAssociateContextEx` enabled only when text input focused |
| **Linux (Wayland / X11)** | Wayland: `zwp_text_input_v3` (`gpui_linux/src/linux/wayland/client.rs:2278-2354`); X11: XIM (`XIC`) | UTF-8 byte offsets | `Event::PreeditString { text, cursor_begin, cursor_end }` buffered until `Event::Done { serial }` | `set_cursor_rectangle(x, y, width, height)` + `commit()` with serial tracking | Transactional `PreeditString` + `CommitString` applied atomically on `Done` |
### 5.2 Deep-Dive Findings & Subtle Platform Traps
1. **macOS Key Routing Order (`gpui_macos/src/window.rs:2700-2748`):**
- If you run app keybindings *before* `[inputContext handleEvent: native_event]`, multi-keystroke bindings (like Vim `jj` or chord shortcuts) intercept keys meant for Japanese/Chinese/Korean IME (turning `ji` into `jい` instead of `じ`) or swallow dead keys (`Option+e` -> `é`).
- Conversely, if you send *all* keys to `inputContext` first when no text input is focused, macOS beeps or eats shortcuts.
- **Rule:** Send key events to `inputContext` first if and only if: (a) `hasMarkedText()` is true (`is_composing`), OR (b) a printable key without `Ctrl`/`Cmd`/`Fn` is pressed while an IME input source is active and the focused view accepts text input (`is_ime_printable_key`), OR (c) it is a dead key (`key_char.is_none()`).
2. **iOS Direct `UITextInput` vs Hidden `UITextField` (`gpui_ios/src/ios/text_input.rs` & `FlutterTextInputPlugin.mm`):**
- **Why a hidden `UITextField` / `UITextView` fails:** A hidden native text field has its own internal TextKit layout and gesture recognizers; its selection handles, loupe magnifier, Scribble (Apple Pencil), and floating trackpad cursor (holding Spacebar on iOS keyboard) cannot match custom-rendered GPU text lines.
- **How GPUI and Flutter solve iOS `UITextInput` directly:**
- Create a dedicated `UIView` subclass (`GPUITextInputView` in `gpui_ios/src/ios/text_input.rs:197-318`, `FlutterTextInputView` in `FlutterTextInputPlugin.mm:400-1100`) that conforms to `UITextInput` and `UIKeyInput`.
- Attach a `UITextInteraction::editableInteraction()` (`text_input.rs:285-295`) and `UIEditMenuInteraction` so UIKit renders the **native iOS selection handles, double-tap/long-press loupe, floating keyboard trackpad cursor (`beginFloatingCursorAtPoint:` / `updateFloatingCursorAtPoint:` / `endFloatingCursor`), Scribble, and Cut/Copy/Paste/Autofill callout bar** directly over the GPU canvas using geometry returned by `firstRectForRange:`, `caretRectForPosition:`, and `selectionRectsForRange:`!
- **Critical anti-reentrancy trick (`gpui_ios/src/ios/text_input.rs:212-238, 1080-1145`):** Calling `[inputDelegate textWillChange:]` / `[inputDelegate selectionDidChange:]` synchronously inside a UIKit callback causes UIKit's `UITextInteraction` and autocorrect engine to re-enter `UITextInput` methods with stale state. GPUI sets an `in_input_callback: BOOL` ivar and schedules a single coalesced `reconcileTextInput` via `dispatch_async_f(dispatch_get_main_queue(), ...)` to notify `inputDelegate` (`selectionWillChange`/`selectionDidChange`/`textWillChange`/`textDidChange`) only when the model state actually diverged from what UIKit already knows.
- **Flutter's iOS 17+ `UITextInteraction` workaround (`FlutterTextInputPlugin.mm:260-285`):** On iOS 17+, `UITextInteraction` requires an view in the responder chain when keyboard dictation / trackpad mode activates; keeping `GPUITextInputView` in the view hierarchy (with zero visual sublayers) satisfies UIKit's responder checks.
3. **Web IME in 2026: Hidden Sliding-Window `<textarea>` + `EditContext` (`gpui_web/src/ime_mirror.rs:1-450`):**
- **State of `EditContext` in 2026:** W3C `EditContext` is shipping in Chromium/Edge (`Chrome 121+`), giving direct `textupdate`, `characterboundsupdate`, and `textformatupdate` (Japanese clause underline thickness/style) without DOM mutation side-effects. However, **Safari (WebKit) and Firefox still lack complete `EditContext` support on mobile/desktop in 2026**.
- **Why GPUI's `ImeMirror` (`gpui_web/src/ime_mirror.rs:1-130`) works everywhere:** Instead of mirroring an entire 100 KB document into a hidden `<textarea>` (which freezes mobile Safari), `ImeMirror` mirrors only a **sliding window of `CONTEXT_CHARS = 512` characters before and after the selection** (`ime_mirror.rs:23`), tracks `window_start_utf16` and `composition_start_utf16`, and positions the `1px` transparent `<textarea>` directly at the caret's `bounds_for_range` (`ime_mirror.rs:412-448`) so the OS candidate popup and macOS emoji picker (`Ctrl+Cmd+Space`) anchor to the exact caret pixel.
4. **Windows Clause Underline Attributes (`gpui_windows/src/events.rs:713-785, 1738-1760`):**
- Japanese and Chinese IMEs on Windows split an active composition into multiple clauses, where one clause is the **active conversion target** (`ATTR_TARGET_CONVERTED` / `ATTR_TARGET_NOTCONVERTED`, rendered with a thick or highlighted underline) and sibling clauses are `ATTR_CONVERTED` (thin/dotted underline). Querying `ImmGetCompositionStringW(ctx, GCS_COMPATTR, ...)` alongside `GCS_CURSORPOS` is required so users can see which clause Left/Right arrow keys are reconverting.
5. **Linux Wayland `zwp_text_input_v3` Serial & Vim-Mode Quirks (`gpui_linux/src/linux/wayland/client.rs:2278-2354`):**
- Wayland `zwp_text_input_v3` sends `PreeditString` and `CommitString` as pending state followed by `Event::Done { serial }`. If `Done` arrives with `ime_pre_edit == None` while previously composing, the client must clear marked text (`client.rs:2346-2350`).
- Also note `client.rs:2306-2320`: IBus intercepts single ASCII keys like `a` or `b` and sends them as `CommitString("a")` instead of `wl_keyboard::Key`, which breaks modal keybindings unless single-byte ASCII commits when not composing are routed through `KeyDown`.
---
## 6. Accessibility (a11y) & Agent Inspection
### 6.1 AccessKit in 2026 (`accesskit` v0.24+)
Inspection of `accesskit/` confirms AccessKit now ships first-party platform adapters across **all five native targets**:
- **macOS (`accesskit_macos`):** Maps `accesskit::Node` to `NSAccessibilityElement` subclasses (`accesskit/adapters/macos/src/node.rs:36-210`), posting `NSAccessibilityFocusedUIElementChangedNotification`, `NSAccessibilityValueChangedNotification`, and `NSAccessibilityLayoutChangedNotification`.
- **iOS (`accesskit_ios`):** Implemented in `accesskit/adapters/ios/src/node.rs:1-515` (`v0.4.0`), mapping `accesskit::Node` to `UIAccessibilityElement` with `UIAccessibilityTraits` (`Button`, `Header`, `Adjustable`, `UpdatesFrequently`, `Selected`, `NotEnabled`), `accessibilityFrame` (converted via `UIAccessibilityConvertFrameToScreenCoordinates`), `accessibilityActivate`, `accessibilityIncrement`/`Decrement`, and `accessibilityScroll:`.
- **Android (`accesskit_android`):** Implemented in `accesskit/adapters/android/` (`v0.6.0`), bridging to Android's `AccessibilityNodeProvider` (`AccessibilityNodeInfo` virtual view hierarchy) for TalkBack.
- **Windows (`accesskit_windows`):** Implements UI Automation (`IRawElementProviderSimple`, `ITextProvider`, `IValueProvider`, `IScrollItemProvider`) for Narrator, NVDA, and JAWS.
- **Linux (`accesskit_unix`):** Implements AT-SPI2 over D-Bus (`zbus`) for Orca.
### 6.2 Roles, Actions, Live Regions, Focus, and Text Navigation
- **Core primitives (`accesskit/accesskit/src/lib.rs`):**
- `NodeId(NonZeroU64)`: Stable 64-bit identifier per semantic node.
- `Role` (`lib.rs:62-284`): 180+ WAI-ARIA / native roles (`Button`, `TextInput`, `MultilineTextInput`, `Switch`, `Slider`, `List`, `ListItem`, `Dialog`, `Tab`, `TabPanel`, `ScrollView`, `TextRun`, etc.).
- `Action` (`lib.rs:289-350`): `Click`, `Focus`, `Blur`, `Increment`, `Decrement`, `ReplaceSelectedText`, `SetValue`, `SetTextSelection`, `ScrollIntoView`, `ScrollToPoint`, `SetScrollOffset`, `Expand`, `Collapse`, `ShowContextMenu`, `CustomAction`.
- `Live` (`lib.rs:584`): `Off`, `Polite`, `Assertive` (maps to `UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, ...)` on iOS and `NSAccessibilityAnnouncementRequestedNotification` on macOS).
- **Character-level text navigation (`Role::TextRun`):** For multi-line text inputs and selectable text, AccessKit represents each wrapped visual line as a child `Role::TextRun` node carrying `character_lengths: Box<[u8]>`, `character_positions: Box<[f32]>`, `character_widths: Box<[f32]>`, and `word_starts: Box<[u8]>`. AccessKit transforms this directly into macOS `accessibilityFrameForRange:`, Windows `ITextRangeProvider`, and iOS text selection navigation without platform-specific text glue!
### 6.3 How Flutter Maps `SemanticsNode` and What iOS VoiceOver Needs
- In Flutter (`flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h` & `SemanticsObject.mm`), every `SemanticsNode` becomes a `SemanticsObject : UIAccessibilityElement` (or `SemanticsObjectContainer` for children).
- **Critical iOS VoiceOver requirements that custom GPU frameworks miss:**
1. **Two-finger Z-scrub ("Escape" gesture):** iOS VoiceOver users scrub a "Z" with two fingers to dismiss modals, pop navigation stacks, or close sheets. `accesskit_ios` (`accesskit/adapters/ios/src/node.rs`) and Rune's root container must implement `accessibilityPerformEscape` and map it to a dismiss/back action on the active modal or navigation route.
2. **Modal sibling masking (`accessibilityViewIsModal`):** When a dialog, sheet, or popover is open, setting `Node::set_modal(true)` (which maps to `accessibilityViewIsModal = YES` on iOS) prevents VoiceOver swipe navigation from cycling through background views behind the scrim.
3. **Scroll-on-swipe (`accessibilityScroll:` & `Action::ScrollIntoView`):** When VoiceOver swipes past the last visible row of a virtualized list, the list must keep a **1-screen buffer of offscreen semantic nodes** above and below the viewport and handle `Action::ScrollIntoView` + `accessibilityScroll:` by advancing the virtual scroll offset and posting `UIAccessibilityLayoutChangedNotification`.
4. **Rotor Custom Actions (`UIAccessibilityCustomAction`):** Swipe actions on list rows (e.g., Archive, Delete, Pin) must register as `CustomAction` on the row's `accesskit::Node` so VoiceOver users can trigger them via the vertical swipe rotor.
### 6.4 Should the Accessibility Tree Double as the Agent-Inspector Tree?
**Yes — unequivocally.**
- Kit's existing automation tools (`cua-driver`, macOS Accessibility inspector, agent proof scripts) already operate by snapshotting the accessibility tree, binding stable element tokens, reading bounds/labels/values, and invoking semantic actions (`Click`, `SetValue`, `ScrollIntoView`).
- By making `accesskit::TreeUpdate` a **first-class frame output** (built incrementally for dirty subtrees or serialized on demand over a local Unix socket / WebSocket / MCP debug endpoint even when OS screen readers are inactive), Rune gets:
1. **Zero-cost agent drivability on every platform** (including headless Linux CI, iOS simulators, Android emulators, and Web) via one JSON/binary `TreeUpdate` schema.
2. **Built-in a11y enforcement:** If an AI agent cannot see or click a button in an agent proof script, a blind VoiceOver user cannot use it either.
3. **Lightweight extension:** Add an optional side-table `InspectorMetadata` keyed by `accesskit::NodeId` for agent-only diagnostics (component source `file:line`, test ID, computed style/spring state, layout constraints) without polluting the OS accessibility bridge.
---
## 7. Layout
### 7.1 Comparative Evaluation of Layout Models
| Dimension | **Taffy (`v0.9.x`, Flexbox + CSS Grid)** | **SwiftUI Proposal / Size Negotiation** | **Flutter Constraints-Down, Sizes-Up (`BoxConstraints`)** | **Clay (Nic Barker's C micro-layout)** | **Morphorm (Subform / Vizir units)** |
|---|---|---|---|---|---|
| **Mental Model** | CSS Flexbox & CSS Grid (`Style` struct) | Parent proposes `(w?, h?)` -> Child picks size -> Parent places child | Parent passes `(min_w..max_w, min_h..max_h)` -> Child returns `Size` | Single-header immediate-mode `Sizing::Fixed`, `Grow`, `Percent`, `Fit` | Constraint units (`Pixels`, `Percentage`, `Stretch`, `Auto`) |
| **Passes per Tree** | 1–3 passes (Flex intrinsic measure + flex resolve; cached by `(known_dimensions, available_space)`) | 1–3 proposals (`nil` ideal, `0` min, `.infinity` max, concrete width) | Strictly $O(N)$ single pass (except `IntrinsicWidth`/`Height`) | Strictly 3 linear array passes (BFS/DFS over flat arena) | 2 passes (upward intrinsic, downward stretch) |
| **Agent-Writability (LLM accuracy)** | **Highest:** Every LLM has millions of Tailwind/CSS Flexbox/Grid examples in pretraining | High (SwiftUI modifiers), but `.frame(maxWidth: .infinity)` + `layoutPriority` traps are common | Medium-High (`Expanded`/`Flexible` inside unconstrained `ScrollView` panics at runtime!) | Good for simple rows/columns; no CSS Grid or baseline wrap | Low training corpus; unfamiliar `Units::Stretch` rules |
| **1M-Row Virtualized List Perf** | Must NOT instantiate 1M Taffy nodes; pair with virtual viewport + `SumTree` height index | `LazyVStack` struggles with variable heights (`sizeThatFits` = 106.4 ms / 500 rows) | `SliverList` is fast, requires custom sliver protocol | Arena-based (~15 µs for visible ~100 nodes), no built-in virtualization | Requires external virtualization |
| **Layout Animation (FLIP / Shared Element)** | Outputs static `Layout { location, size }`; requires framework-level previous-rect diffing | First-class (`matchedGeometryEffect`, `Layout` protocol animatable properties) | Manual (`AnimatedSize`, `Hero` overlay widgets) | Immediate-mode rect output; easy to interpolate `(x, y, w, h)` per ID | Static rect output |
### 7.2 Measured & Cited Benchmark Numbers
1. **Taffy (`v0.9.2`) vs Yoga (`v3.2.1`) on Apple M1 Pro (`taffy/README.md:94-114`, Criterion benchmarks):**
- **1,000 nodes (deep hierarchy):** Taffy **1.60 ms** vs Yoga **1.50 ms** (~1.6 µs/node).
- **10,000 nodes (deep hierarchy):** Taffy **17.5 ms** vs Yoga **16.2 ms**.
- **10,000 nodes (super-deep 12-level hierarchy):** Taffy **24.6 ms** vs Yoga **36.2 ms** (**Taffy is 32% faster** due to 9-slot `Cache` in `taffy/src/tree/cache.rs` avoiding exponential re-measurement).
- **100,000 nodes (wide 2-level hierarchy):** Taffy **98.9 ms** vs Yoga **191.5 ms** (**Taffy is 48% faster**).
- **Twitter feed benchmark (`yoga/taffy` real-world cards):**
- 1,500 nodes: Taffy **626 µs** vs Yoga **950 µs** (**1.52x faster**).
- 15,000 nodes: Taffy **6.40 ms** vs Yoga **11.17 ms** (**1.75x faster**).
- 100,000 nodes: Taffy **59.17 ms** vs Yoga **84.42 ms** (**1.43x faster**).
2. **GPUI's Taffy Integration (`zed/crates/gpui/src/taffy.rs:1-315`):**
- GPUI wraps `TaffyTree<NodeContext>` in `TaffyLayoutEngine`, using `FxHashMap<GlobalElementId, NodeId>` and a 2-frame mark-and-sweep (`computed_layouts: FxHashSet<NodeId>`) so unchanged subtrees keep their Taffy nodes and measurement cache across frames instead of rebuilding the Taffy arena from scratch each frame.
3. **Text Measurement Inside Layout (a private iOS layout benchmark):**
- In any real UI, **80–90% of layout wall-clock time is spent inside the leaf `measure_function` (text shaping & line wrapping), not in the Flexbox solver itself.**
- Measuring 500 chat paragraphs on iOS:
- SwiftUI `sizeThatFits`: **106.44 ms** (212.88 µs/item) — blows nine 120 Hz frames (8.33 ms budget).
- Cold CoreText `CTFramesetter`: **17.75 ms** (35.51 µs/item).
- Reused `CTFramesetter` height: **2.60 ms** (5.19 µs/item).
- Pre-computed width-break table (`Pretext`): **0.23 ms** (0.45 µs/item).
### 7.3 Solving the 3 Hard Layout Cases in Rune
1. **Agent-Writability:**
- Expose **Tailwind/Flexbox/Grid-aligned builder methods** backed by `taffy` (`flex()`, `flex_col()`, `items_center()`, `justify_between()`, `gap(px(8.))`, `grid_cols(3)`) **plus** ergonomic SwiftUI-style shorthand (`hstack()`, `vstack()`, `zstack()`, `spacer()`) that compile down to the exact same `taffy::Style`. Agents never hit Flutter's dreaded *"RenderFlex children have non-zero flex but incoming height constraints are unbounded"* crash because Taffy gracefully resolves `flex-grow` inside auto-sized containers to content size.
2. **1M-Row Variable-Height Virtualized Lists:**
- Never insert offscreen rows into `TaffyTree`.
- Store the 1M-row list state in a **`SumTree<ListItemSummary>`** (`zed/crates/sum_tree/src/sum_tree.rs`) where each item summary stores `(count: usize, height: f32, is_measured: bool)`:
- Unmeasured items initialize with a fast estimated height (or `LineLayoutCache` unwrapped width / container wrap width estimate).
- Mapping a scroll pixel offset $y \in [0, 50,000,000]$ to the first visible row index is a **$O(\log N)$ `SumTree` seek (~200 nanoseconds for 1M items)**.
- Only the visible viewport rows + overscan buffer (~20–40 rows) are laid out via `Taffy` each frame (< 0.15 ms). When a row's measured height differs from its estimate while scrolling upward, anchor scroll position relative to the first visible item's top edge so the viewport never jumps.
3. **Layout Animation (Spring-Driven Bounds & Shared-Element `layout_id`):**
- Why layout animation is painful in raw Flexbox: Taffy outputs discrete `(location, size)` rectangles per frame.
- **Rune's solution:** Attach an optional `.layout_id(id)` / `.animate_layout(Spring)` to any element. After `Taffy` computes the target layout rect $R_{\text{target}} = (x, y, w, h)$ in window space, Rune's layout-animation pass compares $R_{\text{target}}$ against the previous frame's rendered rect $R_{\text{prev}}$ for that `ElementId`:
- **Position delta ($\Delta x, \Delta y$):** Drive a 2D spring offset on the element's GPU transform matrix (zero re-layout cost!).
- **Size delta ($\Delta w, \Delta h$):** Drive a 2D spring on the element's rendered clip/background bounds while keeping text children anchored (or using `Overflow::FadeMask`) so text never re-wraps on every intermediate frame of a container resize spring!
---
## 8. What to Steal / What to Avoid
### What to Steal
1. **Kit's GPUI fork (`kitlangton/gpui`) 5-level Luminance Glyph Dilation (`kitlangton/gpui/src/platform/mac/text_system.rs:42-81, 470-564`, commit `2582af8ad0`):** Quantize text foreground luminance into 5 buckets (`0..=4`), pad glyph bounds by `1px`, and rasterize with `AppleFontSmoothing` / stem darkening scaled to that luminance so light-on-dark and dark-on-light text have optically matched weight.
2. **GPUI's Two-Tier `LineLayoutCache` (`zed/crates/gpui/src/text_system/line_layout.rs:523-698`):** Separate cached unwrapped `LineLayout` (shaping) from `WrappedLineLayout` (wrap boundaries) with two-frame epoch swapping and index-range `reuse_layouts`. Resizing a window or split pane only recomputes line breaks over cached glyph advances, never re-running HarfRust/CoreText shaping.
3. **Zed's `SumTree` (`zed/crates/sum_tree/src/sum_tree.rs`):** Use one battle-tested concurrent B+ tree for both text ropes (simultaneous UTF-8, UTF-16, line/col, and soft-wrap coordinates in $O(\log N)$) and 1M-row virtualized list height indexing.
4. **Parley `v0.12.0` (`parley` + `fontique` + `harfrust` + `skrifa` + `icu4x`):** Use Parley's shaping/bidi/segmentation pipeline (`parley/parley/src/shape.rs`, `layout.rs`, `cursor.rs`) for UAX #9 bidi reordering, UAX #14 line breaking, `InlineBox` layout, and `Affinity`-aware cursor/selection geometry.
5. **Vello `glifo`'s `COLRv1` + `sbix` + `skrifa` Glyph Extractor (`vello/glifo/src/glyph.rs:289-465`, `colr.rs`):** Steal `glifo`'s priority waterfall (`COLRv0/v1` vector paint trees -> `sbix`/`CBDT` PNG bitmaps -> `skrifa` hinted outlines) and size-adaptive subpixel quantization (`SubpixelAxis::Four` at body sizes, `One` at large sizes).
6. **GPUI iOS's `GPUITextInputView` + Deferred `reconcileTextInput` (`zed/crates/gpui_ios/src/ios/text_input.rs:197-318, 1080-1145`) & Flutter's `UIEditMenuInteraction` / Floating Cursor (`FlutterTextInputPlugin.mm:400-950`):** Direct `UITextInput` conformance with `UITextInteraction` and coalesced main-queue delegate reconciliation gives native iOS selection handles, loupe, Scribble, Dictation, and Spacebar trackpad cursor with zero reentrancy bugs.
7. **GPUI Web's 512-Char Sliding-Window `ImeMirror` (`zed/crates/gpui_web/src/ime_mirror.rs:1-130, 412-448`):** Bound hidden `<textarea>` synchronization to $\pm 512$ characters around the selection and position it at the exact caret rect, adding Chromium `EditContext` as a fast path when detected.
8. **AccessKit (`v0.24+`) Across All 5 Platforms (`accesskit/adapters/{macos,ios,android,windows,unix}`):** Emit one `accesskit::TreeUpdate` that simultaneously powers VoiceOver (macOS/iOS), TalkBack (Android), UIA (Windows), AT-SPI (Linux), and Rune's AI agent inspector.
### What to Avoid
1. **Avoid absorbing continuous spring scale transforms into the glyph atlas cache key (`vello/glifo/src/glyph.rs:1702-1731`):** Hashing `draw_font_size.to_bits()` during a 120 Hz scale animation rasterizes 60+ transient font sizes per glyph, thrashing the atlas and causing stem-hinting jitter.
2. **Avoid ignoring the `Sel` argument in macOS `doCommandBySelector:` (`zed/crates/gpui_macos/src/window.rs:3515`):** Dropping the Cocoa selector breaks custom `~/Library/KeyBindings/DefaultKeyBinding.dict` bindings and standard Cocoa text movement/kill-ring commands.
3. **Avoid SDF / MSDF for body UI text (`10–16pt`):** MSDF rounds or spikes complex CJK/symbol corners, lacks stem hinting, and has slow CPU generation for dynamic Unicode fallback.
4. **Avoid subpixel LCD (`RGB`) glyph atlases:** Incompatible with layer opacity, rotation, scale springs, OLED subpixel layouts, and modern macOS/mobile compositors.
5. **Avoid hidden native `UITextField` / `NSTextView` overlays for mobile/desktop IME:** They desynchronize selection handles, break custom line heights/inline pills, and fight custom scroll physics.
6. **Avoid per-OS text shapers as the sole layout engine:** Relying exclusively on CoreText on Apple and DirectWrite on Windows causes cross-platform line-wrap differences and `CFAttributedString` allocation overhead (17.8 ms / 500 paragraphs cold vs < 1 ms cached `harfrust` + `LineLayoutCache`).
7. **Avoid putting offscreen virtualized list items into `TaffyTree` or re-running text shaping during width animations:** Use `SumTree` height prefix-sums for offscreen rows and `Overflow::FadeMask` or cached unwrapped glyph advances during animated width transitions.
---
## 9. Decisive Recommendations for Rune
### 9.1 Architectural Decisions & Rejected Alternatives
| Sub-Area | Rune Decision | Rejected Alternatives & Why |
|---|---|---|
| **1. Text Shaping & Fonts** | **`harfrust` (`0.14`) + `skrifa` (`0.42`) + `fontique` (`0.8`)**, with a thin platform bridge on Apple to read `.AppleSystemUIFont` (`SF Pro`) `trak` optical tracking tables. | **Rejected `rustybuzz` + `swash`:** `swash` is unmaintained; `rustybuzz` is 10–15% slower and duplicates `ttf-parser` tables.<br>**Rejected CoreText/DirectWrite-only shaping:** Allocates OS objects per run and produces divergent line wraps across platforms. |
| **2. Text Layout** | **`parley` (`0.12`)** wrapped in **GPUI's two-tier `LineLayoutCache`** (unwrapped shaped runs separated from wrapped line boundaries) + first-class **`Overflow::FadeMask`** shader clip alongside `Overflow::Ellipsis`. | **Rejected `cosmic-text`:** Tied to `rustybuzz`/`swash`, lacks `InlineBox` layout.<br>**Rejected naive `Pretext` whitespace width tables:** 29% height mismatch on hyphenated/kerned prose (`opencode-ios-pretext-layout`); caching exact `LineLayout` glyph advances achieves the same sub-millisecond resize speed with 0% drift. |
| **3. Glyph Rendering** | **Two-tier hybrid:**<br>• **Tier 1 (UI Text `<= 28pt`):** Grayscale `R8Unorm` (`RGBA8` for `COLRv1`/`sbix` emoji) shelf-packed atlas with `skrifa` hinting, 4x X-subpixel phases, and **5-level luminance glyph dilation (`kitlangton/gpui`)**.<br>• **Tier 2 (Animated / Hero Text):** Transform-invariant linear-metrics octave sampling for scaled UI containers, and **direct GPU vector paths (`skrifa` outlines -> Vello/Slug)** for hero/per-character animated text (`> 28pt` or `.textRenderMode(.vector)`). | **Rejected SDF/MSDF:** Artifacts on CJK and `11–14pt` UI text.<br>**Rejected LCD subpixel AA:** Breaks transparency and transforms.<br>**Rejected per-frame `draw_font_size` atlas rasterization (`glifo` default):** Thrashes atlas on spring scales. |
| **4. Text Editing** | **Single unified `TextBuffer` built on Zed's `SumTree` + `Rope`**, supporting both `<Input>` and multi-MB `<Editor>`, UAX #29 grapheme/word movement (`icu_segmenter`), `Affinity`-aware bidi carets, 300 ms undo coalescing, and macOS `DefaultKeyBinding.dict` selector dispatch. | **Rejected separate `String` for `<Input>` and `ropey` for `<Editor>`:** Maintaining two cursor/IME/UTF-16/undo stacks doubles surface area for surrogate-pair and IME bugs. |
| **5. Platform IME** | **Direct native protocols per OS:** `NSTextInputClient` (macOS), `UITextInput` + `UITextInteraction` + deferred `reconcileTextInput` (iOS), `InputConnection` + `CursorAnchorInfo` (Android), `ImmGetCompositionStringW`/TSF (Windows), `zwp_text_input_v3` (Wayland), and **512-char sliding-window `<textarea>` + `EditContext`** (Web). | **Rejected hidden `UITextField`/`NSTextField`:** Breaks native iOS loupe/handles/Scribble alignment on custom GPU text.<br>**Rejected `EditContext`-only on Web:** Not supported on Safari/iOS WebKit or Firefox in 2026. |
| **6. Accessibility & Agent Tree** | **`accesskit` (`v0.24+`) across all 5 native platforms**, with the frame's `accesskit::TreeUpdate` + `InspectorMetadata` exposed directly as Rune's **AI Agent Inspector & Automation Tree**. | **Rejected custom per-OS accessibility bridges:** Thousands of lines of duplicated ObjC/JNI/COM glue.<br>**Rejected separate DOM/inspector tree for agents:** Diverges from real screen-reader semantics. |
| **7. Layout** | **`taffy` (`0.9.x`, incremental retained tree) + `SumTree` prefix-sum height virtualizer for lists + built-in FLIP/Spring layout-rect interpolation.** | **Rejected Flutter `BoxConstraints`-only:** Poor LLM ergonomics (`Expanded` in `ScrollView` runtime crashes) and lacks CSS Grid.<br>**Rejected `Clay` / `Morphorm`:** Lack CSS Grid and deep LLM pretraining familiarity. |
### 9.2 Recommended Rust Crate Dependencies
```toml
[dependencies]
# Text Shaping, Fonts, Bidi & Segmentation
harfrust = "0.14"
skrifa = { version = "0.42", features = ["std", "autohint_shaping"] }
read-fonts = "0.37"
fontique = "0.8"
parley = "0.12"
icu_segmenter = "2.0"
icu_properties = "2.0"
# Buffer & Virtualized List Indexing
sum_tree = { path = "crates/sum_tree" } # Forked/extracted from zed/crates/sum_tree
rope = { path = "crates/rope" } # Forked/extracted from zed/crates/rope
# Layout
taffy = { version = "0.9", features = ["flexbox", "grid", "taffy_tree"] }
etagere = "0.2" # Shelf-packing allocator for glyph & emoji atlases
# Accessibility (Core + Platform Adapters)
accesskit = "0.24"
[target.'cfg(target_os = "macos")'.dependencies]
accesskit_macos = "0.24"
[target.'cfg(target_os = "ios")'.dependencies]
accesskit_ios = "0.4"
[target.'cfg(target_os = "windows")'.dependencies]
accesskit_windows = "0.31"
[target.'cfg(target_os = "linux")'.dependencies]
accesskit_unix = "0.20"
[target.'cfg(target_os = "android")'.dependencies]
accesskit_android = "0.6"
```
### 9.3 Top Risks Ranked
1. **Risk #1 (High): iOS `UITextInput` + `UITextInteraction` edge cases across iOS 17/18/19 (Scribble, Floating Trackpad Cursor, Autofill, Dictation, Hardware Keyboard).**
- *Why:* UIKit's `UITextInteraction` makes undocumented synchronous re-entrant calls into `UITextInput` during autocorrect and trackpad gestures.
- *Mitigation:* Port `GPUITextInputView` (`zed/crates/gpui_ios/src/ios/text_input.rs`) and its deferred `reconcileTextInput` state machine verbatim, augmented with Flutter's `beginFloatingCursorAtPoint:` (`FlutterTextInputPlugin.mm:780-845`), and test on real iOS Simulator via `fieldwork-prove`.
2. **Risk #2 (High): Cross-platform stem weight & Apple `.AppleSystemUIFont` (`SF Pro`) optical fidelity when moving from CoreText to `harfrust` + `skrifa`.**
- *Why:* Users immediately notice if macOS/iOS text looks 5% thinner, wider, or differently tracked than native SwiftUI/AppKit.
- *Mitigation:* Apply `SF Pro` `trak` table optical tracking in `harfrust` on Apple platforms, and support both CoreGraphics `rasterize_glyph` (with 5-level luminance dilation from `kitlangton/gpui`) on Apple and `skrifa` + stem-darkening dilation on Windows/Linux/Android/Web.
3. **Risk #3 (Medium-High): Animated text jitter and re-wrap stutters during 120 Hz spring layout transitions.**
- *Why:* Naive layout springs re-wrap text at every intermediate width and re-snap glyphs to device pixel grids, causing visible 1px crawling and line-reflow pops.
- *Mitigation:* Enforce two invariants in the renderer: (a) during an active transform spring, disable integer pixel-grid snapping and lock the glyph atlas lookup to unhinted linear-metric outlines at the target octave scale; (b) during animated width transitions, freeze wrap width to the target width (or use `Overflow::FadeMask`) unless explicitly opted into live reflow.
4. **Risk #4 (Medium): Virtualized list scroll-anchor jumping with dynamic streaming markdown/chat rows.**
- *Why:* When unmeasured items above the viewport resolve to a different height than estimated, naive scroll-top offsets jump visibly.
- *Mitigation:* Anchor the scroll state to `(anchor_item_id, pixel_offset_within_item)` in the `SumTree<ListItemSummary>` rather than a raw global `scroll_top` pixel float.
5. **Risk #5 (Low-Medium): AccessKit iOS (`accesskit_ios`) maturity for complex custom gestures and virtualized lists.**
- *Why:* `accesskit_ios` (`v0.4.0`) is the newest AccessKit adapter and requires host cooperation for `accessibilityScroll:` and offscreen buffer nodes.
- *Mitigation:* Keep a 1-viewport semantic overscan buffer in virtualized lists and wire `Action::ScrollIntoView` + `accessibilityPerformEscape` directly into Rune's scroll and navigation primitives.
---
## 10. Open Questions (Requiring Prototype or Benchmark)
1. **`skrifa` + CPU/GPU stem darkening vs CoreGraphics `CGContext` glyph rasterization on macOS/iOS:** Can `skrifa` (`Target::Smooth` with custom 5-level luminance dilation in our shader/outline dilator) match CoreGraphics `CTFontDrawGlyphs` + `AppleFontSmoothing` pixel-for-pixel on `SF Pro` at `11–15pt` on 2x Retina, allowing us to drop `CGContext` glyph rasterization on Apple entirely, or should we keep `CGContext` rasterization on Apple as an `AppleGlyphRasterizer` backend? *(Needs a side-by-side pixel-diff prototype at 5 luminance levels.)*
2. **Hero vector text threshold (`28pt` vs `36pt`) and GPU cost on mobile:** At what exact point size does rendering unhinted `skrifa` outlines directly through the Vello/Slug GPU path pipeline match or beat the glyph atlas in frame time and memory bandwidth on an iPhone 16 Pro at 120 Hz? *(Needs a GPU frame-time benchmark on iOS device.)*
3. **Android `InputConnection` batch edit behavior on Samsung Keyboard vs Gboard:** Samsung Keyboard issues aggressive `beginBatchEdit` / `setComposingRegion` sequences across word boundaries that differ from Gboard. *(Needs a small Android IME harness test against our `SumTree` UTF-16 offset mapping.)*
+981
View File
@@ -0,0 +1,981 @@
# 06 — State/reactivity model and animation as a first-class primitive
Research agent notes, 2026-10-21. Sources are cited inline. Kit's own code is cited by `repo/path:line`. Numbers marked *est.* are estimates, not measurements.
## Summary
- **State pick: a keyed retained tree rebuilt from pure view functions, with GPUI-style models and
Xilem-style handlers.** App state lives in typed `Model<T>`s held in a store. Views are plain
`fn(&mut Cx, ..) -> El`. Reading a model through `cx.read` subscribes that view scope. Handlers get
`&mut T` when they run, queued between frames, so there is no `RefCell` re-entry and no
`cx.notify()` to forget. The output is a type-erased `El` tree that is diffed by key. Fine-grained
signals, GPUI's re-render-per-frame and immediate mode are rejected as the *primary* model (see the
recommendation below).
- **Animation is never state.** Animated values never pass through view functions. A view states
*targets*. The diff sees that a target changed and sends `Animate{prop, target, spring}` to a
**render thread**. That thread owns the presented tree, the property tracks, scroll physics and
drag bindings. When one value animates, the main thread does **zero** work: no view re-run, no
layout, no diff. SwiftUI (attribute graph), Core Animation (render server), Compose (deferred
draw-phase reads) and Motion (`MotionValue`s that skip React) all reach for this same split.
- **Every property is a piecewise analytic track.** A segment is `{t0, x0, v0, target, curve}`, and
you sample position *and* velocity at any absolute time. Retargeting = sample `(x, v)` at the
commit's presentation time, then start a new segment from there. This is psychopomp's model
(`psychopomp/crates/psychopomp/src/timeline.rs:143-337`) generalised. It fixes the launcher's problem that Core
Animation can't report velocity (`launcher/src/macos.rs:2735-2777` has to guess "mid-flight" from
heights and fall back to an analytical model).
- **Springs are `Spring::new(duration, bounce)` with ω = 2π/duration and ζ = 1 − bounce**
(1/(1+bounce) when bounce < 0). This matches SwiftUI, Flutter's `withDurationAndBounce`, knobs,
the private iOS client and Kit's generated presets exactly. Each spring is a named token pair (enter/exit) loaded from
Kit's motion presets, and the render thread re-resolves tokens live, so tuning
retargets springs already in flight.
- **Layout animation sits between layout and commit.** Layout runs once, at the target. For each
node whose frame changed, the runtime animates the **edges** (left, right, top, bottom) in
parent space, with one spring per axis. A stationary edge gets no track, so it can't jiggle. Width
leads by giving the X axis a faster spring. Rigid travel stays rigid. Backgrounds, borders,
shadows and glass are parametric shapes drawn at the presented size, so there's no FLIP scale
distortion.
- **Presence and identity are built into the runtime.** Removing a keyed node moves it to
`Exiting{gen}`. By default it leaves layout flow (`popLayout`), plays its exit and unmounts only
after its opacity track has *settled at 0*. If the same key comes back first, the node revives
from where it is now. This is PresenceGate's generation guard
(`PresenceGate.swift:12-69`) applied to every node.
- **Kit's rules become defaults, not discipline.** Direct manipulation applies instantly. Nothing
animates on first mount. Reduced motion is applied per property class by the runtime. Both edges
snap to 1/64 device px on the render thread. Every clip has soft edges by default; a hard clip is
an explicit opt-out that the inspector reports. Persistent items never blur.
- **One clock, with time scaling and manual stepping.** Virtual time is `base + (host − anchor) ×
scale` and re-anchors when the scale changes (`scrawl/src/ui/motion.rs:17-53`). Tracks are sampled
at the frame's **target presentation timestamp**. Tests use `Clock::Manual{hz}`, and the frames
come out bit-identical when the math uses deterministic `libm`.
- **The render thread writes motion traces natively** in Scrawl's JSONL format
(`scrawl/src/ui/motion.rs:563-788`): the element tuple `[id,x,y,w,h,a,r,flags,(vis)]`, plus exact
flag and intent bits (the motion linter's `src/analyze.ts:41-43`). The runtime *knows* which changes were
intended, so the internal motion linter no longer has to infer it. Tracing costs nothing when it's off.
---
## Part 1 — State and reactivity
### 1.1 Criteria (from the brief and the task)
| Criterion | Why it matters for Rune |
| --- | --- |
| Per-frame CPU when one value animates | 120 Hz means an 8.33 ms budget. Animation must not depend on how complex the view tree is. |
| A 1M-row list | Infinite-software apps: logs, transcripts, mail. |
| Agent-writability | Explicit data flow, few silent failure modes, clear errors, fast compiles. |
| Hot-reload state preservation | Edit to pixels in under 300 ms with state kept, through code patches. |
| Borrow-checker ergonomics | Agents give up, or reach for `Rc<RefCell>`, when lifetimes fight them. |
| Test determinism | Headless rendering, golden frames, golden motion traces. |
### 1.2 The models compared
**Fine-grained signals: SolidJS, Leptos `reactive_graph`, Sycamore, Floem.**
Components run once and build a graph of signals, memos and effects. Writing a signal re-runs only
the effects that read it. Rust implementations keep signals in an arena and hand out `Copy` handles,
which removes lifetimes. Floem's `RwSignal` is just an `Id` plus phantom types
(`floem/reactive/src/signal.rs:223-228`), and Leptos 0.7 moved to arena-allocated `Copy` signals
([reactive_graph docs](https://docs.rs/reactive_graph)).
- *One value animating:* the cost is minimal: one effect runs and sets one property. In a native
Rust renderer, though, the property write still triggers a style, layout and paint pass on the
main thread (Floem animates through its style pass; `floem/src/animate/mod.rs`, `easing.rs:208`).
- *1M rows:* a keyed `<For>` diffs the whole source on each change (O(n)), and a signal per row
costs memory (around 100 B or more each, *est.*, so ~100 MB). You still need virtualization; the
signal graph doesn't help there.
- *Agents:* silent failure modes. Reading a signal outside a tracking scope gives a stale UI with no
error. Effects can form cycles, ordering inside a batch is subtle, a disposed signal panics later,
and `move ||` closures are everywhere.
- *Hot reload:* **the worst of the four.** State is captured in closures created by a component body
that runs once. Patching that body means re-running it, which recreates the signals. Leptos
hot-reloads `view!` templates, but a Rust logic change resets state
([cargo-leptos](https://github.com/leptos-rs/cargo-leptos)). Dioxus 0.7 keeps state across
[Subsecond](https://github.com/DioxusLabs/dioxus/tree/main/packages/subsecond) patches precisely
*because* it re-runs components and stores state in hooks, which is the retained model.
- *Determinism:* fine when single-threaded.
**Retained tree plus diff: React, Xilem, SwiftUI's AttributeGraph, Compose's slot table.**
View functions are re-run when their inputs change. The result is diffed against the retained tree
by structural identity plus explicit keys, and state lives in slots keyed by that identity.
- *One value animating:* naive React re-renders the component subtree every frame. That's why
framer-motion skips React with `MotionValue`s. The serious systems take animation out of the view
layer. SwiftUI interpolates `Animatable` attributes in the attribute graph without re-evaluating
`body` ([WWDC23 Explore SwiftUI animation](https://developer.apple.com/videos/play/wwdc2023/10156/);
for graph internals see [Rens Breur's reverse engineering](https://rensbr.eu/blog/swiftui-attribute-graph/)).
Compose's `Modifier.graphicsLayer { }` lambda reads state only in the draw phase, so animating it
skips composition and layout ([Compose phases](https://developer.android.com/develop/ui/compose/phases)).
Compose's footgun is that reading the same value during composition silently recomposes every frame.
- *1M rows:* fine when the list is lazy (LazyColumn, `List`). Only visible rows exist as views.
- *Agents:* the best of the four. `view = f(state)` is explicit and testable. The footguns are
React's rules of hooks (order-based identity) and deep generic view types (Xilem's
`View<State, Action, Context>` with `build/rebuild/teardown`, `xilem/xilem_core/src/view.rs:53-90`),
which mean long compiles and unreadable errors.
- *Hot reload:* **the best of the four.** After a patch, re-run every view; state survives because
identity is stable (React Fast Refresh, Compose Live Edit, SwiftUI previews).
- *Borrow checker:* Xilem's handlers receive `&mut State` when they run, which is borrow-free at
compile time. That's the nicest Rust ergonomics I found.
**GPUI: entities plus whole-view render.**
`Entity<T>` lives in `App`. `render(&mut self, window, cx)` rebuilds the element tree whenever the
view is notified. Layout (Taffy) and paint run for dirty views, and `AnyView::cached` reuses clean
subtrees (`zed/crates/gpui/src/view.rs:46,258`). As of today GPUI has analytic springs
(`crates/gpui/src/spring.rs:13-37`, stiffness/damping/mass) and `with_spring` that keeps position and
velocity per element ID (`elements/animation.rs:119-160`). But every animation frame calls
`window.request_animation_frame()`, which **notifies the current view**
(`window.rs:2742-2745`; `animation.rs:349`). So the view is re-rendered, laid out and painted on the
main thread every frame.
- *Agents:* forgetting `cx.notify()` gives a stale UI. Updating an entity while it's already being
updated panics at runtime. Every call takes `window, cx`.
- *Hot reload:* reasonable. Entity state lives outside the code, but a changed struct layout breaks
Subsecond-style patching.
**Immediate mode: egui, Clay.**
The whole UI is rebuilt and laid out every frame. Persistent bits sit in ID-keyed memory, such as
egui's `animate_bool`.
- *One value animating:* the full UI is rebuilt on the main thread every frame, around 1–3 ms for a
rich app (*est.*), and nothing can be offloaded to a compositor. It costs battery on a 120 Hz
display.
- *1M rows:* fine with manual virtualization.
- *Agents:* the simplest of the four, and state is just the app struct, which survives hot patching.
- *Gaps:* layout animation, presence and matched geometry all need retained identity and the
previous frame's rects. Once you add those you've rebuilt a retained tree.
**Summary table** (✓ good, ~ mixed, ✗ poor):
| | One value animating | 1M rows | Agent footguns | Hot-reload state | Borrow ergonomics | Determinism |
| --- | --- | --- | --- | --- | --- | --- |
| Signals (Leptos/Floem) | ✓ (main-thread effect) | ~ | ✗ silent stale reads | ✗ | ✓ Copy handles | ✓ |
| Retained diff (SwiftUI/Compose/Xilem) | ✓ *if* animation lives below views | ✓ lazy | ✓ (hooks/generics aside) | ✓ | ✓ Xilem-style | ✓ |
| GPUI entity + render | ✗ re-render per frame | ✓ (`list` sum tree) | ~ notify/double borrow | ~ | ~ | ✓ |
| Immediate (egui/Clay) | ✗ full rebuild | ✓ manual | ✓ | ✓ | ✓ | ✓ |
### 1.3 The pick
**Retained, keyed, type-erased view tree. Model-granularity auto-tracking. Queued `&mut` handlers.
All animation below the view layer, on a render thread.**
1. **App state lives in `Model<T>`** (a `Copy` generational handle into the store, owned by the
app). The store is the hot-reload unit: one place to snapshot, serialize and inspect.
2. **Views are plain functions returning `El`.** `El` is a type-erased builder (boxed nodes, no deep
generics), which keeps compiles fast and errors short for agents. `cx.read(model)` returns `&T`
and records a dependency for the current *view scope* (a component function or a list row).
Writing a model marks its readers dirty. There's no manual notify.
3. **Handlers are `move |state: &mut T, event, tx| ..`**, queued and applied in order before the next
build. They can't run while views are being built, so a double borrow can't happen. `tx` holds
the transaction: animation choice, origin, extra model updates.
4. **Local state uses explicit string keys** within a scope: `cx.state("open", || false)`. Rejected:
hook order (React's rules, a classic agent footgun) and `#[track_caller]` positions (Compose-style
positional memoization; a hot patch shifts line numbers and loses the state). A duplicate key in
one scope panics with the scope path in the message.
5. **Identity is the parent path plus an explicit `.key(..)`.** Keys are required on dynamic
children (`list`, `for_each`); without one, the build fails loudly with a message saying how to
fix it.
6. **Values that change every frame never re-run views.** Animations, scroll offsets and drag
offsets are render-thread tracks or `Live<f32>` values (§2.4). Views state targets and
bindings; they never see the per-frame value. If a view needs the presented geometry (hit
testing, "fling from where it is"), `cx.presented(node)` gives a snapshot that is *not tracked*.
This removes Compose's "read in the wrong phase" footgun by design.
7. **Finer invalidation comes later.** A `#[derive(Model)]` can record field-level reads, the way
Swift's `@Observable` does. Model-level tracking is the v1 default because it's simpler and
honest. Agents split models when invalidation is too coarse.
### 1.4 API sketch (as an agent would write it)
```rust
use rune::prelude::*;
use rune::motion; // generated from Kit's motion presets: SNAP, SETTLE, REFLOW, GLIDE, MORPH, ...
#[derive(Model, Default)] // Model = reflect (inspector) + serde (hot-reload migration)
pub struct Mail {
pub threads: Vec<Thread>, // 1M is fine: only visible rows become views
pub selected: Option<ThreadId>,
pub query: String,
}
pub fn app(cx: &mut Cx) -> El {
let mail = cx.model::<Mail>(); // created once, keyed by type (or cx.model_keyed("inbox"))
let m = cx.read(mail); // this scope re-runs when `mail` changes
col()
.child(
search_field(&m.query)
// direct manipulation: Origin::Direct, so applied instantly (Kit rule 5)
.on_input(mail, |m, text, _tx| m.query = text),
)
.child(thread_list(mail, m.filtered()))
}
fn thread_list(mail: Model<Mail>, rows: impl ListSource<Item = Thread>) -> El {
list(rows) // ListSource: len(), key(i), get(i); no Vec<El>
.key(|t| t.id)
.estimated_row_height(56.0)
.row(move |cx, t| { // each row is its own tracked scope, built lazily
let selected = cx.read(mail).selected == Some(t.id);
thread_row(mail, t, selected)
})
.layout_animation(motion::REFLOW) // siblings slide into gaps, container resizes on a spring
.presence(Presence::pop()) // removed rows exit in place, out of flow
}
fn thread_row(mail: Model<Mail>, t: &Thread, selected: bool) -> El {
let id = t.id;
row()
.padding(12)
.fill(if selected { theme::ACCENT_SOFT } else { theme::CLEAR }) // a target, not a frame value
.animate(Prop::Fill, motion::SNAP) // node default for this prop
.child(text(&t.subject).weight(if t.unread { 600 } else { 400 })) // overflow: soft right fade
.on_tap(mail, move |m, _ev, tx| {
tx.animate(motion::SNAP); // opt in: a tap that selects isn't dragging the thing itself
m.selected = Some(id);
})
.on_key(Key::Backspace, mail, move |m, _ev, tx| {
tx.animate(motion::REFLOW);
m.threads.retain(|x| x.id != id); // row exits, siblings slide
})
}
fn disclosure(cx: &mut Cx, title: &str, body: impl FnOnce(&mut Cx) -> El) -> El {
let open = cx.state("open", || false); // State<bool>, keyed by scope path + "open"
col()
.child(button(title).on_tap(open, |o, _, tx| { tx.animate(motion::SETTLE); *o = !*o; }))
.child_if(*cx.get(open), body) // enters and exits through presence, height reflows
.resize(Resize::Mask { feather: 28.0 })
}
```
Remote and sync changes go through `app.apply(Origin::Remote, |m: &mut Mail| ...)`. Their default is
*animate with the node's declared spring*, because Kit animates undo, redo and remote changes, not
the user's own hand.
### 1.5 The 1M-row list
- `ListSource` is a trait (`len`, `key(i)`, `get(i)`, optional `height_hint(i)`). App data stays in the
app's `Vec`, a database cursor or a rope. **No views and no signals per row.**
- Heights live in a **sum tree** keyed by row (GPUI's `list` does the same). That gives O(log n)
offset↔index lookups, and unmeasured rows use estimates. Measured heights replace estimates with
**scroll anchoring**: the first visible row keeps its screen position, which matters for streaming
transcripts in the private iOS client.
- The main thread materializes the visible rows plus overscan (around 1.5 screens) as row scopes and
diffs them by key: O(visible) per change, not O(n). The render thread scrolls through what is
already there (§2.11) and publishes the offset so the main thread can top up overscan. Running out
of rows (checkerboarding) is a hard problem, below.
- Inserting or deleting in the middle shifts indices but not keys. Presence and layout animation work
on keys, so a deleted row exits and its visible neighbours slide.
- Rough budget (*est.*): 60 visible rows × (view build + diff + incremental layout) ≈ 0.3–0.8 ms on
M-series when a model change touches every visible row; 0 ms per scroll frame between overscan
top-ups.
### 1.6 Hot-reload state preservation
- **Code patch, same types** (Subsecond-style jump-table patching; see the hot-reload research doc):
the store and every `cx.state` slot are untouched. The runtime marks every view scope dirty and
rebuilds. The diff reconciles by key, and the render thread's tracks keep running. If a patched
view emits new targets, they **retarget from the current position and velocity**, so you can tune
a value while it's moving.
- **Changed model or state struct layout:** `#[derive(Model)]` includes serde. The runtime
serializes the store and keyed slots, swaps in the new code (or restarts the process) and
deserializes with defaults for new fields. Local `cx.state` slots with an incompatible type reset
one at a time and log the key path.
- **Spring or token edits:** the token table is data (§2.18), so changing it needs no code patch.
- Why the alternatives lose: signals tie state to closures created by run-once component bodies;
hook order and `#[track_caller]` identity break when a patch moves code.
### 1.7 Determinism and tests
- A single-threaded build/diff/layout pipeline. Handlers apply in queue order. A deterministic
`HashMap` seed in test builds.
- `TestApp` runs the render thread's frame function **synchronously** on the test thread, with
`Clock::Manual{hz: 120}`. Every frame lands at `n × 1/120 s`.
- Track math uses a deterministic `libm` (no platform `exp`/`sin` differences), so traces and PNGs
are bit-identical on macOS and Linux CI. The extra cost is a few ns per call (*est.*).
```rust
#[test]
fn deleting_a_row_slides_siblings_and_exits_in_place() {
let mut app = TestApp::new(app).size(390, 844).scale(3.0).hz(120);
app.apply(Origin::Remote, |m: &mut Mail| m.threads = fixtures::threads(5));
app.settle(); // runs until no track is active
app.focus(key!("thread", 2)).press(Key::Backspace);
let trace = app.record(|app| app.advance(ms(600))); // motion-trace JSONL, in memory
trace.assert_clean(); // pop-in, jump, reversal, fade-cutoff, ...
assert!(app.node(key!("thread", 2)).is_none()); // unmounted only after its exit settled
assert_eq!(app.node(key!("thread", 3)).unwrap().frame().y, 2.0 * 56.0);
insta::assert_binary_snapshot!("after.png", app.png());
}
```
---
## Part 2 — Animation as a first-class primitive
### 2.1 Kit's prior art and what each one teaches
| Source | What it does | Lesson for Rune |
| --- | --- | --- |
| knobs `src/core/spring.ts:61-73` | `springMotion({duration,bounce})`: ω = 2π/d, ζ = 1−b (1/(1+b) below 0) | The canonical mapping. |
| knobs `spring.ts:1-2, 33-53` | Semi-implicit Euler in fixed 480 Hz substeps, dt clamped to 0.1 s; retarget keeps `v` | Works, but it can't be sampled at an arbitrary *t*. Rune uses closed form. |
| knobs `spring.ts:16-26` | `set(target, delay)`: delayed retargets (cascades); repeating the same target is a no-op | Delays and the no-op rule belong in the track model. |
| knobs `spring.ts:84-96` | Samples a spring into CSS `linear()` | The web backend can bake tracks into `linear()` only where WAAPI offload helps. |
| The private iOS client `SpringSolver.swift:86-90, 96-113, 168-200` (on `origin/main`; the brief's `Core/Utilities/Motion.swift` path doesn't exist, and local `main` is behind) | Closed form for under-, critically and over-damped springs; `retarget(to:preservingVelocity:)` | The exact math Rune's segment uses. Velocity override = gesture handoff. |
| The private iOS client `PresenceGate.swift:12-69` | Mounts immediately on open; unmounts only when *the latest generation's* completion fires while closed | Generation-guarded presence, in the runtime for every keyed node. |
| The private iOS client `PresenceGate.swift:71-97` | Blur forced to 0 at progress ≥ .98 (no offscreen cost at rest), but **kept until unmount on close** so the last frame doesn't flash sharp | Blur filters attach and detach on settle and unmount, never mid-transition. |
| The private iOS client `MotionDisplayLink.swift:4-11, 62-73` | One 80–120 Hz link; `dt` and `now` from `targetTimestamp` through `AnimationTimeScale` | Sample at the predicted presentation time, through the scaled clock. |
| The private iOS client `MotionConstants.swift:10-37` | Every spring and fade is a named, live-tunable token; `reducedFade` .20 s | A token table, not literals. |
| Scrawl `src/ui/motion.rs:17-53` | One clock: `base + elapsed × scale`; changing the scale re-anchors so running ages continue | Clock design, verbatim. |
| Scrawl `motion.rs:58-163, 316-360` | `Tune::DEFAULT` plus `tune.json` polled at 4 Hz in debug builds; presets; `scrawl tune rust` prints a paste-back | Live tuning loop; the source of truth stays in code. |
| Scrawl `motion.rs:551-788` | motion-trace JSONL: header, per-frame `e/m/g/c/cm/ev`, writes only what changed, `SCRAWL_MOTION_TRACE` | Rune emits the same format from the render thread. |
| Scrawl `src/native/pill/model.rs:130-200` | Closed-form critically damped step that **snaps to the target if it would cross it** | Prevents velocity overshoot, but it's a velocity cliff (the motion linter's `stop-dead`). Rune keeps C¹ by default (open question). |
| Scrawl `src/ui.rs:82-95` | `Spring::visual(d, b)` stored in a field called `response` | Naming drift: `response` means different things in psychopomp. Use `duration` everywhere. |
| The launcher `docs/motion.md:41-44` | Pill↔panel morph runs in WindowServer (CA); GPUI renders the panel **once at its final layout**; CA drives clip/scale/blur | Final-layout-once plus animated geometry is FLIP. It works at 120 Hz with zero CPU relayout. |
| The launcher `src/ui/core.rs:2425-2481` | `CaSpringSpec`; velocity **normalized by distance** for `CASpringAnimation.initialVelocity` | Keep velocities in property units; normalize only at a CA boundary. |
| The launcher `core.rs:2483-2522` | `eval_ca_spring_spec_at`: evaluates the CA spring analytically so `CAShapeLayer` paths stay within < 0.02 pt | If Rune mirrors tracks into CA (system glass), it must evaluate the same function. |
| The launcher `core.rs:2604-2705` + `macos.rs:2735-2777` | `compute_ca_interruption_handoff` (called from `src/ui.rs:1461,1695`): the analytical presented state, overridden by `presentationLayer` values only when "mid-flight" is detected by a height heuristic (`h > 34.5 && |h − analytic| < 80`) | **CA doesn't expose velocity, and presentation values are racy.** Rune's render thread owns the analytic tracks, so `(x, v)` is always exact. |
| Kit's motion presets (generated Rust) | `KitSpring{duration,bounce}`, `omega()/zeta()`; enter/exit pairs (`SETTLE` .3/.24, `REFLOW` .4/.32, `MORPH` .3/.16 → .27/.08, …) | Tokens are pairs. Exit springs run 10–25% shorter. |
| psychopomp `crates/psychopomp/src/motion.rs:43-73` | `Spring::sample(initial: MotionState{position,velocity}, target, elapsed)` | Pure sampling from `(x0, v0)`. |
| psychopomp `motion.rs:75-132` | `settling_time`: a deterministic time after which *both* error and speed stay under thresholds (envelope for ζ < 1, bisection for ζ = 1) | Precompute `settle_at` per segment, so finding idle tracks needs no sampling and no hysteresis. |
| psychopomp `timeline.rs:143-248` | Track = list of segments (`Set`/`Spring`/`Ease`); `sample_at` picks the last segment with start ≤ t | The track data structure. |
| psychopomp `timeline.rs:250-337`, `timeline/retarget.rs:62-67, 120-215` | A retarget samples the prior state at its start time; `Animate`/`Replay{from}`/`Immediate`; batches are transactional; "an unchanged Animate request retains its pending due time and existing trajectory" | Retarget semantics: transactional commits; setting the same target again is a no-op. |
### 2.2 Other frameworks
- **SwiftUI.** `withAnimation`/`Transaction` attach an animation to a *state change*, and the change
propagates to every animatable attribute it touches. `Spring(duration:bounce:)` is the mapping
above ([docs](https://developer.apple.com/documentation/swiftui/spring)). Springs **merge**: a
retarget keeps velocity ([WWDC23 Animate with springs](https://developer.apple.com/videos/play/wwdc2023/10158/)).
`CustomAnimation` (iOS 17) exposes `animate(value:time:context:)`, `velocity` and `shouldMerge`
([docs](https://developer.apple.com/documentation/swiftui/customanimation)). Non-merging animations
run alongside the earlier ones and are combined. `matchedGeometryEffect` handles shared elements;
`.transition` with `.blurReplace` covers presence. *Steal:* transactions, merge-by-default springs,
velocity as part of the API. *Avoid:* animations evaluated on the main thread.
- **Core Animation.** A model tree and a presentation tree. Implicit animations come through actions
and are batched by `CATransaction`. Interpolation runs out of process in the render server
(`backboardd` on iOS, WindowServer on macOS), so a main-thread hitch doesn't stall motion. UIKit
made animations interruptible with **additive** animations
([WWDC14 #236](https://developer.apple.com/videos/play/wwdc2014/236/)) and
`UIViewPropertyAnimator` ([WWDC16 #216](https://developer.apple.com/videos/play/wwdc2016/216/)).
`CASpringAnimation(perceptualDuration:bounce:)` arrived in iOS 17
([docs](https://developer.apple.com/documentation/quartzcore/caspringanimation/init(perceptualduration:bounce:))).
*Steal:* the off-main render thread, model/presentation split, atomic transactions. *Avoid:* no
velocity readback (the launcher's workaround above), no determinism, Apple-only.
- **Compose `Animatable`.** `animateTo(target, spec, initialVelocity = velocity)` cancels the running
animation and continues from its current value and velocity. `animateDecay` handles flings
([docs](https://developer.android.com/develop/ui/compose/animation/value-based#animatable)). Deferred
reads in `graphicsLayer {}` skip composition and layout. *Steal:* the retarget signature and phase
separation. *Avoid:* leaving phase choice to the author.
- **Motion (framer-motion).** `layout` does FLIP with transforms plus *scale correction* for
border-radius, shadows and children. `layoutId` handles shared elements, `AnimatePresence
mode="popLayout"` lets exits leave layout flow, and `LayoutGroup` coordinates siblings
([layout docs](https://motion.dev/docs/react-layout-animations)). It computes deltas in a
projection tree so nested elements don't drift. Note that Motion's `visualDuration` = SwiftUI
duration / 1.2 (Kit's motion rules). *Steal:* popLayout, layoutId, projection to keep paths
straight. *Avoid:* scale-based FLIP, which distorts text and needs corrections. Rune draws
shapes parametrically instead.
- **Flutter.** `AnimationController` ticks on the UI (now main) thread with `Simulation`s
(`SpringSimulation`, `FrictionSimulation`), and the raster thread only draws. Since 3.29 (iOS and
Android) and 3.35 (macOS and Windows), Dart runs on the platform main thread, giving up a separate
UI thread for synchronous platform interop
([breaking change](https://docs.flutter.dev/release/breaking-changes/macos-windows-merged-threads)).
So Flutter animations hitch whenever the main thread does. `SpringDescription.withDurationAndBounce`
matches SwiftUI (`flutter/packages/flutter/lib/src/physics/spring_simulation.dart:70-82`). Its scroll
physics are the best open reference (§2.11). *Steal:* the simulation trait, scroll physics, velocity
trackers. *Avoid:* animation evaluated on the main thread.
- **Rive.** State machines with typed inputs (bool, number, trigger), transitions with their own
duration, interpolation and interruptibility, blend states, and `advance(dt)`, which is
deterministic (`rive-runtime/src/animation/`, e.g. `state_machine_instance.cpp`,
`blend_state_1d.cpp`). *Steal:* a transition table keyed by (from-phase, to-phase), the right shape
for Scrawl-style pills with phases. Rive files could become a node type later.
- **GPUI.** Springs now exist (above), but they're evaluated on the main thread inside
`request_layout`, which forces a view re-render every frame. *Avoid* that structure.
- **Xilem/Masonry.** `on_anim_frame(elapsed_ns)` runs as a pass over the widget tree on the main
thread (`xilem/masonry_core/src/passes/anim.rs:11-51`). It's fine for simple widgets, but nothing
happens off-thread.
### 2.3 Spring math (normative)
```
Spring::new(duration d, bounce b): ω = 2π / d
ζ = 1 − b (b ≥ 0)
ζ = 1 / (1 + b) (b < 0)
mass 1, stiffness k = ω², damping c = 2ζω
Δ = x0 − T
ζ < 1: ωd = ω√(1−ζ²); x(t) = T + e^{−ζωt} (Δ cos ωd t + (v0 + ζωΔ)/ωd · sin ωd t)
ζ = 1: x(t) = T + (Δ + (v0 + ωΔ) t) e^{−ωt}
ζ > 1: r1,2 = −ω(ζ ∓ √(ζ²−1)); c1 = (v0 − r2Δ)/(r1 − r2), c2 = Δ − c1; x = T + c1 e^{r1 t} + c2 e^{r2 t}
v(t) is the analytic derivative (SpringSolver.swift:168-200).
```
- **Units:** velocity is property units per second (pt/s, opacity/s). It's normalized only when a
CA mirror needs it (the launcher `core.rs:2441-2454`).
- **Settling:** each segment stores `settle_at = t0 + settling_time(x0, v0, T, ε_pos, ε_vel)` using
psychopomp's bound (`motion.rs:75-132`). `ε_pos` comes from the property class and is set *below the
snap quantum*: 1/128 device px for geometry, 1/512 for opacity, 1/64 px for blur. So the final snap
to `T` is invisible. After `settle_at` the track returns exactly `(T, 0)` and is retired.
- **Conversions** at the boundaries: psychopomp's `SpringPlan::visual` multiplies duration by 1.2,
and Motion divides by 1.2 (Kit's motion rules and presets). Rune stores
`(duration, bounce)` and exports ω and ζ.
- **Other curves**, as segment kinds that sample analytically:
- `Decay{k}` (fling, scroll inertia): `x = x0 + v0/k · (1 − e^{−kt})`, `v = v0 e^{−kt}`.
- `Tween{dur, cubic}` (fades, reduced motion): velocity from the curve's slope, as psychopomp's
`Ease` does.
- `Rubber{..}` (overscroll).
- `Bound(live, expr)` (render-thread binding).
- `Fixed`.
### 2.4 Runtime architecture
```
platform main thread render thread (one per display)
┌──────────────────────────────────────────────┐ commits ┌────────────────────────────────────────┐
│ input pump ─┬─ live-binding input ───────────┼────────────▶│ vsync (CAMetalDisplayLink / CVDL / rAF)│
│ └─ app events → handler queue │ (SPSC, │ 1 drain commits with apply_at ≤ T │
│ apply handlers (&mut models, tx) │ lock-free)│ 2 drain forwarded input → Live values │
│ rebuild dirty view scopes → El │ │ 3 step scroll sims & bindings │
│ diff by key → node ops │ │ 4 sample tracks at target time T │
│ incremental layout (target frames) │ │ 5 world xforms → 2-edge snap → masks │
│ layout-animation planner → Animate ops │ │ 6 encode + submit GPU, present at T │
│ text shaping / display lists for changed │◀────────────┤ 7 publish presented snapshot (triple │
│ content only │ events │ buffer); Settled/Exited/Release evts │
│ build Commit{apply_at, ops} │ │ 8 trace frame (if on); sleep if idle │
└──────────────────────────────────────────────┘ └────────────────────────────────────────┘
```
**On the render thread:**
- sampling every track;
- scroll position integration (decay, rubber band, spring-back, paging snap);
- 1:1 drag bindings;
- matched-geometry flights;
- world transforms;
- two-edge snapping;
- soft-mask and blur parameters;
- compositing and encoding of already-recorded display lists and glyph runs;
- presentation timing;
- trace output.
**Not on the render thread:**
- app logic, handlers and view functions;
- diff;
- layout;
- text shaping and line breaking;
- deciding a fling's target (the main thread decides; the render thread bridges, §2.10);
- accessibility tree;
- platform calls.
This matches Core Animation's split: the app builds the model tree, and the server interpolates and
composites.
**Why app logic stays on the platform main thread:** platform interop (text input, accessibility,
menus) is synchronous. Flutter merged its threads for exactly this reason. Animations stay smooth
while the main thread hitches, because the render thread keeps sampling and content updates simply
land a frame late. The input latency of render-thread-owned gestures still depends on the main
thread pumping events quickly. That pump is a tiny forwarder, kept apart from app work by
budgeting: rebuild and layout are time-sliced, and text shaping is async (open question 1).
**Data structures** (render thread):
```rust
#[derive(Copy, Clone)] struct NodeId(u32 /*index*/, u32 /*generation*/);
#[repr(u8)] enum Prop { L, T, R, B, Opacity, Blur, Scale, Rotation, Radius,
FillL, FillA, FillB, FillAlpha, MaskFeather, Custom(u8) }
#[derive(Copy, Clone)]
enum Curve {
Spring { omega: f32, zeta: f32, token: TokenId },
Decay { k: f32 },
Tween { dur: f32, cubic: [f32; 4] },
Rubber { min: f32, max: f32, dim: f32, c: f32 },
Bound { live: LiveId, expr: ExprId }, // tiny pure expression, not a closure
Fixed,
}
#[derive(Copy, Clone)]
struct Segment { t0: f64, x0: f32, v0: f32, target: f32, curve: Curve, settle_at: f64 }
struct Track { seg: Segment, pending: Option<(f64 /*due*/, Segment)>, gen: u32 } // knobs-style delay
struct Animator {
tracks: SlotMap<TrackId, Track>, // ~48 B each (est.)
by_prop: HashMap<(NodeId, Prop), TrackId>,
active: Vec<TrackId>, // compacted on settle; a timer wheel on settle_at if large
}
```
Colour channels animate in OKLab, so a hue change doesn't pass through grey. Rects animate as edges
(§2.7).
**Commit protocol** (main → render, applied atomically at one frame, like `CATransaction`):
```rust
struct Commit { id: u64, apply_at: f64 /* target presentation time */, origin: Origin, ops: Vec<Op> }
enum Op {
Insert { node: NodeId, parent: NodeId, index: u32, props: PropSet, content: ContentId },
Remove { node: NodeId, exit: Option<ExitSpec>, gen: u32 },
Revive { node: NodeId, gen: u32 },
Set { node: NodeId, prop: Prop, value: f32 },
Animate { node: NodeId, prop: Prop, target: f32, curve: Curve,
velocity: Velocity /* Inherit | Override(f32) */, delay: f32 },
Content { node: NodeId, display_list: Arc<DisplayList> },
Bind { node: NodeId, prop: Prop, live: LiveId, expr: ExprId },
Matched { ns: u32, id: u64, incoming: NodeId, mode: MatchMode },
Clip { node: NodeId, shape: RRect, feather: [f32; 4] },
}
```
`apply_at` is the next target presentation time at least one render lead (≈ 2 ms) after the commit
is ready. Every op in a commit starts on the same frame. Kit's rule that the pill width and the word
roll start together holds by construction.
**Per-frame cost when one value animates** (*est.*, M-series):
- main thread: 0;
- render thread: drain plus one closed-form sample (~30 ns), world-transform update for that subtree,
snap, and re-encoding of the scene;
- the scene encode dominates (renderer doc), and 10,000 concurrently animating tracks still sample in
about 0.3 ms.
When nothing is active, no commits are pending and no scroll or binding is live, the display link is
paused: zero idle CPU (Kit's idle rule).
### 2.5 How a property gets an animation (resolution order)
When the diff finds that a node's target for `prop` changed, the runtime decides between `Set` and
`Animate` in this order:
1. **Transaction override.** `tx.instant()` → `Set`. `tx.animate(spring)` or
`tx.prop(Prop::Opacity, curve)` / `tx.axis(Axis::X, spring)` → that curve.
2. **Origin policy.** `Origin::Direct` (typing, dragging, arrow-key selection and other changes made
with the user's own hand) → `Set` unless the transaction opted in. `Origin::Undo | Redo | Remote |
System` → continue to step 3. (Kit rule 5.)
3. **The node's declared default**, `.animate(Prop::Fill, motion::SNAP)`, or the inherited
`.layout_animation(..)` / `.presence(..)`.
4. **Otherwise `Set`.** Nothing animates unless something asked for it.
5. **First mount.** Nodes inserted in a scope's first build (`Mount::Initial`) always `Set` (`initial
= false`, Kit rule 6). Descendants inserted together with an animating parent don't animate on
their own; they ride the parent, which avoids cascades.
6. **Reduced-motion filter** (§2.12) is applied last.
Spring *pairs* (enter/exit tokens) are resolved by direction. Presence exits and `open → closed`
toggles (`child_if`, `.open(bool)`) use `.exit`; everything else uses `.enter`.
### 2.6 Retargeting
```rust
fn retarget(track: &mut Track, at: f64, target: f32, curve: Curve, vel: Velocity) {
let (x, v) = track.seg.sample(at); // exact, analytic
if target == track.seg.target && curve.same_params(&track.seg.curve) && vel.is_inherit() {
return; // psychopomp: unchanged Animate keeps trajectory
}
let v0 = match vel { Velocity::Inherit => v, Velocity::Override(g) => g };
track.seg = Segment::new(at, x, v0, target, curve); // recomputes settle_at
track.gen += 1;
}
```
- **Sample-and-restart, not additive stacking.** Springs are linear ODEs. Restarting from the sampled
`(x, v)` with the same spring gives *exactly* the motion UIKit's additive animations add up to,
while using one segment per property, O(1) evaluation and no growing stack. A different spring on
retarget is also C¹ (position and velocity continue). Only acceleration jumps, which nobody can see.
- `at` is the commit's `apply_at`. Main and render threads agree on it, so a test can predict the
exact frame.
- Changing a token while tracks are live retargets every live track using that token, at the
current frame, to the same target with the new ω and ζ. Live tuning is therefore smooth.
- Reversing mid-flight keeps velocity. There's no snap back to the start (Kit's motion checklist).
### 2.7 Layout animation with the layout engine (FLIP done natively)
Layout (Taffy-like, incremental, with two-edge rounding) runs **once, at the target state**. Then
the planner runs on the main thread:
```
for node in layout.changed_nodes(): // frames in parent space, device-rounded
old = node.prev_target; new = node.target
policy = resolve(tx, node) // §2.5, gives per-axis springs or Set
for axis in [X, Y]:
(e0, e1) = edges(old, axis); (n0, n1) = edges(new, axis)
spring = policy.axis_spring(axis) // "width leads": X faster than Y
if e0 != n0: Animate(node, axis.start_edge, n0, spring, Inherit)
if e1 != n1: Animate(node, axis.end_edge, n1, spring, Inherit)
// an unchanged edge gets no op at all, so it can't jiggle
```
- **Edges, not origin plus size.** Animating `(x, w)` with different springs moves an "anchored"
edge: `x + w` drifts when x and w ride different curves. With edge tracks:
- a stationary edge has no track;
- rigid travel (both edges moving by the same Δ on the same spring with equal velocities) stays
rigid, even across retargets;
- two-edge snapping (§2.13) falls out of this directly.
- **Parent-relative by default.** If a child's parent-relative frame doesn't change, it rides its
parent with no tracks of its own.
- **Straight paths (Kit rule 12).** One transaction gives every layout track the same spring and the
same `t0`. With zero initial velocity, the composed screen path is `start + (end − start)·s(t)` for a
single shape `s`, so it's a straight line. When that can't hold (different springs, or retargets
with mixed velocities) use `.travel(Travel::Screen)`. Then the node's edges are tracked in the
**space of the transaction's common ancestor** and converted to parent space at sample time using
the parent's *presented* transform, which is Motion's projection idea. Matched-geometry flights
always use screen space.
- **Content while a container resizes** is chosen per node with `.resize(..)`:
- `Resize::Shape` (default for surfaces): background, border, shadow, radius and glass are
parametric primitives drawn at the presented rect every frame. That's free, and nothing is
scaled.
- `Resize::Mask{feather}` (default for clipping containers): children are laid out at the target
and revealed by a soft-edged mask that follows the presented rect (OpenCode's `TopAnchoredRow`,
Kit's motion patterns #6; the launcher's "static final-layout render").
- `Resize::Scale`: FLIP scale for media and thumbnails only.
- `Resize::Relayout`: re-runs layout per frame with interpolated constraints on the main thread.
Opt-in only, for text that must reflow. The inspector flags it as main-thread-per-frame.
- **Siblings sliding into gaps** need nothing extra. When the removed row leaves flow (popLayout),
the siblings' targets change, so their edges animate on the transaction's spring (`REFLOW`).
- **Row growth** (streamed text, images loading): a `.growth(Growth::capped(max_speed, max_accel))`
policy implements OpenCode's `RowGrowth`/`GrowthRide` (Kit's motion patterns #5). It caps speed per
frame and cuts immediately on catch-up bursts.
### 2.8 Presence (exits that stay mounted, identity by key)
The main-thread node phase is `Present | Exiting{gen}`.
- **Removal.** When a keyed child disappears from the view output, the node's phase becomes
`Exiting{gen+1}`.
- `Presence::pop()` (the list default) takes it out of layout flow at its last presented rect in
parent space. Siblings reflow.
- `Presence::hold()` keeps it in flow and collapses its slot along the main axis with a mask.
- `Op::Remove{exit: ExitSpec, gen}` sends the exit targets on the exit spring. The defaults are
opacity → 0, blur → 4 px and scale → .96 on `SETTLE.exit` (.24/0, 20% shorter than enter).
- **Unmount.** The render thread sends `Exited{node, gen}` when the node's exit tracks pass
`settle_at`. The main thread drops the node **only if** its phase is still `Exiting{gen}`. So
nothing ever unmounts at opacity > 0. The blur filter stays attached until unmount, so the last
frame doesn't flash sharp (`PresenceGate.swift:76-79`).
- **Revive.** If the same key comes back while it's exiting, the node returns to `Present` with
`gen+1` (the late `Exited` is ignored). Its props retarget back to rest from their current values
and velocities, and it isn't remounted. Identity is preserved.
- **Enter.** An insert after first mount starts at the enter-from props (opacity 0, blur 4, scale .96)
and animates to rest in the same commit. `.enter_from(anchor)` makes an item that was hidden
*behind* another start under the anchor's presented rect and travel a straight path, drawn beneath
it (Kit rule 12).
- **Persistent items never blur.** Blur is only part of enter and exit specs. Nodes that move because
of layout have no blur track. Validation clamps presence scale to ≥ .9 and rejects scale 0.
- **Nesting.** Children of an exiting parent ride the parent's exit and aren't exited on their own.
Opt out with `.exit_independently()`.
### 2.9 Shared-element and matched geometry
- `.matched(ns, id)` — **move.** In one commit, when node A with `(ns, id)` leaves and node B with the
same id arrives, B's edges start at A's *presented screen rect* and velocities, converted to B's
space, and animate to B's layout target. A hides instantly. While in flight, B is drawn in a
**flight layer** at the transaction's common ancestor, so it isn't clipped by a scroll container it
is leaving. Its own soft masks still apply (z-order is an open question).
- `.morph(ns, id)` — **one shape** (Kit rule 9, Liquid Glass `matchedGeometry`, Kit's motion patterns
#9). The *surface* (rect, radius, fill or glass) is a single primitive that interpolates from A's
presented shape to B's. A's content fades out with blur, riding the surface, and B's content fades
in on a short lead. Width leads through the X-axis spring (launcher morph: `width_vd = 0.78·vd`,
`docs/motion.md:47-50`).
- Under reduced motion both become a .15–.2 s crossfade in place (Apple's `.materialize` analogue).
### 2.10 Gestures and velocity handoff
```rust
let offset = cx.live("drawer.y", 0.0); // Live<f32>: render-thread owned, keyed
drawer()
.translate_y(offset) // Bind op: no view re-run while dragging
.draggable(Axis::Y, offset, Bounds::new(0.0, 640.0).rubber_band())
.on_release(ui, move |u, fling, tx| { // main thread decides the target
let land = fling.projected_y(Decel::IOS_NORMAL); // x + v/1000 · r/(1−r)
u.drawer_open = land < 320.0;
tx.animate_live(offset, if u.drawer_open { 0.0 } else { 640.0 }, motion::GLIDE)
.velocity(Velocity::Inherit); // keep the live velocity
})
```
- **During the drag** (render thread): pointer deltas apply 1:1 to the `Live` value. That's the
user's hand, so there's no spring (Kit rule 5). The only exception is an opt-in `follow` spring
(palette: ω 34, ζ .86 lead).
- **Velocity estimation** uses platform event timestamps (not arrival time) and coalesced touches.
- The default is least squares over the last 100 ms and 20 samples, treating 40 ms of silence as
stopped (Flutter `velocity_tracker.dart:142-144`).
- On iOS, scroll flings use UIScrollView-like weights over the last three deltas, 0.6/0.35/0.05
(`velocity_tracker.dart:295-369`).
- On macOS: 0.15/0.65/0.2 (`velocity_tracker.dart:416-439`, fetched from flutter `master`).
- **The release bridge.** The main thread's decision arrives one or two frames late. So on release
the render thread immediately continues the `Live` value as a `Decay{k}` with the release velocity.
When the main thread's `Animate{velocity: Inherit}` lands, it retargets from the decay's exact
`(x, v)`. The result is C¹ with no stall at release, which is the problem UIKit solves by running
everything on the main thread.
- **Projection.** Use `fling.projected(rate)` with the iOS formula from
[WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/), so the
target snap point respects the user's momentum.
### 2.11 Scroll physics per platform
A `ScrollPhysics` trait produces segment kinds for the render thread. Scroll offset is a `Live` value
the render thread owns, and the main thread gets offset snapshots for virtualization and
non-blocking `on_scroll` events.
| Platform | Inertia | Overscroll | Notes |
| --- | --- | --- | --- |
| iOS | `v(t) = v0 · r^(t_ms)`, r = 0.998 normal / 0.99 fast ([UIScrollView.DecelerationRate](https://developer.apple.com/documentation/uikit/uiscrollview/decelerationrate-swift.struct)); as `Decay{k}` with k = −1000·ln r ≈ 2.002 s⁻¹; Flutter uses the same constant, `0.998^1000 ≈ 0.135` (`scroll_simulation.dart:50-56`) | Rubber band `f(x) = (1 − 1/(x·c/d + 1))·d`, c = 0.55, d = viewport dimension ([Grant Paul, 2012](https://twitter.com/chpwn/status/285540192096497664), older but still the reference); release out of range → spring back, ζ ≈ 1 (Flutter default ≈ mass .5, k 100, ζ 1.1, `scroll_physics.dart:434-438`) | Hand off to the spring at the edge with friction velocity capped at 5000 pt/s (Flutter `maxSpringTransferVelocity`, `scroll_simulation.dart:79-81`). Paging = projected target snapped to a page, spring with inherited velocity. |
| macOS | **The OS generates momentum.** Trackpad `NSEvent`s carry `phase` and `momentumPhase` with system-computed deltas, which must be applied 1:1, not re-simulated | While the gesture or momentum pushes past the edge, apply the elastic formula to the deltas; spring back when the momentum phase ends | Mouse wheel (non-precise) deltas: animate line steps on `instant` (.1/0). Never double-apply inertia. |
| Android | Spline fling (`SplineOverScroller`): decel rate ln(.78)/ln(.9), inflexion .35, physical coefficient ≈ 9.8·39.37·ppi·0.84 (Flutter port `scroll_simulation.dart:201-259`) | Android 12+ **stretch** `EdgeEffect` (scale toward the edge), not glow | Velocity in px/s against ppi. |
| Windows | DirectManipulation supplies inertia for precision touchpads | Clamp or optional bounce | Wheel = discrete steps on `instant`. |
| Web | Wheel deltas on macOS *already include* OS momentum; touch is browser-native | Emulate per the host OS (UA-detected) | When possible, back the scroll container with a native scroller and read its offset. |
Every scroll viewport gets soft edge masks: 24 pt by default on edges where content overflows. The
mask strength is `min(1, overflow/feather)`, so it ramps in instead of popping (Kit rule 11). The
mask is attached to the viewport, not the content (Kit's "edge travel" rule). Scrolling runs on the
render thread, so checkerboarding is possible. The mitigations are an overscan sized to the current
scroll velocity and a placeholder skeleton (hard problem 3).
### 2.12 Reduced motion
The runtime applies it per property class, so authors can't forget it:
| Class | Under Reduce Motion |
| --- | --- |
| Spatial (edges, translate, scale, rotation, layout animation, matched flights, programmatic scroll) | `Set` (no travel) |
| Opacity, presence enter/exit | Opacity-only `Tween` of .15–.2 s (token `motion::REDUCED_FADE`; OpenCode `reducedFade` .20, `MotionConstants.swift:33-37`; the launcher 75 ms, `docs/motion.md:78`) |
| Blur | 0 (and the filter is never attached) |
| Morph | Crossfade in place |
| User's hand (drag, fling inertia, trackpad momentum) | Unchanged: it's the user's own motion |
| Continuous loops (shimmers, orbs) | Hold a calm static pose that still shows state |
The source is the OS setting (`accessibilityReduceMotion`, `prefers-reduced-motion`, Android
animator scale). Tests can override it: `TestApp::reduce_motion(true)`.
### 2.13 Two-edge 1/64 px snapping
This runs as the last step on the render thread, in device pixels. For axis-aligned world transforms,
`x0 = grid(left)` and `x1 = grid(right)`, and width is *derived* as `x1 − x0`, where
`grid(v) = round(v·64)/64` (Kit's motion patterns #3; Signal desk v3 `autocomplete.js`). With
rotation or non-uniform scale, only the translation is snapped.
At rest, layout has already rounded both edges to device pixels using the same cumulative two-edge
pattern Taffy uses (`taffy/src/compute/mod.rs:381-393`: `size = round(cum + w) − round(cum)`). So the
moving 1/64 grid and the resting pixel grid agree, and a node lands with no final shift. Settle
thresholds sit below the quantum (§2.3).
### 2.14 Soft-edge masks everywhere
- **The clip primitive** is `Clip{shape: RRect, feather: [l, t, r, b]}`, evaluated as an SDF ramp in
the composite shader. It costs a few ALU ops per pixel. Nested clips multiply.
- **Defaults:**
- scroll viewports: 24 pt on overflowing edges, ramped (§2.11);
- text overflow: a 1.5 em right-edge fade, never an ellipsis;
- panels and cards clipping children: a 16 pt inner fade on the clipping side;
- rounded corners: an anti-aliased SDF, so no stair-steps.
- **Hard clips** need an explicit `.clip_hard(reason)`. The inspector and the trace (`flags.clipped`
plus the `vis` rect) let the internal motion linter flag unmasked cuts. Every clipping ancestor and axis is
checked, matching the skill's audit rule.
- **Group isolation.** When a masked subtree has overlapping translucent children, it's rendered to
an offscreen layer, which the renderer can do automatically (renderer doc).
### 2.15 Blur and scale for enter and exit
- **Defaults:**
- whole-element replacement in place: 3–4 px blur, scale ≈ .96, plus opacity;
- exits run 10–25% shorter;
- persistent and sliding content stays sharp.
- **Blur cost.** Blur is a filter on an offscreen layer (dual-Kawase at reduced resolution, radius
≤ 8 px). It's attached when a blur track becomes non-zero and detached when it *settles* at 0.
On exit it stays until unmount. Resting UI pays no blur cost (the launcher removes `CAFilter`s at rest,
`docs/motion.md:43`; `PresenceGate.swift:92-97`).
### 2.16 One clock, time scaling and deterministic stepping
```rust
enum ClockSource { Display, Manual { hz: f64 } }
struct Clock { anchor_host: f64, base: f64, scale: f64 } // τ = base + (host − anchor)·scale
impl Clock {
fn set_scale(&mut self, s: f64, host_now: f64) { // re-anchor (scrawl motion.rs:42-53)
self.base += (host_now - self.anchor_host) * self.scale;
self.anchor_host = host_now;
self.scale = s.clamp(0.02, 4.0);
}
}
```
- **Every** consumer reads τ: tracks, scroll simulations, presence timing, trace `t` and `sc`. Slow
motion is truthful only when every clock scales together (Kit's motion patterns #12). If a CA mirror
is used, its `layer.speed` and `timeOffset` get re-anchored in the same step.
- Frames are sampled at the display link's **target presentation timestamp**
(`CAMetalDisplayLink`/`CADisplayLink.targetTimestamp`; `MotionDisplayLink.swift:62-68`). Tracks
sample absolute time, so a hitch lands motion where it should be, which is CA's behaviour.
Eye-tracked flights can opt into a dt clamp (Kit's motion patterns #1).
- `Manual{hz}`: `app.advance(ms(500))` steps exact frames, `app.settle()` runs until there are no
active tracks, and `app.frame()` steps one frame.
### 2.17 motion traces
Turn it on with `RUNE_MOTION_TRACE=<file>`, mirroring `SCRAWL_MOTION_TRACE`
(`scrawl/src/ui/motion.rs:551-561`). When it's off it costs one `OnceLock` read. In tests,
`app.record(..)` returns the trace in memory. The render thread writes after step 5, so the trace
records **exactly what was presented**: post-snap and post-mask.
```jsonc
{"type":"header","launch":"mail","width":1512,"height":982,"hz":120,"scale":2,
"platform":"rune-macos","units":"pt","clock":"virtual"}
{"t":1234.567,"n":1,"sc":1,
"ev":["tx#41 Direct tap thread:7 SNAP","retarget thread:3.T REFLOW v=-212.4"],
"ai":[[12,16,112,358,56,2,400]], // intent: [id,x,y,w,h,bits,ms] from Animate ops
"m":[{"id":12,"cls":"row","nm":"thread:3","host":"list:inbox","pv":4}],
"e":[[12,16,140.25,358,56,1,8,258]], // [id,x,y,w,h,alpha,radius,flags,(vis x,y,w,h)]
"g":[9], // unmounted (only after its exit settled)
"cm":[{"id":1,"name":"scroll:inbox","kind":"position"}],"c":[[1,840.5]]}
```
- **Flags** use the motion linter's bits (`analyze.ts:41-43`): animated 1, ancestorAnimated 2, scrolling 4,
clipped 8, filtered 16, occluded 32. Intent classes are packed at `<<8` (own) and `<<16`
(ancestor): position 1, size 2, opacity 4, shape 8, transition 16, reveal 32, contents 64.
Rune sets them from the actual track kinds, so the motion linter's "was this intended?" logic gets the
truth instead of a guess.
- **Events** carry the commit id, origin, token name and retarget velocities. Channels carry scroll
offsets and, optionally, per-track progress.
- **Scrubbing.** The runtime can also emit a *sweep*: sample a recorded commit sequence at any τ
without running the app. Tracks are pure, which gives the motion linter's `sweepClock` the same power
natively.
- **In-process invariants in debug builds.** "Unmount at opacity > 0" is impossible by construction.
Warnings fire for a visible `Set` of a spatial prop whose origin isn't Direct (a likely pop), a
`.clip_hard` without a reason, and blur on a persistent node.
### 2.18 Live tuning and tokens
- `motion::*` constants are *token ids* whose defaults are generated from Kit's motion presets
(generated Rust today). The render thread resolves tokens through a `TokenTable`.
- Debug builds watch `~/.config/<app>/tune.json` (Scrawl's loop, `motion.rs:316-360`) and accept a
knobs remote over WebSocket. A change retargets live tracks (§2.6).
- `rune tune rust` prints the paste-back for the token defaults (`scrawl tune rust`,
`motion.rs:442-455`).
- The trace logs token names, so a clip can be matched to the knob that produced it.
### 2.19 Public animation API (a summary)
```rust
// springs
Spring::new(0.30, 0.0) // duration, bounce
SpringPair { enter: Spring::new(0.30, 0.16), exit: Spring::new(0.27, 0.08) } // motion::MORPH
// transactions (inside handlers)
tx.animate(motion::MORPH).axis(Axis::X, motion::SNAP) // width leads
.prop(Prop::Opacity, Curve::fade(0.16)).delay(Prop::Opacity, 0.012);
tx.instant();
tx.animate_live(live, target, spring).velocity(Velocity::Override(v));
// node modifiers
.animate(Prop::Fill, motion::SNAP)
.layout_animation(motion::REFLOW)
.presence(Presence::pop().enter(Fx::fade().blur(4.0).scale(0.96)).exit(Fx::fade().blur(4.0).scale(0.96)))
.enter_from(key!("pile-top"))
.matched(ns, id) / .morph(ns, id)
.travel(Travel::Screen)
.resize(Resize::Mask { feather: 28.0 })
.transitions(phase, |t| t.on(Phase::Recording, Phase::Picker, motion::MORPH)) // Rive-style table
.clip_soft([0.0, 24.0, 0.0, 24.0]) / .clip_hard("video surface owns its edges")
// live values
let v: Live<f32> = cx.live("drawer.y", 0.0);
node.translate_y(v).opacity(v.map(Expr::remap(0.0, 640.0, 1.0, 0.4)));
cx.presented(key!("thread", 3)) -> Option<PresentedRect> // untracked snapshot
```
---
## Steal
- SwiftUI: transaction-scoped animation, merging springs, `Spring(duration:bounce:)`.
- Core Animation: an off-main render thread, model/presentation split, atomic commits.
- Compose: `animateTo(.., initialVelocity = velocity)` and phase separation.
- Motion: `popLayout`, `layoutId`, projection to keep paths straight.
- Flutter: the `Simulation` trait, scroll physics constants and velocity trackers.
- Rive: a transition table keyed by (from, to) phases.
- psychopomp: pure piecewise tracks, `settling_time`, transactional retargets.
- The private iOS client: `PresenceGate` generations, blur gating, one display link through `AnimationTimeScale`.
- Scrawl: the clock, live tuning and the trace writer.
- The launcher: final-layout-once plus animated geometry, and per-axis "width leads" springs.
- Xilem: handlers that receive `&mut State`.
- GPUI: `Model` entities as the hot-reload unit, and the `list` sum tree.
- Taffy: two-edge cumulative rounding.
## Avoid
- Animations evaluated on the main thread (GPUI's `request_animation_frame → notify`, Flutter, egui).
- Velocity you can't read back (CA `presentationLayer` heuristics).
- Numeric integrators that can't be sampled at an arbitrary *t* (knobs' 480 Hz Euler).
- Run-once components whose state lives in closures (signals) when hot reload matters.
- Hook-order or call-site identity.
- Deep generic view types (compile times, error messages).
- Scale-based FLIP for anything with text.
- Snapping a critically damped spring to its target when it crosses, which creates a velocity cliff.
- Manual `notify()`.
- `Task.sleep`-style unmount timers.
- Hard clips and ellipses.
## Recommendation
**Rune uses:**
- a **keyed retained tree built from pure view functions over `Model<T>` stores**, with model-level
auto-tracking and queued `&mut` handlers;
- a **type-erased `El`** for compile speed;
- explicit string keys for local state;
- an **animation runtime on a dedicated render thread per display**: piecewise analytic tracks per
property, transactional commits with presentation-time `apply_at`, sample-and-restart retargeting,
edge-based layout animation, generation-guarded presence, render-thread scroll and drag bindings
with a decay bridge on release, runtime-enforced reduced motion, two-edge snapping, soft masks by
default, one scalable or manual clock, and native motion traces.
**Rejected alternatives:**
| Alternative | Why not |
| --- | --- |
| Fine-grained signals as the primary model | Their main advantage (a cheap per-frame update) is already delivered by render-thread tracks. They lose on hot reload and have silent stale-read footguns. Kept as a narrow tool: `Live<f32>` is effectively a render-thread signal. |
| GPUI's entity plus re-render per frame | Per-frame cost scales with view complexity; manual notify; runtime double-borrow panics. |
| Immediate mode | CPU every frame, nothing offloaded, and presence or layout animation would rebuild a retained tree anyway. |
| Core Animation as the engine | No velocity readback, Apple-only, no determinism, no custom shaders for soft masks or glass inside CA's content model. Keep it only as an optional mirror for system materials (`NSGlassEffectView`, `CABackdropLayer`). |
| Additive animation stacks | Equivalent for linear springs, but more state and harder to trace. |
| Running app logic off the main thread by default | Conflicts with synchronous platform APIs (Flutter's thread merge). Revisit if input latency measurements demand it. |
## Hard problems
1. **Straight paths with nested, independently timed animations.** Parent and child on different
springs, or retargeted with mixed velocities, compose into curves. `Travel::Screen` fixes
individual nodes, but choosing the coordinate root automatically, and reparenting mid-flight, is
subtle (Motion's projection tree is roughly 2k lines for a reason).
2. **Content during resize.** Mask vs shape vs scale vs per-frame relayout. Text that must reflow
during a size animation forces main-thread work every frame, so it needs a budget and a lint.
3. **Main/render consistency.**
- Hit-testing must use *presented* geometry: a tap on a moving row should hit what you see.
- Virtualization runs behind render-thread scrolling (checkerboarding on fast flings, sizing
overscan to velocity).
- Commit latency is one frame plus input-to-photon.
4. **Presence edge cases.**
- Exits inside an exiting parent.
- The z-order of exiting nodes versus new arrivals.
- Exits inside a scroll container that is itself scrolling.
- A key that moves to a different parent (a reparent: it should travel, not exit and enter).
5. **Matched geometry across clip and scroll ancestors.** Should the flight layer escape clipping
(Flutter Hero) or stay under the chrome it's passing beneath (Kit's "emerge from behind")? This is
probably per transition, which needs a z-policy API.
6. **macOS scrolling.** Mixing OS-provided momentum with Rune's rubber band, spring-back and
render-thread offset, plus the rule that web wheel deltas must never get inertia twice.
7. **Determinism.** Cross-platform float math (deterministic `libm`), the order of commit
application against forwarded input in tests, and time-scaling CA mirrors in lockstep.
8. **System materials (Liquid Glass) in lockstep with Rune's Metal layer.** Either mirror tracks
into `CASpringAnimation`s evaluated with identical math (the launcher `eval_ca_spring_spec_at`), or drive
CA every frame from the render thread with actions disabled (Scrawl's fixed `NSPanel` plus single
`CATransaction`). Both have a one-frame-skew risk.
9. **Blur and mask cost at scale.** Offscreen passes per blurred or isolated group, and many
simultaneous exits in a big list (cap concurrent blurred layers; degrade to opacity-only past N).
10. **Overshoot from velocity at bounce 0.** A fast fling into a critically damped spring physically
overshoots. Is that "bounce"? Scrawl clamps, which causes a velocity cliff. My default is to allow
the physics; an opt-in `no_overshoot` would clamp *velocity*, not position.
11. **Hot reload while animations are in flight**, when node identity changes shape (a key type
changes, a list becomes a grid): decide between exit/enter and a best-effort matched transfer.
12. **Streaming text** (line-hold, growth caps) belongs half in layout and half here. The interface
between text layout and the growth policy needs design together with the text doc.
## Open questions
1. App logic on the platform main thread (the default) vs a separate app thread with a thin
main-thread forwarder. Measure input-to-photon for render-thread drags under a deliberately busy
main thread before deciding.
2. Field-level read tracking (`@Observable`-style derive) in v1, or model-level only?
3. Does the renderer re-encode the whole scene every frame (Vello-style) or cache layer textures?
This sets the render-thread budget. Coordinate with the renderer doc.
4. Port the motion linter's core rules to Rust for in-process `trace.assert_clean()`, or shell out to the
TS CLI?
5. The default list presence: `pop` (siblings close the gap immediately, while the exit plays) or
`hold` (the gap closes as the exit plays)? Kit's "siblings slide into the gap" works with both.
Needs a blind A/B.
6. Confirm the semantic token names (`snap`, `settle`, `reflow`, `glide`, `morph`, `pop`, `drift`)
proposed in Kit's motion presets. Kit's motion rules still treats the old palette as the reference.
7. Should `Origin::Direct` include keyboard selection moves? The skill says keys apply 1:1, but a
selection *highlight* gliding on `SNAP` is often wanted. Probably the highlight animates and the
content doesn't.
+358
View File
@@ -0,0 +1,358 @@
# Hot reload: keep the native host, reload the view and small handlers
Research date: 2026-10-21. This report supports the choice of Rune's reload architecture. It is source research, not a completed benchmark; the practical spike is separate.
## Summary
- Aim for under 300 ms from saved edit to presented frame for tokens, view structure, and small interpreted handlers on both Mac and a connected iPhone. Keep rendering, text, layout, animation evaluation, and durable app state native.
- Use one reloadable view representation on both platforms. A small declarative language or restricted expression interpreter avoids native compilation and executable-memory changes for the edits designers make most often.
- Add Subsecond for Mac and simulator Rust implementation edits. Its current source explicitly excludes physical iOS devices. Its documentation also understates current workspace support, so use the inspected implementation rather than the introductory limitations alone.
- Native function replacement does not migrate Rust state. Struct layout, closures, futures, trait-object vtables, thread-local storage, and destructor ownership all need an explicit compatibility boundary.
- Flutter demonstrates that device hot reload and JIT remain possible with debugger cooperation. Current Dart/Flutter code contains special executable-page handling and version-specific LLDB workarounds. Attaching a debugger once is not a general solution for a Rust dylib loader.
- InjectionNext advertises device support, but a detailed July 2026 iPhone failure and an October maintainer response leave modern device loading unresolved. HotReloadKit deliberately supports only Mac and simulator. Neither establishes a dependable physical-iPhone Rust patch path.
- wasm3, WAMR's interpreter, and wasmi can execute replacement logic without native JIT. They still incur module loading, interpretation, and, for Rust guests, Rust compilation. A current iPhone benchmark supports keeping expensive UI work outside the interpreter.
- Build state preservation around explicit node/state IDs and schemas. Preserve compatible state; migrate declared changes; reset only incompatible subtrees; restart with a snapshot for native-core changes. Apply each generation atomically and acknowledge its first presented frame.
- No source reviewed establishes a general sub-300 ms native-Rust or physical-device edit-to-pixels guarantee. The budgets below are proposed engineering targets, not measurements.
## 1. Measure the whole edit-to-frame path
For a save-triggered reload, measure:
```text
file save → detection/batching → parse or compile → link/package
→ device transfer → validate/load → commit generation
→ reconcile/layout → GPU work → presented frame
```
An application receipt after `dlopen`, or a CLI message after compilation, stops too early. Record generation IDs at every stage. For interactive controls, use the input event rather than a file save as the start. At 120 Hz a frame interval is 8.33 ms; at 60 Hz it is 16.67 ms. Compilation can happen in the background, but final application must also fit the active frame workload.
### What the available numbers actually establish
| System | Number | Evidence class and limitation |
|---|---|---|
| Subsecond/ThinLink | Incremental build below 500 ms | Author claim in [runtime docs, lines 168–183](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/subsecond/subsecond/src/lib.rs#L168-L183). No device-to-presented-frame distribution. |
| Subsecond symbol cache | Docsite patch time reduced from 3 s to 1.1 s | Author-reported measurement in [source comment, lines 63–68](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/cli/src/build/patch.rs#L63-L68). Hardware and sampling unspecified. Shows real workloads can exceed 300 ms. |
| HotReloadKit | Roughly 100–300 ms for safe edits | [README](https://github.com/kitlangton/hot-reload-kit/blob/410708f0a204618d7ef3afc923f3e5790bcc80d6/README.md) claim, not a published latency dataset. Runtime receipt follows invalidation, not confirmed display. |
| Flutter | Example log says 978 ms | [Official hot-reload guide](https://docs.flutter.dev/tools/hot-reload). Illustrative output, not a benchmark or SLA. |
| React Native Fast Refresh | “Within a second or two” | [Official guide](https://reactnative.dev/docs/fast-refresh), qualitative product expectation rather than a sub-300 ms result. |
| `hot-lib-reloader` | 500 ms default debounce; suggests 20–50 ms | [README](https://github.com/rksm/hot-lib-reloader-rs/blob/master/README.md). Configured waiting time, before compilation/loading/rendering costs. |
| Slint live preview | 50 ms rebuild debounce | [Implementation](https://github.com/slint-ui/slint/blob/6a6fe8c874809d8c35a656809ccb33582276989d/internal/live-preview/lib.rs). Its separate macOS 200 ms [watcher rescan delay](https://github.com/slint-ui/slint/blob/6a6fe8c874809d8c35a656809ccb33582276989d/internal/live-preview/file_watcher.rs#L98-L108) repairs missed events after watch changes; it is not a universal 200 ms edit delay. |
| Makepad current scripting reload | No trustworthy end-to-end number found | Source establishes a no-Rust-compile path for script edits, not a measured latency. |
The Subsecond CLI's completion log also precedes a rendered-frame acknowledgement ([builder source](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/cli/src/build/builder.rs#L883-L895)). Do not compare these figures as if they all measured the same endpoint.
## 2. Subsecond removes much linking work, but leaves Rust compatibility to Rune
Inspected Dioxus revision: `7a817390a69294f614b3055aae2dacdf25c050a2` (2026-10-17). Published Subsecond documentation currently exposes version 0.7.10; the implementation findings here refer to the pinned repository revision.
### ThinLink reuses the running program's symbols
The baseline build records compiler/linker arguments and symbol information. For a patch, the CLI recompiles changed workspace crates and the tip crate, then links fresh code against symbols already resident in the running process. It generates assembly stubs for otherwise undefined symbols, using an address supplied by the running application to account for address-space randomization. The patch therefore avoids relinking unchanged dependency archives into a whole new application.
The runtime loads the patch image, adjusts the address map, retains the image, and publishes a new jump table. Calls through `subsecond::call`/`HotFn` reach updated implementations. Framework integration still decides when to invalidate/rebuild views and how to handle retained state. See [workspace/link flow](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/cli/src/build/link.rs#L135-L265), [symbol mapping](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/cli/src/build/patch.rs#L424-L463), and [runtime loading](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/subsecond/subsecond/src/lib.rs#L498-L546).
Two documentation discrepancies matter:
1. **Workspace support exists in the inspected implementation.** The runtime's introductory docs still say only the tip crate patches. `compile_workspace_hotpatch` now replays changed workspace crates in dependency order and links their updated rlibs. The old [workspace issue #4160](https://github.com/DioxusLabs/dioxus/issues/4160) was closed through #5291 in February 2026. This does not prove every workspace configuration works, but “main.rs only” is stale guidance.
2. **Do not assume exact function-body diffing.** ThinLink's docs advertise object-file diffing. The inspected path collects fresh `.rcgu.o` files plus updated workspace rlibs, and the patch map matches same-name symbols. That is not evidence that only bytewise-changed function bodies enter each patch. Measure patch size and invalidation scope rather than assuming ideal granularity.
### Unchanged state is only safe when its representation remains compatible
The [runtime's own limitations](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/subsecond/subsecond/src/lib.rs#L77-L122) include:
- Struct size/alignment/layout changes need framework-managed re-instancing. Calling new code on an old layout can crash.
- Tracked globals persist, renamed globals are new, and changed initializers are ignored. Newly introduced globals do not have their destructors run.
- Patched-crate thread-locals reset. Current [TLS patch handling](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/cli/src/build/patch.rs#L1192-L1234) still makes per-patch copies; initializer fixes do not make them persistent host state.
- Function pointer identity is not a reliable fine-grained change detector across generations.
`subsecond::call` provides a reload/unwind boundary, not a proof that arbitrary existing Rust values match new code. The inspected `try_call` path casts callable pointers; it does not provide comprehensive schema/layout validation. A changed async function also changes its compiler-generated future type. Existing futures, captured closures, and trait objects can retain old implementation pointers even if a top-level function was replaced.
**Rune use:** keep the scheduler, runtime/Tokio ownership, state store, GPU objects, and thread-locals in the stable host. Patch small view-builder/reducer entry points. Reject incompatible schemas before invoking replacement code. Use generation-scoped tasks and callbacks, with quiescence or cancellation at reload. Keep old images resident until safe reclamation is demonstrable; bound memory with a snapshot/restart policy.
### Platform labels need qualification
The source lists macOS, Linux, Windows, Android, wasm32, and iOS arm64, then explicitly says **physical iOS devices are unsupported due to code signing; use the simulator** ([lines 193–208](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/subsecond/subsecond/src/lib.rs#L193-L208)). This is project-declared support, not a matrix independently tested here. For Rune, count Mac/simulator native patching as available to investigate and physical iPhone native patching as unavailable through stock Subsecond.
## 3. A stable-ABI dylib is simpler to reason about, but has the same device barrier
[`hot-lib-reloader`](https://github.com/rksm/hot-lib-reloader-rs) watches a dynamic library, uses unique shadow copies to avoid loader caching/locking problems, loads exported symbols through `libloading`, and coordinates replacement. It does not eliminate Cargo/rustc compilation. Its examples using `#[unsafe(no_mangle)]` do not automatically establish a stable C ABI; unmangled names and ABI stability are different properties.
Its [documented limitations](https://github.com/rksm/hot-lib-reloader-rs/blob/master/README.md#know-the-limitations) cover signature/layout mismatches, generic exports, globals, and changing `TypeId`s. The README also describes a tracing-callsite crash, illustrating how third-party global registries can retain references into unloaded images.
For a Rune-owned boundary, use an explicit `extern "C"` entry point returning a versioned `#[repr(C)]` function table. Pass opaque host handles, fixed-width scalars, or explicitly owned byte buffers. Keep allocation/freeing paired with the owning side. Do not pass `Vec`, `String`, Rust trait objects, references with hidden lifetimes, or panics across the boundary. Validate ABI version and schema fingerprints before installation.
Host-owned state can survive every library generation. Library-owned state needs a serialization/migration call into the old generation before retiring it. Every registered callback/task must either retain its owning generation or be unregistered and drained before unload. A C ABI does not solve those lifetime problems by itself.
**Tradeoff:** this is a useful Mac fallback if Subsecond integration proves too coupled to Dioxus tooling. It requires more explicit API design and still cannot load arbitrary downloaded native code on ordinary physical iOS. Reject it as the shared Mac/iPhone reload foundation.
## 4. Makepad and Slint demonstrate a more portable view boundary
### Makepad reparses scripts and reapplies them to a live native app
Inspected Makepad revision: `44ecb822b48106fa76bde4dfd309e5a8a7ff1932`. Current Splash documentation uses `script_mod!`; older `live_design!` descriptions refer to the archived system ([current scripting guide](https://github.com/makepad/makepad/blob/44ecb822b48106fa76bde4dfd309e5a8a7ff1932/docs/agents/splash.md)).
The reload path receives changed file contents, extracts script blocks from Rust source, matches them to compiled sites, checks block counts and embedded Rust `#(...)` placeholder counts, then tokenizes/parses the replacement scripts. It stages a new override map and publishes it only after validation of the batch. See [live_reload.rs, lines 186–366](https://github.com/makepad/makepad/blob/44ecb822b48106fa76bde4dfd309e5a8a7ff1932/platform/src/live_reload.rs#L186-L366).
The app then reapplies scripts to the existing application through `ScriptApply` ([app_main.rs](https://github.com/makepad/makepad/blob/44ecb822b48106fa76bde4dfd309e5a8a7ff1932/platform/src/app_main.rs#L326-L350)). `StudioToApp::LiveChange { file_name, content }` supplies a transport-shaped entry point ([cx_shared.rs](https://github.com/makepad/makepad/blob/44ecb822b48106fa76bde4dfd309e5a8a7ff1932/platform/src/os/cx_shared.rs)). This is a concrete design for sending source as data rather than loading a new native library.
Preservation follows the existing object's apply behavior; it is not universal migration of arbitrary Rust fields. Native Rust code and changed embedded Rust values still require compilation. Shader cache invalidation is a separate concern from applying style properties. Source inspection establishes these mechanisms, but does not establish current end-to-end iPhone transport reliability or a latency distribution.
**Steal:** a live language embedded near native code, stable binding sites, preflight validation, batched application, and native hot paths. Prefer explicit IDs over line/column-derived identity where source movement should preserve state.
### Slint reconstructs a component and restores explicitly retained values
Inspected Slint revision: `6a6fe8c874809d8c35a656809ccb33582276989d`. The live-preview implementation watches `.slint` dependencies and resources, compiles on a worker using the interpreter, and retains the last working component on compilation failure. On success it creates a new component using the existing window ([live_component.rs, lines 118–145](https://github.com/slint-ui/slint/blob/6a6fe8c874809d8c35a656809ccb33582276989d/internal/live-preview/live_component.rs#L118-L145)).
It restores the properties and callbacks held in its explicit registration maps ([lines 174–199](https://github.com/slint-ui/slint/blob/6a6fe8c874809d8c35a656809ccb33582276989d/internal/live-preview/live_component.rs#L174-L199)). That is narrower than preserving every current internal widget value, focus target, scroll offset, or running animation. Values changed only inside the old instance are not automatically all represented by those maps.
**Steal:** worker compilation, diagnostics, an existing-window handoff, and last-good retention. **Improve for Rune:** define persistent state separately from the generated view tree, so state survival does not depend on incidental property registration. The inspected preview facility is not proof of a turnkey physical-iPhone live-preview product; Rune would supply the device host and transport.
## 5. Flutter and React preserve state because their runtimes know its identity
### Flutter controls both executable code and object metadata
Flutter's debug hot reload sends changed Dart program material to the VM, updates code, and rebuilds the widget tree while preserving compatible state. `main()` and `initState()` do not rerun; static/global initialization is generally retained. Native Swift/Objective-C/Kotlin/Java changes require a restart/rebuild. Enum/class changes and changes to generic type parameter counts are among documented reload restrictions ([official guide](https://docs.flutter.dev/tools/hot-reload)).
The [Dart VM reload design](https://dart.googlesource.com/sdk/+/42ec219908a0ce38b0f16593302f96cad6f38e9b/docs/Hot-reload.md) explains replacement of method dictionaries, retention of existing field values, and invalidation of inline caches and optimized assumptions. This works because the VM owns object metadata and code dispatch. Rust's unmanaged existing allocations do not come with that capability.
Flutter supports physical and virtual targets in debug mode. Its device JIT/debugger machinery is substantial, as detailed below. The reusable idea is the division between persistent state and replaceable behavior, not the assumption that a native Rust function patch inherits Dart's migration semantics.
### React Fast Refresh uses component families and hook signatures
The [refresh runtime](https://github.com/facebook/react/blob/main/packages/react-refresh/src/ReactFreshRuntime.js) associates old/new component implementations with stable families. It compares component kinds and hook signatures, including custom-hook dependencies, then separates families that can update from families that must remount.
Function-component hook state can survive compatible edits; class component state is not preserved. Changed hook structure can force a reset. Effects, memoized values, and callbacks refresh even with otherwise unchanged dependency arrays, and module export shape affects how far refresh propagates ([React Native guide](https://reactnative.dev/docs/fast-refresh)).
**Rune lesson:** give every reloadable component a stable family ID and a state-schema signature. Distinguish “recompute this view” from “recreate this state.” Rerun subscriptions with cleanup rules instead of preserving stale closure pointers. React's “second or two” wording is not evidence for the target latency.
## 6. Swift tooling is useful precedent, with a sharp simulator/device split
### HotReloadKit has a narrow compatibility planner worth copying
Inspected revision: `410708f0a204618d7ef3afc923f3e5790bcc80d6`, plus local `README.md` and `docs/architecture.md`.
HotReloadKit parses baseline and edited Swift with SwiftSyntax, replaces allowed function/computed-property bodies with empty bodies, and compares the remaining structure. Compatible edits produce `@_dynamicReplacement` thunks with source-scoped private imports. It compiles those thunks with `swiftc -emit-object`, links a Mach-O bundle against the baseline executable using `clang -bundle -bundle_loader`, publishes an atomic manifest, loads the bundle with `dlopen`, invalidates affected observers, and writes a receipt ([architecture](https://github.com/kitlangton/hot-reload-kit/blob/410708f0a204618d7ef3afc923f3e5790bcc80d6/docs/architecture.md)).
Stored-property, signature, and new-type changes fall back to rebuilding. Opaque return types need additional restrictions; TCA reducer edits are constrained to suitable closure bodies. SwiftUI state survives when the existing identity remains. Recreating a subtree through `.rebuildsOnHotReload()` resets its local state, focus, and scroll, while externally owned models survive ([README](https://github.com/kitlangton/hot-reload-kit/blob/410708f0a204618d7ef3afc923f3e5790bcc80d6/README.md)).
The runtime is intentionally inert on physical devices and in release builds. Its filesystem manifest depends on the shared host/simulator filesystem; adding a socket would solve transport, but not native device loading. Loaded Swift images remain resident; the documented 50-generation restart policy bounds accumulation. Its claimed 100–300 ms is promising for a narrow edit class, not a measured device guarantee.
### Modern SwiftUI previews are not simply third-party dynamic replacement
Apple's current [build-product layout documentation](https://developer.apple.com/documentation/xcode/understanding-build-product-layout-changes) describes the debug executable stub, application `.debug.dylib`, and `__preview.dylib`. Older descriptions focused on generated dynamic-replacement thunks. HotReloadKit deliberately uses its own compatible build layout and replacement mechanism; its README's relationship to previews should not be read as a complete description of current Xcode internals.
Apple's supported preview workflow, including on-device previews, does not establish that an ordinary development app may receive a newly built dylib into its data container and `dlopen` it. Use previews as precedent for edit classification and tooling, not evidence for a portable Rust device loader. No comparable current edit-to-presented-frame dataset was found.
### InjectionNext's actual loader is more informative than its support label
InjectionIII and its successor InjectionNext rebuild changed Swift/Objective-C source and replace behavior using injection/runtime mechanisms. InjectionNext advertises device support. At inspected revision `b39c9f15cf8d8b99978297cb76514a7e0280ec8c`, the host signs generated dylibs using a selected Apple Development identity ([NextCompiler.swift, lines 392–411](https://github.com/johnno1962/InjectionNext/blob/b39c9f15cf8d8b99978297cb76514a7e0280ec8c/App/InjectionNext/NextCompiler.swift#L392-L411)); the app receives bytes, writes a temporary file, and loads/patches it ([runtime, lines 349–354](https://github.com/johnno1962/InjectionNext/blob/b39c9f15cf8d8b99978297cb76514a7e0280ec8c/Sources/InjectionNext/InjectionNext.swift#L349-L354)).
Counterevidence is specific and recent. [Issue #81, July 2026](https://github.com/johnno1962/InjectionNext/issues/81#issuecomment-5106386779) reports an iPhone 15 on iOS 26.4.2 with Xcode 26.3 rejecting the dylib with `code signature invalid … (errno=1)`, despite a matching signing identity and corrected load commands. An entitlement hypothesis did not resolve the report. On [2026-10-06 the maintainer wrote](https://github.com/johnno1962/InjectionNext/issues/81#issuecomment-6006741081), “Been unable to test this on an iOS 26 phone thus far.”
The thread also [quotes Apple DTS](https://github.com/johnno1962/InjectionNext/issues/81#issuecomment-5106411624) distinguishing OS/embedded libraries from downloaded libraries in the data container. The original [Apple forum thread](https://developer.apple.com/forums/thread/773210) was blocked by security verification during this research, so that quotation is secondary evidence. The thread does not prove every native injection technique is impossible on every iOS version. It does rule out treating “sign the dylib with the same identity” as an established solution.
## 7. Physical iPhone reload must separate data loading from native executable loading
Apple's [runtime process security documentation](https://support.apple.com/guide/security/runtime-process-security-sec15bfe098e/web) explains signed entitlements and execute-never protections. A development signing identity, Developer Mode, and `get-task-allow` are not interchangeable with permission to execute arbitrary downloaded native pages. `get-task-allow` enables debugger attachment; macOS's hardened-runtime JIT entitlement is not a general iOS entitlement an ordinary app can add.
Historically, debugger attachment and `CS_DEBUGGED` relaxed relevant checks. See the [XNU code-signing flags](https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/cs_blobs.h) and [technical investigation of iOS 18.4 changes](https://gist.github.com/osy/8940e5ae5f24646b808f58d197883ca5). With newer Trusted Execution Monitor restrictions, executable pages may require debugger-assisted handling rather than merely a one-time attachment.
Current working source shows the distinction:
- Dart's [virtual_memory_posix.cc](https://github.com/dart-lang/sdk/blob/main/runtime/vm/virtual_memory_posix.cc) creates executable mappings/aliases and calls `NOTIFY_DEBUGGER_ABOUT_RX_PAGES` for debugger-assisted preparation.
- Flutter's [ios/lldb.dart](https://github.com/flutter/flutter/blob/master/packages/flutter_tools/lib/src/ios/lldb.dart) installs a Python callback that touches those pages via LLDB `WriteMemory`, including the `IHELPED!` marker. The inspected implementation also contains an iOS 27 manual-continue workaround.
- [UTM's corresponding change](https://github.com/utmapp/UTM/commit/07c79d17c5c9cc3136d50b00867bdeb56ca070d2) provides another concrete debugger-assisted JIT precedent.
Therefore, both “iOS JIT is impossible” and “attach LLDB and normal dylib loading works” are too broad. A native Rust experiment could investigate debugger-assisted executable pages, but would additionally need Mach-O/object relocation, symbol resolution, unwind metadata, TLS handling, architecture-specific details, and patch lifetime management. That is a new loader/runtime project, not an entitlement flag for Subsecond.
| Route | Mac | iOS simulator | Physical iPhone |
|---|---|---|---|
| Tokens, assets, parsed view descriptions | Ordinary data reload | Ordinary data reload | Ordinary data reload; implement device transport |
| Native Subsecond patch | Project-supported | Project-supported | Explicitly unsupported in current source |
| HotReloadKit | Supported Debug path | Supported Debug path | Runtime deliberately inert |
| InjectionNext dylib transfer | Native injection path | Native injection path | Advertised, but recent signing/load failure unresolved |
| Dart/Flutter debug hot reload | Supported framework workflow | Supported framework workflow | Supported framework workflow with debugger machinery |
| Interpreter embedded in signed host | Feasible | Feasible | Avoids native executable mapping for replacement bytecode |
| Custom debugger-assisted Rust loader | Unnecessary for baseline | Unnecessary for baseline | Experimental, no Rune implementation or latency proof |
For development, transfer ordinary data to an already installed native host. A release build can compile out the reload transport and ship bundled descriptions or a native lowering of the same representation. App Store distribution policy is a separate question from whether a developer-installed interpreter can run; do not describe an interpreter choice as automatic approval for arbitrary downloaded production features.
## 8. Interpreted Wasm can carry Rust logic, but should not carry the renderer
An interpreter treats incoming Wasm bytes as data and executes them through code already in the signed host. Configure interpreter-only builds explicitly: WAMR also offers AOT/JIT modes, and a native-code AOT artifact does not gain the portability of interpreted bytecode merely by coming from a Wasm toolchain.
| Runtime | Mechanism and fit | Main question for Rune |
|---|---|---|
| [wasm3](https://github.com/wasm3/wasm3) | C interpreter, internal execution representation without native JIT. Strong current scalar/call-heavy benchmark results. | Does the chosen Rust Wasm target emit only supported features? Measure load time and the host-call boundary. |
| [WAMR](https://github.com/bytecodealliance/wasm-micro-runtime) fast interpreter | Configurable C runtime with interpreter, AOT, and JIT options. Use interpreter only. | Select features carefully; published benchmark patches must not be mistaken for upstream functionality. |
| [wasmi](https://github.com/wasmi-labs/wasmi) | Rust interpreter with validation, embedding APIs, and fuel metering. Version 2.0 arrived 2026-09-01 with accumulator IR and revised dispatch. | Benchmark current v2, rather than using historical rankings. Its [changelog](https://github.com/wasmi-labs/wasmi/blob/main/CHANGELOG.md) claims 2.2× geomean improvement over v1; that is not an iPhone comparison. |
The strongest current physical-device evidence found is a [2026-09-22 interpreter comparison](https://github.com/rebeckerspecialties/wasm-benchmark/blob/main/docs/runtime-comparison-2026-09-22.md), with raw data and N=10 runs on an iPhone XS Max/A12, iOS 18.7.10, primarily E-core execution. Across 17 mutually supported cases, geometric means of CPU time relative to the fastest runtime per case were wasm3 **1.04**, WAMR **1.38**, and Pulley **1.68**. Those are relative interpreter scores, not slowdowns versus native, and wasmi was absent. The WAMR build carried patches.
That benchmark's full femtovg Wasm guest achieved only **7.0 fps** for scene 0 on wasm3/A12. Pulley's load-time translation of the roughly 1 MB guest took about **2.7 s**. These workloads do not predict tiny-handler reload times, but they directly contradict assuming that a full interpreted Rust UI stack will comfortably maintain 120 Hz or load below 300 ms.
Recommended boundary:
- Native host owns layout, text shaping, rasterization, springs/gesture integration, resource caches, and authoritative state.
- Guest computes small event reductions and view descriptions when dependencies change. It does not run a whole per-frame renderer.
- Host calls are batched through a compact command/result buffer. Avoid crossing the interpreter boundary for every property of every node.
- Stable numeric handles identify native state and resources. Guest memory is generation-local unless an explicitly versioned serialization contract migrates it.
- Fuel/time limits contain runaway handlers. A failed candidate generation leaves the previous one active.
Rust-to-Wasm still invokes rustc. A small isolated crate may compile quickly, but no sub-300 ms result was established here. For the primary design loop, a parsed view/expression language is the stronger latency bet. Wasm is an optional logic tier when Rust reuse is worth the compilation and embedding cost. Reusing an old guest's linear-memory bytes with a changed Rust allocator/data layout is not state migration.
## 9. Tokens, assets, and shaders should each have a direct reload path
### Reuse knobs' typed remote-control model
Local sources inspected: the knobs library's `README.md`, especially `createRemoteControls`, and `docs/migration.md`. Remote descriptors carry typed values such as spring, color, point, easing, gradient, and curve. `onSet` handles individual updates; `onSetBatch`/`setMany` batches related edits; `null` resets a value. Incoming `.sync` updates avoid echoing back and creating undo entries.
The requested tuning files from a private iOS client were absent from the current checkout. They were inspected through Git revision `67fbf2b6`: `scripts/tune-server.ts` and `scripts/tune-page/index.ts` in the private iOS client. That historical implementation uses `/phone` and `/ui` WebSockets, capability negotiation, atomic batch validation, and the older `setValues` name. State broadcasts are coalesced for 16 ms. The page's `echo: 5000` setting suppresses stale echoes; it is not a five-second outbound delay. Do not assume those historical paths or protocol names describe the present checkout.
For Rune, connect each typed descriptor to a stable host property ID. Validate a whole edit transaction before applying it on the UI thread. Preserve spring position and velocity when changing targets or parameters. Stream compact deltas while dragging; persist the final chosen values to source/configuration with an explicit policy so a live value is not mistaken for a saved default.
### Assets can swap by stable resource handle
Proposed asset pipeline: content hash → transfer missing bytes → decode/shape/upload off the render thread where possible → replace the resource generation at a frame boundary. Keep the old resource on decode failure and while GPU work references it. A font change must invalidate affected text/layout caches; it is more expensive than changing a color. Large texture uploads and font work get separate latency reporting rather than being hidden in the token budget.
### Shader compilation is available without arbitrary CPU JIT
Metal exposes runtime shader-library compilation through [`MTLDevice.makeLibrary(source:options:)`](https://developer.apple.com/documentation/metal/mtldevice/makelibrary(source:options:)). For a portable WGSL front end, [naga](https://github.com/gfx-rs/wgpu/tree/trunk/naga) can validate and translate to backend shader code. Neither API implies a universal shader-to-pixels latency.
Proposed pipeline: parse/validate → compile shader and pipeline asynchronously → validate resource/binding compatibility → stage the new pipeline → swap at a frame boundary. Retain old pipeline/resources until prior GPU submissions complete. Binding-layout changes need a compatible resource rebuild or a rejected patch. On any error, retain the last working pipeline and report source diagnostics. Cached small shaders may fit 300 ms; cold or complex pipeline compilation needs measurement and must not block ordinary view/token edits.
## 10. State preservation needs an explicit contract
The state host should retain application entities/signals, navigation, keyed list identity, text selection/composition, focus, scroll anchors, gesture ownership, and animation position/velocity independently of replaceable view code. Stable identity must be explicit enough to survive inserting a sibling or moving a source block. A source line number or Rust `TypeId` alone is insufficient.
### Classify edits before publishing them
| Edit | Proposed behavior |
|---|---|
| Color, spacing, text, spring target/parameters | Update values, invalidate affected dependencies, retain state and motion continuity. |
| View structure with the same explicit node/state IDs | Reconcile nodes; preserve compatible state, focus, and scroll anchors. |
| Handler/body change with the same state and call schema | Install new behavior at a safe boundary; retained state remains authoritative. |
| Added optional state field with a declared default | Run a transactional schema migration. Existing fields keep their values. |
| Renamed field with an explicit migration | Migrate by stable field ID or declared mapping, not coincidental position. |
| Incompatible component state or changed hook-like signature | Reset only that component/subtree and report the reason. |
| Native renderer/layout ABI, allocator, or platform-shell change | Snapshot supported state, rebuild/relaunch, restore; replay if required. |
Schemas must capture semantic compatibility, not just `size_of`/alignment. Two equally sized fields can change meaning or order. State outside the stable host needs an explicit export/import contract; absence of a migration means reset or restart, not a best-effort pointer cast.
### Commit one generation, with no mixed old/new behavior
Proposed transaction:
1. Receive generation N with base-generation ID, source hashes, required host capabilities, ABI/schema fingerprints, and all changed resources.
2. Parse/compile and validate in staging. Reject missing dependencies, stale bases, incompatible bindings, or invalid migration plans without mutating the live generation.
3. At a safe event/frame boundary, finish the current reducer. Drain or cancel generation-owned work. Take the migration snapshot from the current state, not an earlier background copy that would lose intervening user input.
4. Apply migrations and install view/handler/resource references as one commit. Route future events through stable handler IDs. Drop late async results from retired generations unless their host-owned operation explicitly survives reload.
5. Reconcile affected nodes, render, and acknowledge N on its first presented frame. Release retired resources only when CPU callbacks and GPU submissions no longer reference them.
Old native images may need to stay loaded because destructors/vtables/code pointers remain reachable. Interpreted generations are easier to reclaim if host handles and generation ownership are enforced. Validation can be atomic even when parsing allocates staging objects; execution-time traps still need an explicit rollback/reset policy rather than a claim that every script has been proven safe.
### Snapshot/replay is a fallback, not a substitute for live identity
Record semantic inputs, external I/O responses, timer delivery, a controlled clock, and random seeds. Rebuild from a snapshot and replay events to restore a useful development state after native changes. Network mutations and other external side effects must be suppressed or substituted during replay, with stable operation IDs to avoid duplicate sends.
Replay needs the same deterministic scheduler/input model used for headless agent verification. It will not automatically recreate arbitrary OS handles, an in-progress IME session, or undocumented platform state. Expose which state was preserved, migrated, reset, or reconstructed in the inspector.
## 11. Steal and avoid
### Steal
- Subsecond's baseline-symbol reuse and jump-table entry points for desktop native edits.
- HotReloadKit's conservative compatibility planner, atomic publication, and runtime receipt, extended through actual presentation.
- Makepad's source-as-data update path and preflight of a complete script batch.
- Slint's worker compilation, diagnostics, and last-good retention.
- React's stable component families and compatibility signatures.
- Flutter's persistent-state/replaced-behavior model, with explicit restart-only edit classes.
- Knobs' typed descriptors, batch validation, remote synchronization, and echo suppression.
### Avoid
- Calling simulator support “iOS device hot reload.”
- Claiming <300 ms from a compiler timer, animation GIF, or unqualified README number.
- Depending on arbitrary data-container dylib loading for the main iPhone workflow.
- Patching arbitrary Rust allocations or async futures across type-layout changes.
- Using reloadable-crate TLS/globals as the durable state host.
- Unloading libraries while callbacks, tracing registries, vtables, or destructors still reference them.
- Putting text/layout/rendering or spring integration into an interpreter merely to make everything reloadable.
- Rebuilding the entire view state on every edit, or replaying external side effects to reconstruct it.
- Applying half of a multi-file save or reporting success before the changed generation is visible.
## 12. Recommended Rune layers and latency budgets
Use a native runtime with one persistent state store and one keyed view representation. Expose four reload classes through the same development connection:
1. **Live values:** typed tokens, animation parameters, and resource references. This should be the quickest path on every platform.
2. **Live views:** a declarative tree plus bounded expressions/handlers that can be parsed without invoking Rust. Keep IDs, schemas, diagnostics, and dependency tracking shared with the native runtime. The same representation can be bundled or lowered for production.
3. **Replaceable logic:** small interpreted Wasm modules when Rust reuse is needed; Subsecond as the Mac/simulator native acceleration path. Both use the same host-state and handler-ID contract where practical.
4. **Native rebuild:** renderer/platform/core changes rebuild with snapshot restoration and deterministic replay support.
Do not make an elaborate language a prerequisite for the first spike. Start with a minimal typed tree and a tiny handler/expression vocabulary that can change real behavior. Let the device result determine whether to expand that language or add Wasm.
### Proposed warm-path budgets, not measurements
All figures below are milliseconds. Assumptions: app already running in the foreground; established connection; small payload (tokens or view/handler delta up to roughly 32 KiB); no large asset upload; warm caches; no new native build. These are allocations to validate, not percentiles inferred from other frameworks.
| Stage | Tokens, Mac / iPhone | View data + small interpreted expressions, Mac / iPhone |
|---|---:|---:|
| Detect/settle save or collect input | 10 / 10 | 20 / 20 |
| Parse, validate, package | 2 / 2 | 25 / 25 |
| Established transport | 2 / 15 | 2 / 20 |
| Receiver decode/validation/staging | 2 / 5 | 15 / 30 |
| Wait for safe boundary and commit | 10 / 10 | 10 / 10 |
| Reconcile/layout/render/present | 17 / 25 | 25 / 35 |
| Scheduling/variance reserve | 15 / 25 | 40 / 60 |
| **Allocated total** | **58 / 92** | **137 / 200** |
The render stage can span multiple display intervals; these numbers do not authorize a single 25–35 ms UI-thread stall. Background staging and incremental work must preserve the normal 8.33 ms frame budget. View updates have 100 ms of headroom under the 300 ms target, which may be consumed by realistic trees, transport variance, or cache misses.
For small Rust-to-Wasm edits, a separate **aspirational iPhone allocation** is 20 ms detect + 100 ms compile/package + 20 ms transfer + 40 ms load/validate + 10 ms commit + 35 ms render/present + 50 ms reserve = **275 ms**. The 100 ms Rust compilation and 40 ms module-load allocations are unproven and may fail. If they do, retain the fast interpreted view path rather than moving its target to match Rust compile time.
For Mac Subsecond, write the total as **rustc + patch link + approximately 50–100 ms delivery/application/presentation overhead**, with that overhead also a proposed allowance. A 300 ms total would leave only about 200–250 ms for compilation/linking. The reviewed evidence does not establish that allowance for realistic Rune crates. Treat native patching as a convenience tier with measured per-edit results, not the foundation of the latency promise.
### Device transport must be measured independently
Use a long-lived bidirectional connection with generation IDs, hashes, capability negotiation, and last-applied/last-presented acknowledgements. Test local-network and a deliberately configured USB-forwarded route separately. A plugged-in phone may still be sending traffic over Wi-Fi; log the actual route. USB pairing/forwarding setup and cold connection time are separate from warm edit latency. Remote build-worker-to-Mac artifact transfer, when used, must be counted as an extra stage.
Use a host monotonic clock for save-to-returned-present-ack time. That includes acknowledgement return transit and is a conservative observable bound. Device timestamps partition receive-to-present without cross-machine clock assumptions. For more precise one-way attribution, estimate clock offset and uncertainty explicitly. A submitted command buffer is not a presented drawable; use presentation timing where available and label any proxy.
### Rejected foundations
| Alternative | Why reject it as the primary architecture |
|---|---|
| Subsecond everywhere | Current physical iPhone exclusion, Rust compile variability, and no automatic arbitrary-state migration. |
| One stable-ABI native dylib everywhere | Cleaner boundary, same device executable-loading problem. |
| Build/sign/download a dylib into the iPhone container | Recent concrete failure; no dependable supported recipe established. |
| Custom debugger-assisted native Rust JIT first | High loader/runtime cost and OS-version coupling before proving the basic design loop. Keep as a later experiment. |
| Entire UI stack in interpreted Wasm | Conflicts with the 120 Hz priority; current full-renderer benchmark and load-time evidence are poor. |
| Rust-to-Wasm for every spacing/text edit | Retains compiler latency for edits that can be parsed directly. |
| Restart and replay for every edit | Loses immediate interaction continuity and makes external side-effect reconstruction part of the common path. |
| Adopt Flutter or a WebView solely for hot reload | Gives up the requested ownership of Rune's native rendering/layout/state stack. Reuse the state model instead. |
## 13. Validate the physical-iPhone path first
The first spike should run a development-signed native host on a physical iPhone, launched **without an attached debugger**, with the same minimal view representation on Mac. Keep native state, rendering, and animation alive while a remote edit changes a token, a keyed subtree, and a small event handler. A counter whose increment changes from one to two proves changed behavior rather than only remote styling.
The spike should answer these questions in order:
1. Can token, tree, and handler changes travel to the phone as data and appear within 300 ms, measured through presentation? Record hardware, OS/toolchain, payload sizes, transport route, warm/cold status, and each pipeline stage. Collect at least 30 warm edits per class, reporting median, p95, maximum, and failures; this is proposed spike work, not work performed in this report.
2. Does the same state survive? Include a nonzero counter, text input/selection, a scrolled keyed list, navigation, and an active spring. Check that position/velocity continue across a parameter or subtree edit.
3. Does malformed input leave the last good generation visible? Does an incompatible state-schema change reset only its intended subtree? Can two rapid edits supersede an older staged generation without mixing resources?
4. Does the interpreter remain outside the frame-critical path? Measure handler execution and reload-commit work against the existing native frame budget. Add Wasm only after the simpler path establishes transport and state behavior.
5. Separately, how fast are small Mac Subsecond edits in a realistically partitioned workspace? Include body-only, changed workspace dependency, closure capture, added state field, and patched-crate TLS cases. Record rejection/reset behavior, not just successful reloads.
Only then consider a separate modern-iPhone native-loader experiment with debugger assistance. Its acceptance criterion is repeatable success across the actual device/OS/toolchain combination, including reconnect and multiple generations, not one successful `dlopen`.
## Open questions
- How much application behavior must be live for the first consumers? That determines whether a small expression language is sufficient before introducing Wasm.
- Can a shared typed view representation lower to native production code without dev/release semantic drift? Which constructs must be rejected or interpreted in both modes?
- Which state schemas can be generated mechanically, and which require explicit migrations? How should agents receive precise reset/restart diagnostics?
- What are actual p95 transport and presentation latencies on Kit's connected iPhone over USB forwarding versus local Wi-Fi?
- Which current interpreter wins on Rune-sized modules when compilation, instantiation, host calls, and memory reclamation are included? Include wasmi v2, absent from the cited device comparison.
- Does the chosen renderer expose reliable presented-frame timestamps on every target, or must some targets report a clearly labeled submission/completion proxy?
- How much resident memory accumulates across Subsecond/Swift-style native generations, and when should snapshot/restart occur?
- Can shader/layout changes preserve a moving interface without a visible discontinuity, and which binding or geometry changes require an explicit transition/reset?
+159
View File
@@ -0,0 +1,159 @@
# Standalone Rust hot-patching with Subsecond
Hands-on spike, 2026-10-21. [Source and reproduction instructions](../spikes/hot-patch/README.md). All Rust execution took place on a remote M2 Max build Mac. No windows were opened.
## Summary
- **Yes, a standalone Rust program can hot-patch without a Dioxus UI.** A terminal loop used `dioxus_devtools::connect_subsecond()` and `subsecond::call(...)`; the patched function returned a string.
- Ten successive body edits preserved the running process, counter, Vec allocation and contents, and main-owned struct instance. Save→first new-function output was **989 ms median / 1,150 ms p95**, with a 712–1,150 ms range.
- This did **not** meet Rune's approximately 300 ms target. Even save→patch-applied, before waiting for the next tick, was **826 ms median / 1,100 ms p95**.
- A conventional build of the final spike took **71.33 s artifact-cold** and **1.846 s for one incremental body edit**. The registry was warm for that cold-artifact build.
- The exact simple expression `subsecond::call(|| render(&state))` silently kept running old code in 0.7.10. A two-reference capture worked; `HotFn::current(render).call((&state,))` also worked and is the better integration candidate.
- Generic function bodies, a closure body, and a statically dispatched trait implementation patched successfully. A cached `Box<dyn Trait>` retained its old method. A signature change inside a stable closure patched; changing the explicit `HotFn` boundary signature left old behavior running.
- **State preservation is conditional.** Adding a struct field was accepted without migration or rejection. Tip-crate atomic statics and thread locals reset on patches in this experiment, including a separately tested exported static. The static result contradicts the broad documentation claim.
- Subsecond 0.7.10 explicitly documents **physical iOS devices as unsupported for Rust hot-patching**. Simulator support is documented but was not measured. Recommendation: an optional desktop development backend, not Rune's sole hot-reload foundation.
## 1. Environment and integration
| Item | Actual setup |
|---|---|
| Worker | M2 Max build worker, Apple M2 Max, 12 cores / 96 GiB |
| OS | macOS 27.0.1, build 26A434 |
| Compiler | `rustc 1.99.0 (b940084d7 2026-09-28)`, stable aarch64 Apple Darwin |
| CLI | `dioxus 0.7.10 (57d6794)` |
| Crates | `subsecond = =0.7.10`, `dioxus-devtools = =0.7.10`, lockfile retained |
| Build settings | `opt-level=0`, `debug=0`, incremental enabled, two Cargo jobs |
| Execution | Remote shell on a background-priority job runner |
The pre-existing `dx` on `PATH` was Deno's launcher. I installed the latest available Dioxus release with `cargo-binstall dioxus-cli --no-confirm` on the worker. It installed `~/.cargo/bin/dx`, which the driver addresses explicitly. The inherited sccache wrapper rejected incremental compilation, so the driver clears `RUSTC_WRAPPER` for its subprocesses. [Recorded environment](../spikes/hot-patch/evidence/environment.json).
The binary has a counter, `Vec<u64>`, and nested `Panel` struct owned by `main`. Each nominal 120 Hz tick increments the counter and first Vec entry, calls `render`, and prints a timestamp, PID, state/Vec addresses, and output. It creates no `VirtualDom` or Dioxus renderer. `dioxus-devtools` does bring Dioxus core/signals dependencies transitively; this proves independence from the UI runtime, not a dependency graph free of Dioxus crates.
The devtools adapter supplies a WebSocket connection with the PID, build ID, and ASLR reference, then passes matching jump tables to `subsecond::apply_patch`. The runtime loads the patch dylib and updates its jump table. It retains loaded libraries and jump tables rather than unloading previous code. Sources: [devtools 0.7.10, `connect_subsecond` and `connect_at`](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/devtools/src/lib.rs#L69-L120), [Subsecond `apply_patch`](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/subsecond/subsecond/src/lib.rs#L498-L555), and [jump-table storage](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/subsecond/subsecond/src/lib.rs#L270-L321).
The measured closure needs a second captured reference because of the bug discussed below. A separate successful probe used this simpler API:
```rust
dioxus_devtools::connect_subsecond();
// main owns state; each iteration calls the latest render implementation.
let output = subsecond::HotFn::current(render).call((&state,));
```
## 2. Measured edit latency and builds
The driver writes `src/main.rs`, closes it, records Python `time.time_ns()`, and waits for the first frame whose revision matches the edit. Rust records its epoch timestamp immediately after the patched call returns. Both clocks are on the worker. These numbers include filesystem watching, compilation/linking, patch delivery/loading, and the next actual call. They exclude syncing the source to the worker. The script makes ten revision edits in one process, with at least 30 observed frames between them. [Raw samples](../spikes/hot-patch/evidence/benchmark.json).
| Edit | Save→new output, ms | Save→patch callback, ms |
|---:|---:|---:|
| 1 | 1,150.117 | 1,099.745 |
| 2 | 712.420 | 663.000 |
| 3 | 998.195 | 807.863 |
| 4 | 867.826 | 712.570 |
| 5 | 753.253 | 751.811 |
| 6 | 1,005.250 | 834.011 |
| 7 | 851.558 | 817.549 |
| 8 | 979.820 | 860.620 |
| 9 | 1,036.368 | 915.992 |
| 10 | 1,030.275 | 938.728 |
| **Median** | **989.008** | **825.780** |
| **p95, nearest rank** | **1,150.117** | **1,099.745** |
With ten observations, nearest-rank p95 is the maximum. This is one short run on a shared worker, not a population estimate. The CLI's own ten reported hot-patch durations were 962, 523, 665, 575, 617, 695, 678, 723, 773, and 732 ms; their median is 686.5 ms. CLI duration alone omits part of the experienced delay.
### Scheduling qualification
The job runner launches jobs with background/utility scheduling and `nice 10`. The sleep-based 120 Hz loop was visibly batched: among 1,453 adjacent frame intervals, median was 0.004 ms, p95 16.917 ms, and maximum 207.965 ms. It catches up missed deadlines rather than presenting evenly spaced frames. Patch callback→first new output was 105.374 ms median and 190.332 ms maximum.
These are actual background-worker measurements. They do not establish 120 Hz rendering quality or foreground-app latency. The callback timings still show that removing frame-wakeup delay alone would not get this run under 300 ms. A foreground-priority measurement would need a separate controlled run.
### Comparison with normal builds
| Operation | Wall time | Conditions |
|---|---:|---|
| Conventional artifact-cold build, final source | 71.333 s | Empty `target/normal-final`; dependencies already downloaded |
| Conventional incremental rebuild, final source | 1.846 s | One render constant changed; same target directory |
| Initial conventional cold build | 79.600 s | Earlier minimal source; included dependency resolution/download work |
| Initial conventional incremental rebuild | 1.672 s | Earlier minimal source |
| Initial `dx` hotpatch-enabled build | CLI reported 133.88 s | Separate DX artifact/profile cache; initial single-capture version |
The final normal-build pair is the closer comparison. Both conventional builds exited successfully. The median live patch was about 1.87× faster than that single conventional incremental build, while also retaining the tested state. Conventional build timing stops at build completion and does not include app relaunch/state reconstruction. [Final build results](../spikes/hot-patch/evidence/builds.json), [initial build results](../spikes/hot-patch/evidence/initial-builds.json).
## 3. What preserved state, what broke
The ten body edits all retained PID `12294`, Vec address `4313468912`, and state address `6169897736`. At every first patched tick, the counter advanced, `vec0 == counter + 73`, and panel width remained 800. This establishes preservation of these existing main-owned values, not arbitrary Rust state.
Each following probe began with a fresh process. The driver saved the source edit and observed the running output. [Probe results](../spikes/hot-patch/evidence/probes.json), [extra probes](../spikes/hot-patch/evidence/extras.json), [explicit boundary-signature probe](../spikes/hot-patch/evidence/extra-explicit_hotfn_signature.json).
| Edit | Observed behavior |
|---|---|
| Generic `generic<T: Display>` body, `g0`→`g1` | New monomorphized behavior appeared in 811 ms; main-owned state preserved. This tests an existing `u64` instantiation, not all generic changes. |
| Closure body inside `render`, `value+10`→`value+20` | New result appeared in 974 ms; state preserved. |
| Trait implementation, direct `state.panel.label()` | `t1` appeared in 1,051 ms; state preserved. |
| Trait implementation with a `Box<dyn Label>` cached in main-owned state | Revision changed in 838 ms, but the trait call still returned `t0:42x24`. The existing object's vtable continued to call old code. |
| `render(&state)`→`render(&state, tone)`, with callsite changed inside the two-capture closure | `rev=99` appeared in 1,351 ms. The outer `FnMut() -> String` boundary stayed compatible, allowing its body and inner call to change together. |
| Same signature change when `HotFn::current(render)` was called directly from the original main loop | Patch callback fired, but old `rev=0` continued through the five-second observation. No automatic restart or panic was observed. The host's old call boundary was not replaced. |
| Append `extra: u64` to `AppState`; change its initializer in main | Patch accepted in 1,449 ms. Patched code reported size 56 instead of 48, while PID, state address, and existing contents remained. Main's new initializer did not run. No migration or incompatible-layout rejection occurred. |
| Atomic static initializer, 1000→9000 | First patched output was `static=9000`, rather than the next old counter value. Appeared in 1,123 ms. |
| Same static test after adding `#[unsafe(no_mangle)] pub` | Still reset to 9000; appeared in 1,104 ms. Exporting its symbol did not preserve it in this configuration. |
| Thread-local initializer, 2000→9000 | First patched output was `tls=9000`; appeared in 872 ms. |
Even the ten ordinary revision edits reset the unchanged tip-crate static and TLS to 1000 and 2000 on each first patched frame. The [0.7.10 docs](https://docs.rs/subsecond/0.7.10/subsecond/#globals-statics-and-thread-locals) warn about tip-crate TLS, but claim globals are tracked and initializer edits are not observed. **The static probes did not match that claim.** This result is specific to the tested macOS tip-crate static; dependency statics were not tested.
The struct probe deliberately did not explicitly read `extra`, to avoid turning an out-of-bounds read into a supposed success. Crossing that changed Rust type is already outside the supported safety contract. It demonstrates acceptance of an incompatible patch, not that adding fields is safe. The upstream [layout limitation](https://docs.rs/subsecond/0.7.10/subsecond/#struct-layout-and-alignment) explicitly leaves re-instancing to framework authors.
### Pointer-sized capture bug
The requested minimal `subsecond::call(|| render(&state))` compiled and ran normally, but a revision edit never appeared during the initial 30-second observation. A second isolated reproduction with a patch callback confirmed that a jump table was applied, yet old output continued for five seconds. [Initial failure](../spikes/hot-patch/evidence/pointer-capture-failure.json), [instrumented reproduction](../spikes/hot-patch/evidence/extras.json).
The source explains this behavior. [`HotFn::try_call`](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/subsecond/subsecond/src/lib.rs#L411-L440) chooses function-pointer dispatch whenever the closure's size equals a function pointer's size. One captured reference satisfies that test. [`call_as_ptr`](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/subsecond/subsecond/src/lib.rs#L900-L949) then searches the jump table with those captured bytes, and falls back to the original callable when there is no match. The observed lack of a diagnostic is consistent with that fallback.
Adding a second captured reference makes the measured closure follow the other dispatch path. The separate explicit-argument `HotFn` probe changed behavior in 918 ms with state preserved. Use that API with a stable signature rather than relying on the artificial second capture. Its signature-change probe also shows why the stable-signature restriction matters.
## 4. iOS and GPU scope
### Simulator
Not executed. The worker had Xcode 27.1, no booted simulators, and only the `aarch64-apple-darwin` Rust target installed. More importantly, the release's [`start_ios_sim`](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/cli/src/build/apple.rs#L85-L145) boots a simulator and calls `open::that_detached` on `Simulator.app`. A straightforward `dx serve --ios` would violate this spike's no-visible-windows constraint. A headless simulator launcher would be a separate integration task. No simulator latency or state-preservation claim is made here.
### Physical iPhone, researched only
The [Subsecond 0.7.10 platform documentation](https://docs.rs/subsecond/0.7.10/subsecond/#platform-support) explicitly excludes devices because of code-signing requirements. The [release architecture note](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/notes/architecture/07-HOTRELOAD.md) also lists iOS Simulator support and device hot-patching as unsupported.
Ordinary device deployment needs the `aarch64-apple-ios` target, a signed development app with matching bundle ID/provisioning profile, a development identity, Developer Mode/device trust, and transport to the device. The CLI's [Apple signing path](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/cli/src/build/apple.rs#L282-L363) embeds a provisioning profile and signs the bundle; its generated development entitlements include `get-task-allow`. The [device-serving discussion](https://github.com/DioxusLabs/dioxus/discussions/3545) reports ordinary `dx serve --ios --device` working in 2026. That does not establish Rust dylib hot-patching.
Subsecond additionally needs each newly generated patch to reach the running app, load as executable code under iOS's signing restrictions, and be mapped to that process's ASLR addresses. I found no supported turnkey device path in this release. A proposed debugger-assisted or signed-patch loader remains unverified engineering work; a simulator result would not remove this blocker.
### GPU
The optional wgpu/Metal extension was not attempted. This spike preserves CPU heap allocations and state, not a verified live GPU device/queue/texture. Owning GPU resources outside the patched code is a plausible design, but cached callbacks/vtables and changing Rust wrapper layouts would still need attention.
## Steal
- Use explicit patch boundaries around a small UI-logic function, with state owned by a stable host.
- Keep the compiler/linker cache warm and compile the smallest changing crate. Subsecond documents that only the executable's tip crate patches; `mod` files in that crate fit better than a changing library dependency. [Workspace limitation](https://docs.rs/subsecond/0.7.10/subsecond/#workspace-support).
- Record save time, patch-applied time, and first new frame separately. Verify state with identities and content invariants rather than a CLI success message.
- Reuse the ASLR/PID/build-ID protocol if implementing a smaller Rune-specific transport. The existing adapter is sufficient for an initial experiment.
## Avoid
- Promising approximately 300 ms from the name “Subsecond” or its compiler timer alone.
- Treating arbitrary captured closures, changed type layouts, tip-crate statics, or persistent trait-object vtables as transparently reloadable.
- Assuming a successful Rust build or patch callback means the application is executing new code.
- Designing the connected-iPhone workflow around an unverified device patch loader.
## Recommendation for Rune
Keep Subsecond as an optional **desktop development backend** worth evaluating with a realistic Rune renderer. Put long-lived state and GPU ownership in a stable host, expose explicit patch functions with stable argument/return shapes, and rebuild or migrate state on incompatible schema changes. Replace cached callbacks or trait objects when their implementation changes. Any such migration and invalidation machinery belongs to Rune; this spike did not implement it.
Reject Subsecond 0.7.10 as the **sole Mac-and-iPhone hot-reload layer** for now. The measured latency misses the target, physical devices remain unsupported, and several ordinary Rust patterns silently keep old behavior or lose state. Also reject “wrap everything in `subsecond::call`” as an integration strategy, and do not change the entire renderer to Dioxus just to obtain its compiler tooling: the standalone integration already works.
Normal rebuild/relaunch is the known fallback for incompatible Rust changes, but it does not satisfy the requested state-preserving iteration loop. A runtime-editable UI/layout description could cover frequent visual edits without recompilation; that is a candidate for a separate measurement, not a result of this spike.
## Open questions
1. How much faster is the same end-to-end test under a real foreground app's scheduling policy, and with Rune-sized dependencies?
2. Can the pointer-sized capture and tip-static behavior be fixed upstream or constrained reliably in an adapter?
3. How should Rune detect incompatible schema changes before applying a patch and migrate state across them?
4. What is the practical memory growth over hundreds of patches, given retained libraries and jump tables?
5. Can a supported, repeatable physical-iPhone patch loader meet the target without restarting the app?
6. Do real wgpu/Metal resources survive patches once cached callbacks, vtables, and renderer-thread coordination are included?
@@ -0,0 +1,467 @@
# Agent-native tooling and performance targets for Rune
Research date: 2026-10-21. Reader: Kit and the Rune architecture team. This report supports a decision about the first tooling interfaces and the workloads that should define “fast.” All Rune interfaces and budgets below are proposals, not implemented features or measured results.
## Summary
- Make the scene runner, inspector protocol, clock, and trace schema part of the framework's first architecture. Adding them after applications exist makes deterministic verification much harder.
- Give agents stable semantic IDs, small tree queries, computed geometry, presentation values, source locations, and structured errors. A screenshot alone cannot explain which constraint, state update, or animation caused a failure.
- Use deterministic offscreen rendering for correctness and dedicated devices for performance. Virtual time can prove a spring's continuity; it cannot prove that the GPU presented its frames on time.
- Reuse Scrawl's motion-trace JSONL format, Scrawl's named scene labs, the layout linter's invariant checks, and knobs' remote parameter descriptors. Keep a richer internal trace so the compatibility format does not constrain the renderer.
- Published startup, memory, and size comparisons are useful only with their measurement boundaries attached. One widely cited toolkit benchmark measures container memory rather than process RSS, and its dependency sizes are Docker image deltas.
- Current small Rust app measurements put stripped executables roughly in the 4–14 MiB range for GPUI, egui, Iced, Slint, and Tauri. These are small todo apps on one Mac, not a universal hello-world baseline.
- Set initial Mac goals of fresh-process first presentation p95 ≤200 ms, idle hello-app process RSS ≤50 MiB, and a stripped arm64 hello executable ≤5 MiB. These are proposed engineering budgets, not claims that every platform can already meet them.
- At 120 Hz, gate a defined workload against 8.333 ms presentation opportunities. Start with 1,000 inexpensive animated quads, a separately specified effects scene, and one million virtualized rows. An unspecified “number of animated layers” is not a useful benchmark.
- Measure physical input-to-photon on a dedicated fixture and event-to-presentation in ordinary device CI. Keep the two metrics separate. Published latency rankings change with compositor configuration, refresh rate, and measurement method.
- The <300 ms reload goal should initially cover state-preserving UI, style, asset, and tuning edits. Ordinary Rust code changes need their own rebuild budget and explicit state migration behavior.
## A. Build an interface that agents can inspect and replay
### A1. Determinism requires a complete execution contract
Playwright explicitly warns that screenshots vary with OS, browser version, hardware, power settings, and headless mode. Its screenshot assertion waits for two matching screenshots before comparing, but this is a stabilization heuristic, not a determinism guarantee. Its default perceptual threshold is 0.2. [Playwright visual comparisons](https://playwright.dev/docs/test-snapshots)
Flutter's golden matcher documents its default Ahem test font and warns that fonts can render differently across platforms and Flutter versions. Point-Free's Swift snapshot library similarly requires the same simulator for image reference comparisons. These are good reasons to pin rendering environments and retain semantic snapshots alongside pixels. [Flutter goldens](https://api.flutter.dev/flutter/flutter_test/matchesGoldenFile.html), [Swift SnapshotTesting](https://github.com/pointfreeco/swift-snapshot-testing)
**Proposed contract:** every replay artifact records the framework revision, scene revision, renderer/backend, OS image, GPU/driver, logical viewport, pixel scale, output color space, font and asset hashes, locale, text direction, seed, clock policy, and fixture versions. Fix font fallback explicitly. An unavailable font should fail the fixture instead of silently changing line wrapping.
Control these inputs through injected services:
| Input | Deterministic scene behavior | Real-device behavior |
|---|---|---|
| Monotonic clock, timers, animation tick | One manually advanced clock | Host monotonic time, with recorded display deadlines |
| Wall clock, random values, IDs | Fixed wall epoch and seeded generators | Actual services; record seeds where applicable |
| Network, files, permissions, clipboard | Named fixture responses and ordered completions | Platform integration suite |
| Async completions | Replay scheduler releases recorded completions | Normal executor; record event order |
| Fonts and images | Pinned bytes; explicit decode/upload readiness | Same assets, real upload timings |
| Window and environment | Fixed size, scale, appearance, insets, locale | Physical display and current device configuration |
| Input | Timestamped events through normal hit-testing/dispatch | OS-delivered events and real touch/HID fixture |
“Idle” must mean no pending work relevant to the requested frame. It must not mean “wait forever for all tasks,” because an app can contain polling, cursors, and perpetual animations. Expose `settle` with a bounded deadline and a diagnostic list of remaining work. Expose a separate exact-time render that deliberately permits active animations.
Use two pixel lanes:
1. **Canonical correctness:** pinned offscreen backend and environment; exact hashes where repeatable. Save expected, actual, diff, semantic tree, and layout tree on failure.
2. **Platform fidelity:** actual Metal/WebGPU/other backend with separately keyed baselines. Allow only explicitly justified regional tolerance, with changed-pixel and edge limits. Font/platform changes require their own baseline review.
Skia Gold's accepted image hashes and configuration dimensions are a useful model. It supports multiple accepted exact images as well as fuzzy/Sobel matching. Broad fuzzy thresholds can hide real damage, so they should not be the default response to nondeterministic tests. [Chromium GPU pixel tests with Gold](https://chromium.googlesource.com/chromium/src/+/main/docs/gpu/gpu_pixel_testing_with_gold.md)
A software renderer, if Rune has one, would be a useful canonical lane but cannot stand in for testing the shipping GPU renderer. Avoid committing to a second renderer solely to get screenshots before assessing the maintenance cost.
### A2. The inspector should answer causes as well as shapes
Several existing tools provide complementary pieces:
| System | Useful mechanism | Limitation or lesson |
|---|---|---|
| Flutter Inspector | Creation locations, widget/render-object inspection, constraints and layout exploration | Rune needs both logical ownership and render/layout objects, rather than pretending one tree explains everything |
| Dart VM service | Versioned JSON-RPC 2.0 over WebSocket, subscriptions, object IDs, service extensions | Make ID lifetime, version negotiation, and stream loss explicit |
| Chrome DevTools Protocol | DOM snapshot, computed CSS, full accessibility tree, input dispatch, animation controls, virtual time | Copy a coherent subset; implementing the entire web protocol would impose irrelevant semantics |
| React DevTools | Compact tree-operation messages and lazy inspection of properties | Avoid serializing every property of every node on every frame |
| SwiftUI/Xcode | Mixed SwiftUI/UIKit hierarchy inspection; invalidation diagnostics | `_printChanges` is a debugging-only, best-effort explanation, not a stable machine protocol |
| Dioxus devtools | Source keys using file/line/column/index; build/PID checks before patching | Useful patch provenance; its transport should not be mistaken for a complete geometry inspector |
Sources: [Flutter Inspector](https://docs.flutter.dev/tools/devtools/inspector), [Dart VM service specification](https://raw.githubusercontent.com/dart-lang/sdk/main/runtime/vm/service/service.md), [CDP schema](https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/master/json/browser_protocol.json), [React DevTools architecture](https://github.com/facebook/react/blob/main/packages/react-devtools/OVERVIEW.md), [SwiftUI performance](https://developer.apple.com/videos/play/wwdc2023/10160/), [Xcode hierarchy debugging](https://developer.apple.com/videos/play/wwdc2019/412/), [Dioxus devtools source](https://raw.githubusercontent.com/DioxusLabs/dioxus/main/packages/devtools/src/lib.rs).
**Proposed node record:** stable app-defined key, generation-scoped runtime ID, role/name/state, logical parent, layout parent, render parent, source location, model/layout/presentation bounds, effective clip, transform, opacity, z-order, hit-test eligibility, focus, owning state dependencies, last invalidation cause, and active animations. Properties that are expensive to compute should be requested lazily.
Keep the coordinate systems explicit: logical points versus device pixels; local, window, and screen bounds; pre-transform versus post-transform; geometry versus visible clipped geometry. A model rectangle can be correct while its presentation rectangle jumps or its effective opacity becomes zero.
Add queries for the questions an agent actually asks:
- Why is this node invisible, unclickable, clipped, or outside its parent?
- Which constraint set its width, and which ancestor supplied that constraint?
- What invalidated this subtree, and how many layout/paint passes followed?
- Which node received this input, and why did the expected node lose hit-testing?
- Which state read keeps this component subscribed, and what was the last write?
- Which animation owns this presentation property, and what happened when it retargeted?
Use accessible role/name/state queries for normal automation. Playwright's ARIA snapshots show how compact a useful semantic contract can be. Retain explicit test IDs for repeated or unnamed objects, plus stable item keys for virtualized collections. Do not use array index as list identity. [Playwright ARIA snapshots](https://playwright.dev/docs/aria-snapshots)
### A3. A small versioned protocol can serve the CLI and visual inspector
The following API is a proposed design sketch. It is not a description of an existing Rune tool. Use JSON-RPC 2.0 with generated Rust types and JSON Schema; expose stdio for a spawned scene runner and an explicitly enabled local socket/WebSocket for a running development app. Ship no listening inspector in normal release builds.
| Domain | Initial methods | Important semantics |
|---|---|---|
| Session | `hello`, `capabilities`, `subscribe` | Protocol/schema versions, build ID, scene epoch, supported operations |
| Scene | `list`, `load`, `reset`, `settle` | Named fixtures, seeded reset, bounded completion, new epoch on reset |
| Tree | `query`, `snapshot`, `inspect`, `explain` | Role/key selectors, depth limits, lazy properties, invalidation reasons |
| Input | `pointer`, `key`, `text`, `scroll`, `touch` | Timestamp, pointer identity, coordinate space, dispatched/processed frame IDs |
| Clock | `pause`, `advance`, `seek`, `setRate` | Monotonic advance; backward seek resets and replays rather than reversing physics |
| Capture | `image`, `semantics`, `layout` | Capture all three at one frame ID; explicit GPU completion/readback |
| Animation | `list`, `inspect`, `retarget` | Position, velocity, target, duration/bounce, lifecycle, property ownership |
| Trace | `start`, `stop`, `status` | Chosen channels, bounded buffers, dropped-event count, capture overhead |
| Tune | `list`, `set`, `setBatch`, `reset` | Typed descriptors, atomic batch revision, applied frame ID |
Example request and abbreviated response:
```json
{"jsonrpc":"2.0","id":17,"method":"Tree.inspect","params":{"selector":{"key":"composer.send"},"epoch":4,"fields":["source","layout","presentation","hitTest"]}}
```
```json
{"jsonrpc":"2.0","id":17,"result":{"epoch":4,"frame":73,"node":"4:208","key":"composer.send","source":{"file":"src/composer.rs","line":82},"layout":{"space":"window-points","rect":[280,640,44,44]},"presentation":{"rect":[280,648,44,44],"opacity":1},"hitTest":{"eligible":false,"reason":"covered","by":"4:219"}}}
```
Node IDs expire on removal or epoch change. A stale selection returns a structured `StaleNode` error with the observed/current epoch; it must never resolve to a newly reused allocation. Mutation requests carry the expected scene/build revision. Stream records carry sequence numbers so a client can request a fresh snapshot after a gap. Large captures return artifact handles rather than embedding megabytes of PNG data in tree messages.
The CLI is a thin client of the same protocol:
```sh
# Proposed commands, not runnable today.
rune scene list --json
rune scene run composer/send --seed 7 --clock manual --headless --out run/
rune inspect --key composer.send --fields layout,presentation,source --json
rune input pointer --phase down --x 300 --y 660 --at-ms 200
rune clock advance --ms 8.333333
rune capture --frame current --image --layout --semantics --out frame/
rune trace stop --formats native,motion-trace,perfetto --out run/
```
Use stable machine-readable stdout, diagnostics on stderr, meaningful exit status, and bounded requests. `text` injection should be separate from physical key events and IME composition so an agent does not accidentally claim keyboard/IME coverage from a direct model mutation. Semantic activation is useful for functional tests, but it does not exercise pointer routing or establish latency.
### A4. Named scenes should replay real UI with fake external services
Scrawl already has a good local example: `scrawl lab pill <scene>` replays named capsule states with a pretend recording and no mic/capture/ingest side effects. The lab supports time scaling and per-frame motion traces; tuning values reload within 250 ms. This is stronger than a gallery of inert components because it drives the transition sequence used by the app. [Scrawl's AGENTS.md](https://github.com/kitlangton/scrawl/blob/main/AGENTS.md), implementation in `scrawl/src/ui/lab.rs` and `scrawl/src/ui/motion.rs`.
Rune should let every feature register scenes next to its implementation. A scene supplies initial state, fixture services, stable keys, and an input script. Include empty/loading/error states, long text, large text settings, right-to-left layout, keyboard appearance, interruptions, rapid repeated input, resize, and background/resume when relevant.
Proposed scene manifest:
```json
{
"schema": 1,
"scene": "composer/send-interrupted",
"seed": 7,
"viewport": {"width": 390, "height": 844, "scale": 3},
"environment": {"locale": "en-US", "appearance": "dark"},
"fixtures": {"messages": "two-short", "send": "complete-at-800ms"},
"steps": [
{"atMs": 0, "input": {"activateKey": "composer.send"}},
{"atMs": 90, "input": {"activateKey": "composer.cancel"}},
{"atMs": 120, "capture": ["image", "layout", "semantics"]},
{"atMs": 500, "assert": {"key": "composer.send", "visible": true}}
]
}
```
This functional example uses semantic activation; a sibling pointer/touch scene should verify hit-testing and gesture cancellation. All operations happen through the same dispatch and animation machinery as the app. A fake transport completes a send; it does not swap in a different presentation implementation.
Record enough input and service completion data to replay a failure. Seeded random values alone do not make concurrent task scheduling reproducible. For deterministic tests, replay ordered external completions; for real-world race detection, run separate scheduling/fuzz tests.
### A5. Time control must preserve animation semantics
All springs, delays, transitions, gesture velocity calculations, and animation lifecycle decisions should read one injected monotonic clock. Keep wall time and networking deadlines separate. Pause should freeze animation without accidentally preventing the inspector from responding.
Test a transition at exact time, at a regular 60/120 Hz sample interval, and with irregular intervals. Retarget at several points while preserving current position and velocity. Test cancellation, removal/reinsertion with the same key, and reduced motion. Verify that lifecycle events occur once and that an outgoing surface remains until its visual contribution ends.
Do not implement time scaling by simply multiplying every spring parameter or by slowing some timers but not others. Advance the shared simulation clock; report both simulation and wall time. Define whether an animation uses analytic evaluation or integration and retain that definition across replay. Large time jumps must have explicit event-processing behavior.
CDP's `Emulation.setVirtualTimePolicy` and `Animation.seekAnimations`/`setPaused`/`setPlaybackRate` demonstrate the value of separate scheduling and animation controls. Rune can provide a more coherent clock because it owns both. [CDP schema](https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/master/json/browser_protocol.json)
### A6. Reuse Kit's trace tools without corrupting timing measurements
#### Scrawl's motion-trace JSONL is the initial exchange format
The current writer has a header with `type`, `launch`, `width`, `height`, `hz`, `scale`, `wall`, and optional `platform`, `clock`, `units`, `sampleHz`. Frame records use fields including `t`, `n`, `sc`, `ct`, `m`, `e`, `g`, `cm`, `c`, `cg`, `tx`, `tf`, `k`, `bg`, `s`, and `ev`. `t` is milliseconds; `ct` is seconds. Metadata entries use `{id,cls,nm,view,host,ax,pv}` and geometry entries start `[id,x,y,w,h,opacity,radius,flags]`, optionally followed by visible-rectangle values. The writer rounds geometry to 0.01 and opacity to 0.001. Sources: the internal motion linter's writer, run discovery and README.
Important compatibility detail: virtual sweeps deliberately use `hz:60` and `sc:60*dt`. A 120 Hz virtual sample therefore uses `sc:0.5`, with sampling frequency represented separately. Do not set `hz:120` in an adapter and silently change the motion linter's normalization assumptions. Validate an adapter against actual writer output and parser fixtures.
Export stable node IDs, presentation rectangles, effective opacity, visible clips, scalar channels, and transition events. Include channels for blur, mask progress, spring position/velocity, and ownership/gating where supported. Keep full-precision values in Rune's native trace because rounded motion-trace geometry is unsuitable for some numerical continuity checks.
#### The internal layout linter supplies a useful failure model
The internal layout linter reports shared-line near misses, clipping, overflow, and off-center icons. Its candidate-fix mode applies one change at a time, remeasures, and rejects changes that break previously satisfied invariants. Its scope isolation prevents comparing a transformed device stage's internal coordinates to unrelated page chrome. (the layout linter's README.)
For Rune, expose geometry so equivalent rules can run directly on layout snapshots. Return signed deltas, node keys, relevant ancestors, source locations, and the violated invariant. Do not automatically “fix” deliberate asymmetry. Let scenes declare alignment groups, allowed overlap, intentional overflow, and hit-target constraints.
#### A motion inspector supplies presentation-level evidence
A private iOS client's tooling document was recovered from Git history (revision `632aea45`) because it is absent from the current checkout. Its motion inspector's documentation describes capture of presentation geometry, opacity, transforms, blur, masks, Core Animation springs, source locations, and tunable keys. It reports approximately 0.8–2 ms/frame capture overhead, with serialization deferred until capture stops. These are historical tooling observations, not a Rune overhead target.
Reported failures caught by this tooling include duplicate morph surfaces, gaps during opacity handoffs, premature layer retirement, geometry jumps, and stacked blur overdraw. Those cases should become named Rune regression scenes. Continuity checks need property ownership and lifecycle data as well as rectangles; otherwise an intentional exit can look like a teleport or a missing surface can simply vanish from the sample set.
#### Knobs supplies the tuning interface
Knobs' remote descriptor protocol supports typed values, spring descriptors with `{duration,bounce}`, single and batched setters, and incoming synchronization without echo. Expose the same descriptor vocabulary through `Tune.*`; acknowledge the applied revision/frame so an agent knows which capture contains its change. Keep tune keys linked to source declarations and active animation IDs. ([knobs README](https://github.com/kitlangton/knobs#readme), remote controls section.)
#### Separate correctness capture from performance capture
The internal motion linter warns that walking all layers can add milliseconds per frame, that display-link probes miss render-server/GPU lateness, and that simulator hitch results are relative. A 2 ms observer would consume 24% of a 120 Hz budget. (the motion linter's README.)
Provide three modes:
| Mode | Data | Use |
|---|---|---|
| Full deterministic | Every node/property, exact state, input, screenshots on request | Correctness and explanation; no speed claims |
| Low-overhead real time | CPU spans, GPU timestamps, frame IDs, presentation feedback, counters, selected animations | Performance gates; record overhead and dropped data |
| Focused diagnosis | Selected subtree/layers and optional screenshots | Explain a known hitch; compare with the low-overhead run |
Record input arrival → dispatch → state change → layout → paint encoding → submission → GPU execution → actual presentation where the platform exposes it. Preserve clock domains and calibration uncertainty. GPU completion is not presentation, and a display callback is not proof the submitted frame was visible.
Prefer Perfetto TrackEvent protobuf for the detailed timeline; optionally export Chrome trace JSON for easy inspection. Chrome JSON has nesting constraints and is not an unrestricted event format. Tracy is a useful optional live profiler for CPU/GPU/allocations/locks, but integrate its client instead of promising an invented universal `.tracy` exporter. [Perfetto formats](https://perfetto.dev/docs/getting-started/other-formats), [conversion guidance](https://perfetto.dev/docs/getting-started/converting), [Tracy](https://github.com/wolfpld/tracy)
### A7. Rust APIs should make common agent mistakes hard to express
Zed's own contributor guidance documents incorrect context borrowing in nested closures, nested updates that panic, dropped tasks/subscriptions, missing notification after mutation, and misuse of test clocks. These are concrete failure modes in a mature Rust UI codebase. Dioxus documents runtime borrow panics when signal borrows cross `await`, and handles whose owner has already been disposed. [Zed contributor rules](https://raw.githubusercontent.com/zed-industries/zed/main/.rules), [Dioxus signals](https://dioxuslabs.com/learn/0.7/essentials/basics/signals/)
| Failure mode | Proposed Rune response |
|---|---|
| State changes without redraw | Updates invalidate automatically within a typed transaction; expose the dependency graph |
| Runtime borrow held across `await` | Async task API takes owned input snapshots and returns a message; keep UI mutation on the UI executor |
| Reentrant entity mutation | Queue an update or return a structured diagnostic with both call sites; avoid hidden nested borrowing |
| Dropped task/subscription | Explicit owner-scoped tasks and subscriptions, with visible cancellation reason and optional deliberate detach |
| Stale callback after component removal | Generation-checked weak target; cancellation tied to owner lifetime |
| List reorder resets state or motion | Required stable item keys for stateful virtualization; duplicate-key diagnostics |
| Layout depends on hidden context | Named constraints and computed provenance available through inspector |
| Model bounds mistaken for visible bounds | Separate model/layout/presentation/visible geometry in types and protocol |
| Incorrect hot-reload assumptions | Capability report says which edits patch, migrate, or restart; preserve old runnable app on failed patch |
| Examples use a different framework version | Versioned docs, small compiling examples, generated API schema, diagnostic links to installed version |
Favor small explicit operations and typed IDs over deeply generic builder types exposed in every error. Keep engine complexity behind modules. A useful compiler/runtime error names the operation, expected owner/thread/epoch, actual value, source location, and likely repair. Avoid making agents reverse-engineer a 200-line generic mismatch to discover an expired node.
The 2026 ecosystem experiment supplies additional agent-specific observations: agents had to consult vendored source because examples/docs did not match installed versions; a feature-gated Iced timer produced an unhelpful missing-function error; webview drag defaults swallowed intended events; and the GPUI example had to hand-roll a limited text input without IME/selection/clipboard. These are documented implementation experiences, not a controlled study of LLM success rates. Rune should ship a complete standard text-input path and version-matched executable examples before treating agent code generation as solved. [Interactive experiment and caveats](https://github.com/GoldStrikeArch/rust-gui-desktop-ecosystem-state/blob/main/report/11-interactive-results.md)
Dioxus distinguishes RSX/literal/asset hot reload from Rust hotpatching and changes that require rebuilding. Rune should be equally specific. “Hot reload” must not imply arbitrary Rust type-layout changes in <300 ms. [Dioxus hot reload](https://dioxuslabs.com/learn/0.7/essentials/ui/hotreload/)
## B. Published measurements support budgets, not a universal ranking
### B1. Evidence labels and measurement boundaries
The tables distinguish **reproducible-source measurements** (published harness or raw results), **reported observations** (a concrete configuration but incomplete reproduction), **speaker claims**, and **proposed targets**. Published source does not mean this research independently reran the benchmark. No framework builds or device benchmarks were run for this report.
Keep these boundaries separate:
- Fresh process versus cache-cold start versus first launch after installation.
- App entry, window creation, first GPU submission, first presentation, and interactive readiness.
- Single-process RSS, total app/process-tree RSS, physical footprint, GPU allocations, and container memory.
- Stripped executable, resources, app bundle, compressed download, installed runtime, and system-provided dependencies.
- Software event-to-screen-sample versus software event-to-presentation versus physical input-to-photon.
- Average fps, CPU frame duration, GPU duration, and missed presentation opportunities.
### B2. Startup results span different workloads and clocks
| Source and status | Workload/configuration | Published result | What it establishes |
|---|---|---|---|
| Zed March 2026 user measurement | Zed 0.226.5, M2 Pro, macOS 15.5; launch-to-first-frame log | New window/no warmup mean 258 ±78 ms; restored 273 ±51; warm 225 ±18; clean config/warm 221 ±14 | A full editor can report first frame in a few hundred ms. Occasional 1–2 s cold launches were reported but not quantified |
| September 2026 GPUI discussion, weaker report | M4 Max, 5K/144 Hz, 100k rows, 15 fresh processes | Median/p95: GPUI 152.5/159.6 ms; egui 158.1/165.2; Slint 190.2/252.4; AppKit 155.1/165.8 | Suggests an approximately 200 ms small-app budget is plausible; no linked raw harness, not cache-cold or hello-world |
| Kalbertodt 2023, reproducible comparison | Ubuntu 20.04, X11/Nvidia, OBS at 60 Hz | Tauri ≈380 ms; Iced ≈230 ms; egui ≈280 ms | Older small-app screen-based observation, platform-specific and frame-quantized |
| IronOxidizer raw results and harness | Containerized Linux toolkit samples; five launches | Iced 99 ms; egui 175 ms; Tauri 470 ms; Electron 717 ms | Startup measures image stabilization after container start, not a universal launch-to-first-present metric |
| Jacob Ras 2023 app comparison | Cat-image app, iPhone 12 mini, AppLaunch measurement | SwiftUI 1.441 s; Flutter 1.608 s | A concrete mobile app comparison; not hello-world and not directly comparable to desktop logging |
Sources: [Zed launch measurements](https://github.com/zed-industries/zed/discussions/51187), [September GPUI report](https://github.com/zed-industries/zed/discussions/63832), [2023 Rust GUI comparison](https://lukaskalbertodt.github.io/2023/02/03/tauri-iced-egui-performance-comparison.html), [IronOxidizer results](https://raw.githubusercontent.com/IronOxidizer/gui-toolkit-benchmarks/main/utils/result.json), [IronOxidizer harness](https://raw.githubusercontent.com/IronOxidizer/gui-toolkit-benchmarks/main/utils/benchmark.py), [Flutter/native/KMP app and measurements](https://github.com/jacobras/flutter-vs-native-vs-kmp).
The last source also reports a Pixel 4a Android median of 634.2 ms for Flutter versus 413.1 ms native. Keep mobile OS launch policy in view; a Mac process-start goal should not become an unexplained iPhone cold-launch promise.
### B3. Binary sizes are available; comparable hello-world idle RSS is missing
A July 2026 AI-assisted ecosystem study publishes raw measurements for identical small todo apps on M4 Pro/24 GiB, macOS 26.5.2, rustc 1.96.1. These are useful disclosed experiments, with less independent validation than a maintained benchmark suite. The following conversions use 1 MiB = 1,048,576 bytes. [Method/results](https://github.com/GoldStrikeArch/rust-gui-desktop-ecosystem-state/blob/main/report/10-empirical-results.md), [raw CSV](https://raw.githubusercontent.com/GoldStrikeArch/rust-gui-desktop-ecosystem-state/main/measurements/results-iter1.csv)
| Framework | Stripped executable, exact bytes | MiB | Clean / incremental build, seconds | Separate active-dashboard max RSS |
|---|---:|---:|---:|---:|
| GPUI | 4,467,704 | 4.26 | 56 / 1 | 79 MiB |
| egui | 11,054,344 | 10.54 | 27 / 1 | 109 MiB |
| Iced | 8,885,624 | 8.47 | 22 / 2 | 95 MiB |
| Slint | 13,873,752 | 13.23 | 42 / 4 | 95 MiB |
| Tauri | 6,682,264 | 6.37 | 36 / 10 | 211 MiB, including helpers |
Versions were GPUI 0.2.2, egui/eframe 0.35.0, Iced 0.14.0, Slint 1.17.1, and Tauri 2.11.5. In particular, the published GPUI crate does not represent every change on Zed's current main branch. Profiles used framework defaults with `strip -Sx`, rather than identical custom LTO settings.
The RSS column is the maximum over a 30-second sample of a different workload, a 10 Hz dashboard. The report explicitly did not retain a controlled idle dataset; webview helper attribution was best-effort. Do not call these idle hello-world numbers. Build caches had a warm registry but clean targets; incremental measurements after touching a source file do not prove the cost of a meaningful semantic edit. [Interactive results](https://github.com/GoldStrikeArch/rust-gui-desktop-ecosystem-state/blob/main/report/11-interactive-results.md)
Other requested frameworks and older comparison data:
| Framework/source | Available measurement | Why it does not fill the hello-world idle-RSS gap |
|---|---|---|
| Electron, IronOxidizer | Container memory 192,814 KiB; source/executable field 1 KiB; dependency-image delta 1,327,205 KiB | The 1 KiB entry is not a shipped Electron app. Docker image delta is not runtime distribution size |
| Iced, same harness | Container memory 47,397 KiB; executable 4,496 KiB | Container memory includes more than process RSS |
| egui, same harness | Container memory 52,100 KiB; executable 10,597 KiB | Same restriction; versions/platform differ from the Mac table |
| Tauri, same harness | Container memory 109,117 KiB; executable 4,918 KiB | Same restriction, including WebKit/runtime accounting |
| SwiftUI, Jacob Ras 2023 | Thinned iOS app 1.7 MB | Real cat-image app; system SwiftUI dependencies are not bundled |
| Flutter, same app | Thinned iOS app 17.9 MB | Same app/platform comparison is meaningful, but not a framework-only size |
| Makepad, 2022 talk | Desktop ZIP ≈1 MB; web Brotli ≈500 KB; UI construction ≈1 ms | Speaker claims about a particular demo; ZIP is not executable size and construction time is not launch-to-present |
| Makepad, 2025 Linux/Nvidia issue | User reported ≈300 MB for an empty release window and idle CPU activity | Bug report, not a current baseline; September 2026 closure reports idle fixes and lazy font loading |
Sources: [IronOxidizer raw data](https://raw.githubusercontent.com/IronOxidizer/gui-toolkit-benchmarks/main/utils/result.json), [measurement code](https://raw.githubusercontent.com/IronOxidizer/gui-toolkit-benchmarks/main/utils/benchmark.py), [SwiftUI/Flutter comparison](https://github.com/jacobras/flutter-vs-native-vs-kmp), [Makepad talk](https://gitnation.com/contents/makepad-leveraging-rust-wasm-webgl-to-build-amazing-cross-platform-applications), [Makepad issue #787](https://github.com/makepad/makepad/issues/787).
The critical IronOxidizer source expression is `container.stats()["memory_stats"]["usage"]`. Relabeling this field as RSS would create a false comparison. There is insufficient evidence here for a complete, current, same-device hello-world idle-RSS ranking of GPUI, egui, Iced, Slint, Tauri, Electron, SwiftUI, Flutter, and Makepad.
### B4. Input latency depends strongly on how it is measured
Typometer injects OS keyboard events and samples pixels. It measures a useful software path but excludes the physical input device and display scanout. A camera or photodiode covers a different interval. [Typometer implementation and method](https://github.com/pavelfatin/typometer)
Recomputed from matklad's published CSV, 200 samples per condition, nearest-rank p95:
| App / condition | Mean | p95 |
|---|---:|---:|
| VS Code, compositor off | 17.80 ms | 31.22 ms |
| Sublime Text 3, compositor off | 7.04 ms | 8.01 ms |
| VS Code, compositor on | 36.97 ms | 49.56 ms |
| Sublime Text 3, compositor on | 22.57 ms | 25.77 ms |
[Raw historical CSV](https://gist.githubusercontent.com/matklad/cf9080a2e6c600d05f12263b24e4b12e/raw/data.csv). These are older software measurements, not a current macOS or physical-input benchmark. The compositor difference is large enough to overwhelm many framework-level improvements.
Additional evidence:
- A 2022 VS Code latency experiment reports Typometer means at Windows/60 Hz of the proposed VS Code build 17.6 ms, Sublime 34.2 ms, and an Electron textarea with vsync disabled 16.7 ms. The author discusses the refresh-related floor and ultimately abandons the change because earlier DOM updates did not cause earlier browser rendering. This demonstrates why “Electron always has X ms latency” is not defensible. [VS Code PR #164192](https://github.com/microsoft/vscode/pull/164192)
- A weak 2026 user report gives M2 Pro means of Zed 26.3 ms, Sublime 25.9 ms, and VS Code 20.6 ms, with p95 36.8/33.5/31.7 ms. There is no raw harness, so use it only as contrary evidence against an assumed ranking. [User report](https://news.ycombinator.com/item?id=47959402)
- Historical 240 fps camera tests report VS Code at 116.7 ms on a Windows Dell XPS 13 and 95.8 ms on Ubuntu. A 240 fps camera quantizes observation at approximately 4.17 ms. These cannot be compared directly to Typometer numbers. [Is It Snappy](https://isitsnappy.com/)
- A June 2025 Flutter issue uses an FSR, photodiode, and Bela sampling at 44.1 kHz on an iPad M3 Pro. It reports basic Swift mean 67.8 ms, n=151, and basic Flutter 77.2 ms, n=209. Action semantics and application/network behavior matter; this is not a universal iPhone framework constant. [Physical touch benchmark](https://github.com/flutter/flutter/issues/170735)
- A recent Flutter touch-delivery issue reports smoothing delayed approximately 99% of packets by one vsync, alongside 120 Hz delivery-spread values around 0.18–0.21 ms. Delivery jitter is not end-to-end touch latency. [Flutter touch scheduling](https://github.com/flutter/flutter/issues/191199)
**Conclusion:** a reasonable Rune goal is minimal extra scheduling delay after input arrives, with physical qualification against an equivalent native control on the same device. Do not promise <8.33 ms physical touch-to-photon merely because rendering fits one 120 Hz frame.
### B5. “120 fps” needs an exact scene and actual presentation data
There is no defensible universal animated-layer count. One thousand opaque translated rectangles, one thousand reshaped text runs, and one thousand large blur surfaces are radically different GPU and CPU workloads. Report surface area, overlap, clips, effects, text shaping, resolution, scale, and how much changes per frame.
Robius's May 2024 benchmark provides source and xctrace scripts for a shadow-heavy iOS demo. On iPhone 12/13 running iOS 17.3, it reports Makepad at 60 fps versus Flutter/SwiftUI around 45 fps. These are 60 Hz devices, and the demo's bundled fonts were approximately 40 MB. It is useful evidence about an effects workload, not proof of 120 Hz capacity or minimal app size. [Robius benchmark](https://robius.rs/blog/performance-benchmarking-ios/)
The article titled “SwiftUI Scroll Performance: The 120FPS Challenge” actually performs its main testing at 60 Hz in Low Power Mode on iPhone 15 Pro. Its observations are useful, but the title alone is not a 120 Hz measurement. [Article and methodology](https://blog.jacobstechtavern.com/p/swiftui-scroll-performance-the-120fps)
At 120 Hz, the nominal interval is 8.333 ms. Frame work must leave room for the compositor and OS. Measure the observed presentation schedule and requested display rate, since ProMotion can vary refresh rate. CPU callback cadence alone cannot tell whether the screen displayed repeated frames.
### B6. One million rows is feasible only with explicit virtualization
LazyLayoutKit reports a one-million-item masonry workload on iPhone 14 Pro/A16/iOS 26.5.2 Release: 54 materialized items, 120 fps, p99 frame interval 8.34 ms, and approximately 2 μs query time during a 20-second recorded run. It also reports zero frames over 16.7 ms. The latter threshold alone would miss many 120 Hz deadline failures; use the p99 and raw presentation evidence rather than treating >16.7 ms as the 120 Hz criterion. [LazyLayoutKit](https://github.com/Dave861/LazyLayoutKit)
The same library reports a dense timeline at p99 33–38 ms with 17–31% of frames over 16.7 ms, and approximately 3.115 seconds for a 100k-text-item first measurement pass on A16. This is useful honesty: known-size arithmetic and first-pass arbitrary text measurement are different problems.
The 2026 Rust ecosystem study's 100k-row grids filter in roughly 1.5–6.1 ms across implementations, but one implementation materializes only 20 Slint rows. Neither row count nor filter time proves one-million-row 120 Hz scrolling. [Data-grid results](https://github.com/GoldStrikeArch/rust-gui-desktop-ecosystem-state/blob/main/report/16-data-grid-results.md)
Rune should benchmark fixed-height arithmetic indexing, variable heights with cached measurements, and previously unseen wrapped text separately. Require bounded realized nodes, stable focus/selection by item key, correct scroll anchoring when estimates change, and bounded work on jump-to-end. Test insertion and removal above the viewport, not just steady scrolling through immutable rows.
### B7. Large-file handling is mostly a data-model and scheduling problem
Zed reports include 100–300 MB log files taking seconds to open and a 43 MB JSON file stalling for 30–40 seconds on Windows. These are workload-specific user observations, not a controlled framework comparison. [Large log discussion](https://github.com/zed-industries/zed/discussions/52549), [JSON stall report](https://github.com/zed-industries/zed/discussions/45861)
A stronger primary source is Zed's August 2026 change to stream 1 MB blocks directly into its rope. For a 729 MB SQL file on Ryzen 5950X/Windows 11, the PR reports approximately 25% less peak memory and 28% less CPU. The release notes confirm the change shipped. [Zed PR #62748](https://github.com/zed-industries/zed/pull/62748), [Zed 1.17.2](https://zed.dev/releases/stable/1.17.2)
A separate gpui-component report describes 500 MB text consuming 3.2–5 GB. That editor component's storage/tokenization behavior should not be attributed to GPUI's renderer or to Zed. [gpui-component issue #2566](https://github.com/longbridge/gpui-component/issues/2566)
For Rune, the renderer contract is viewport-proportional work, incremental invalidation, cancellation, and bounded caches. A 100 MB editor demo also needs a streaming text store, deferred syntax work, and a long-line policy. Keep the demo's file-open budget separate from the renderer's frame budget.
## C. Proposed targets and automated measurement
### C1. Pin reference devices before calling a number a gate
Proposed qualification classes are an M2 Pro Mac with 16 GiB and a verified 120 Hz display mode, and an iPhone 14 Pro/A16. These choices are reference classes, not a claim that those exact devices are available. Pin the actual device, OS, toolchain, renderer, power mode, thermal state, viewport, and scale in the benchmark manifest. If the test hardware differs, establish a new baseline rather than relabeling its results.
Mac reference viewport: 1280×800 logical points at 2× for rendering workloads. iPhone: native full-screen viewport/scale, recorded explicitly. Use Release builds without inspector tree walks or video capture. Fonts and image assets remain fixed. The canonical offscreen lane runs on a pinned build worker; physical qualification runs on a dedicated device, never a developer's desk display.
All values in the following tables are **proposed initial budgets**. They need a first implementation and baseline before becoming release promises. Cross-framework evidence supports their order of magnitude, not a guarantee that Rune will achieve them.
### C2. Startup, footprint, and development budgets
| Metric / exact workload | Proposed target | Automated measurement |
|---|---|---|
| Mac hello app, fresh process, caches warm | First presentation p50 ≤150 ms, p95 ≤200 ms; interactive p95 ≤250 ms | External launcher timestamps spawn; correlate first actual presentation and successful input acknowledgment; 30 launches |
| Mac first launch after reboot, already installed | First presentation ≤500 ms in each of 5 scheduled qualification runs | Dedicated reboot sequence; retain every sample. Treat installer/quarantine first-run separately; 5 samples do not establish p95 |
| iPhone hello app, terminated app launch | OS-reported launch p95 ≤800 ms; app-entry-to-first-present p95 ≤250 ms | XCTest/Instruments plus app signposts, 30 launches; report both boundaries |
| Mac hello app idle | Process-tree RSS ≤50 MiB after 10 s settled; GPU allocations reported separately | Sample RSS over 30 s, include helpers; also retain physical footprint where available |
| iPhone hello app idle | Physical footprint ≤40 MiB after settling | Device memory metrics; keep GPU/resource accounting explicit; do not label footprint as RSS |
| Mac hello executable | Stripped arm64 ≤5 MiB; installed app/resources ≤10 MiB | Record executable bytes, bundle bytes, assets, debug symbols separately; system library dependencies listed |
| iPhone hello app size | Thinned installed app ≤10 MiB excluding optional content packs | Archive/export size report on release worker; separate download size |
| Settled UI without periodic app work | Zero framework animation ticks and GPU submissions during a 10 s sample | Internal counters after startup/cursor/animations disabled; report process CPU as a secondary noisy metric |
| Style/layout/assets/tuning reload, Mac and USB-connected iPhone | File-save-to-present p95 ≤300 ms; state preserved | At least 30 meaningful edits; timestamp save, patch, device receipt, apply, present; assert state/focus/scroll continuity |
| Ordinary Rust body edit in a small sample app | Warm incremental compile/link/restart p95 ≤2 s | Edit a consumed function body, not just `touch`; retain compiler/cache/linker versions; explicitly outside the <300 ms patch promise |
| Clean sample-app build, dependencies cached | ≤60 s on nominated build worker | Fixed job concurrency and cache state; this is a developer-cost budget, not a runtime benchmark |
The 5 MiB executable and 200 ms first-present goals are close to the published GPUI small-app range. The idle-memory budgets are deliberate goals in an evidence gap. The mobile launch and footprint budgets are provisional until measured on the reference iPhone. A framework may trade size against shaders, fonts, accessibility, or platform support; optional content packs must not hide dependencies required by the hello workload.
### C3. Frame, list, text, and latency budgets
For each 120 Hz scene below, run at least 60 seconds after a declared warmup and repeat five times. Target CPU UI work p95 ≤4 ms and GPU work p95 ≤4 ms, while separately requiring missed presentation opportunities <0.1% and no app-caused stall >25 ms. CPU and GPU times may overlap; neither their sum nor their individual percentiles establishes the presentation result. Report the full interval histogram and worst frame.
| Workload | Defined contents | Proposed additional target |
|---|---|---|
| Cheap animation | 1,000 24×24 pt rounded quads, independent spring-driven translation/opacity, no blur/shadow/text reshaping; fixed overlap seed | Meet the 120 Hz budget on both reference devices; report retarget cost separately |
| Effects animation | 12 overlapping 160×100 pt cards, 16 pt blur radius, gradient edge masks and shadows, fixed 3-layer maximum overlap | Meet the same budget; publish exact effects implementation and resolution. Do not extrapolate to 1,000 blur layers |
| Text/controls scene | 100 visible text rows with pinned font and mixed Unicode, selection/caret, fixed toolbar; scroll without reshaping unchanged runs | Meet the frame budget after glyph warmup; publish separate cold-glyph/upload measurements |
| One-million fixed-height rows | Generated data, 32 pt row height, stable keys, bounded overscan; fling, reverse, jump-to-end, mutate above viewport | Realized nodes O(viewport + overscan), ≤200 rows in reference viewport; list CPU p95 ≤1 ms; usable first viewport ≤100 ms after data source attach |
| One-million variable-height rows | Cached heights plus estimated unseen wrapped-text rows; fixed text corpus | List CPU p95 ≤2 ms in steady state; no eager million-row shaping; bounded scroll-anchor correction; report cold-measurement costs separately |
| 100 MB plain-text editor demo, Mac | Local UTF-8 file, normal lines, syntax/search deferred | First usable viewport p95 ≤250 ms with warm filesystem cache; complete indexing ≤2 s; incremental peak memory ≤2.5× file bytes plus measured empty-editor baseline |
| Pathological text | 100 MB single line; malformed input; very long grapheme sequence | Remain responsive and cancelable; report explicit truncation/chunking policy; never claim normal-line timings apply |
| Software input-to-presentation | OS event arrival to presentation of an identified changed pixel region | At 120 Hz, p95 ≤16.7 ms; dispatch-to-submit p95 ≤4 ms; phase-randomized input, at least 1,000 samples |
| Physical keyboard-to-photon, Mac | Dedicated HID trigger and photodiode, equivalent minimal text control | Provisional p95 ≤35 ms; compare native AppKit on same fixture; retain both distributions |
| Physical touch-to-photon, iPhone | Instrumented touch actuator/force trigger and photodiode; pointer-down visual response | Provisional p95 ≤80 ms and no more than one 120 Hz interval above equivalent native pointer-down control; do not mix touch-up action timings |
The physical budgets are intentionally looser than a frame interval because they include hardware and OS delivery. They are ambitious qualification targets, not derived claims about all iPhones. Measure drag tracking, touch-down feedback, and button activation separately. A button that activates on release can appear “slower” simply because the test includes finger dwell time.
For missed-frame accounting, infer expected opportunities from the display's actual rate and platform presentation feedback, with a documented timestamp tolerance. Do not call every interval above exactly 8.333000 ms a miss: clock quantization and refresh variation matter. Conversely, a >16.7 ms threshold misses single-slot failures at 120 Hz. Record rate changes and distinguish a system-downshifted display from an app that failed to deliver a requested frame.
### C4. Use a layered CI schedule
| When | Gate | Artifacts |
|---|---|---|
| Every relevant change | Deterministic scene replay, semantic/layout assertions, selected pixel goldens, spring continuity/lifecycle checks | Scene manifest, hashes, input log, tree diff, motion trace, image diff |
| Every renderer/state/scheduler change on reserved hardware | Defined animation/list scenes; startup warm-process samples; software latency; low-overhead trace | Raw samples, distributions, presentation timeline, CPU/GPU counters, machine manifest |
| Nightly or scheduled qualification | Mobile launch, cache-cold/reboot startup, physical input latency, long-run memory/cache growth | Fixture calibration, raw sensor data, all launch samples, memory timeline |
| Release | Binary/bundle size, cross-platform rendering checks, accessibility and IME/device integration | Size breakdown, platform baseline metadata, device reports |
Use both absolute budgets and paired baseline regressions. Initial regression policy: flag >10% deterioration when it also exceeds a metric-specific noise floor, such as 0.5 ms for frame work, 10 ms for startup, or 2 MiB for memory. These thresholds are policy proposals and must be calibrated from repeated baseline runs. Compare the same worker/device and interleave baseline/candidate runs where practical. Avoid universal percentage gates on tiny values.
No noisy retry-until-green policy: preserve the first failure, inspect thermal/background conditions, and rerun only with a stated reason. Store sample count, p50/p95/p99, worst value, and confidence/variability rather than one averaged score. Separate instrumentation-on versus instrumentation-off calibration; report dropped events. A proposed low-overhead trace budget is <0.2 ms/frame p95 observer cost, measured with paired runs. Full-tree captures have no such performance promise.
Physical latency requires hardware. Ordinary CI can automatically check event-to-presentation, but it cannot honestly claim input-to-photon without a sensor fixture. A high-speed camera can provide occasional external checks with stated frame quantization; a calibrated photodiode/HID or touch rig is better for automated repeated samples.
## Steal
- Flutter's source-linked layout inspection and separate logical/render concepts.
- Dart VM service's versioned RPC and subscriptions, CDP's explicit input/time controls, and React DevTools' compact updates with lazy property reads.
- Playwright's role-based selection and readable semantic snapshots, paired with pixels rather than substituted for them.
- Skia Gold's environment-keyed accepted images and explicit baseline review.
- Scrawl's named side-effect-free scene labs and one scaled animation clock.
- The motion inspector's presentation properties, property ownership, source/tunable links, and deferred serialization.
- The motion linter's format/rules, the layout linter's scope-aware invariants, and knobs' duration/bounce tuning descriptors.
- LazyLayoutKit's bounded materialization and its publication of workloads where performance degrades.
- Zed's streaming large-file approach and clear separation between loading, storage, and rendering work.
## Avoid
- Pixel tests that depend on arbitrary sleeps, system font fallback, network timing, or unspecified GPU/OS configurations.
- A screenshot-only “agent API,” pointer coordinates as the only selector, or a giant full-tree dump every frame.
- Animation tests that read target/model values while the visible presentation is elsewhere.
- Treating slowed/virtual motion as a hitch benchmark, or counting display callbacks as displayed frames.
- Unqualified “120 fps,” “cold start,” “idle memory,” or “binary size” claims.
- Treating a process exit, compilation success, or a zero-finding motion trace as proof that a visible surface exists.
- APIs that require remembering to notify after every mutation, hold runtime borrows across async work, or silently discard tasks.
- Promising arbitrary Rust hot reload in <300 ms without a proven compiler/runtime strategy.
## Recommendation for Rune
Build a small end-to-end vertical slice before expanding the widget catalog: a text field and send/cancel morph, a virtualized list, and the two animation workloads above. Give the slice stable identity, an injected clock, fixture services, semantic/layout/presentation snapshots, source-linked queries, and a motion-trace adapter. Use the same registered scenes in offscreen tests and the real Mac/iPhone app.
Keep scene state, interaction dispatch, layout, presentation, and backend submission observable at explicit boundaries. This supports agents and also exposes where runtime cost occurs. Add full Perfetto/performance instrumentation after frame IDs and clocks are coherent; otherwise traces will imply precision they do not possess.
Prioritize the <300 ms state-preserving UI patch path over general Rust hotpatching. Validate actual edit-to-present on a connected iPhone early, because serialization, transport, shader/asset upload, and preserved state are part of that budget. Retain a clear rebuild path for unsupported edits.
Rejected alternatives:
| Alternative | Reason to reject initially |
|---|---|
| Screenshot automation around a normal app as the only test interface | Cannot reliably control time, seed state, explain failures, or inspect invisible/retiring surfaces |
| Implement all of CDP | Large irrelevant web compatibility surface; a small generated protocol can expose Rune's actual model |
| Only a human visual inspector | Agents need queryable, bounded, structured operations; the GUI can be a client of the same protocol |
| Full layer tracing always enabled | Observer cost can consume a substantial fraction of the 8.333 ms frame budget |
| One “framework score” combining startup, memory, and fps | Hides workload boundaries and makes regressions difficult to diagnose |
| Mandatory new framework builds for this report | Published raw size data already answers the rough scale; new builds without a matched benchmark design would add cost without comparable evidence |
| One cross-platform pixel hash | Platform text and GPU differences make it brittle or force tolerances broad enough to miss defects |
## Open questions
1. Which exact Mac and iPhone can remain dedicated to performance qualification, and what display/power/thermal controls can the lab enforce?
2. Can the first renderer produce repeatable offscreen GPU pixels on a pinned worker, or does it need a small reference raster path for a subset of primitives?
3. What is the UI patch boundary: a compiled scene description, a data-driven view layer, dynamic code, or another representation? This determines what the <300 ms promise includes.
4. Which platforms expose reliable presentation feedback, and what proxy plus uncertainty must be reported elsewhere?
5. How much source/dependency provenance can remain available in development without adding per-frame allocation or invalidation cost?
6. Should the one-million-row and 100 MB editor workloads ship as framework examples or a separate benchmark application? The renderer should not inherit every editor data-model responsibility.
7. What exact effects scene best represents Scrawl's and the launcher's glass morph, including blur sampling and soft masks? The provisional 12-card benchmark must be replaced or supplemented by that real workload.
8. Does the internal motion linter's consumer need any schema extension for Rune's transform/mask/velocity data, or can its current scalar channels carry the first adapter without changes?
## Research scope and reproducibility notes
This report inspected local source/docs for internal motion and layout linters, Scrawl, knobs, and a private iOS client's historical motion tooling; read primary protocol/tooling documentation; examined published benchmark results and measurement code; and recomputed the cited Typometer CSV statistics. It did not independently reproduce the external performance measurements, run release-size builds, open GUI windows, or benchmark a desk display. No optional build time was consumed.
Repository links to `main` are mutable. Before using an external number as a release gate, pin its source revision and retain the harness, assets, raw data, and machine manifest in the benchmark artifact. Local relative links in this report point to sibling checkouts; the historical iOS document requires the Git revision given above.
+388
View File
@@ -0,0 +1,388 @@
# 11 — Platform Shells & Platform Order
Research for **Rune** (working title), an experimental Rust UI & animation framework for macOS, iOS, web, Windows, Linux, and Android.
Checked October 2026 against local checkouts of `winit` (`0.31.0-beta.3`), Zed's `gpui` (`gpui_macos`, `gpui_ios`, `gpui_web`, `gpui_windows`, `gpui_linux`), `makepad`, `flutter/engine`, and Kit's production apps (`scrawl`, `hex`, a private Mac launcher and a private iOS client).
---
## Summary
- **Write thin per-platform shells (`rune-macos`, `rune-ios`, `rune-web`, etc.) behind a narrow `Platform` / `PlatformWindow` trait; do not build on `winit`.** In `winit` `0.31.0-beta.3`, macOS live resize does not synchronize `CAMetalLayer` presentation with AppKit's `CATransaction`, macOS `NSTextInputClient` cannot read document context (`selectedRange` returns `NSNotFound` and `attributedSubstringForProposedRange` returns `None`), and iOS (`winit-uikit`) only implements `UIKeyInput` instead of `UITextInput`—breaking autocorrect, Japanese/Chinese IME, Dictation, Scribble, and selection handles.
- **Per-platform shells are smaller than `winit` while doing far more.** Zed's `gpui_macos` (9,711 LOC), `gpui_ios` (3,561 LOC), and `gpui_web` (6,994 LOC) are comparable in size to `winit-appkit` (8,667 LOC), `winit-uikit` (3,471 LOC), and `winit-web` (7,794 LOC), yet include full `NSTextInputClient` / `UITextInput` / hidden-`<textarea>` IME bridges, native menus, pasteboard, drag-and-drop, and `presentsWithTransaction` resize synchronization.
- **macOS 26 / iOS 26 Liquid Glass requires native backdrop views (`NSGlassEffectView` / `UIVisualEffectView` / `GlassEffectContainer`) behind or around a transparent `CAMetalLayer`.** Apple's private `CASDFElementLayer` + `CABackdropLayer` pipeline samples live desktop/wallpaper buffers behind the window that a client Metal shader cannot read. Scrawl's pill (`scrawl/src/native/pill/mod.rs:447-453, 1111-1147`) proves the exact pattern: an `NSGlassEffectView` under a transparent `CAMetalLayer` (`presentsWithTransaction = true`), updated together inside `CATransaction::begin() ... commit()`.
- **120 Hz ProMotion requires explicit frame-rate pinning on both macOS and iOS.** On macOS 14+, `NSView.displayLinkWithTarget:selector:` returns a `CADisplayLink` that adaptively throttles to 30 Hz (33.9 ms) unless `setPreferredFrameRateRange:` is pinned to `CAFrameRateRange { minimum: 120.0, maximum: 120.0, preferred: 120.0 }` (`makepad/.../macos_app.rs:1458-1482`). If using `CVDisplayLink`, keep instances immortal per `CGDirectDisplayID` (`gpui_macos/src/display_link.rs:1-86`) to avoid CoreVideo teardown segfaults. On iOS, pair `CADisplayLink.preferredFrameRateRange = CAFrameRateRangeMake(80, 120, 120)` with `CADisableMinimumFrameDurationOnPhone = YES` in `Info.plist`.
- **Incremental adoption in existing SwiftUI/UIKit apps (the iOS client, `hex`) is a first-class requirement.** Rune must work in two modes on Apple platforms: **Full-Window Shell** (Rune owns `NSApplication`/`UIApplication`) and **Embedded View** (`RuneMetalView: UIView` / `NSView` wrapped in `UIViewRepresentable` / `NSViewRepresentable`, sharing a single process-wide `MTLDevice` and `MTLCommandQueue`).
- **Native view embedding inside a Rune window should use Z-ordered underlay/overlay slots (`NSGlassEffectView` / `WKWebView` / `AVPlayerLayer` / `MKMapView`), not general-purpose interleaved slicing.** Flutter's `FlutterPlatformViewsController.mm` requires `EmbedderViewSlice` picture-recording, `OverlayLayerPool` allocations, and `FlutterTouchInterceptingView` gesture delay buffers for every interleaved platform view. Restricting embedded native views to background underlays (glass materials, video, maps) or top overlays (sheets, popovers, inspectors) eliminates intermediate GPU render targets.
- **Web in 2026 has universal WebGPU (including Safari 26 on macOS/iOS), but `EditContext` is still Chromium-only.** For web text input, steal `gpui_web`'s sliding-window hidden `<textarea>` (`gpui_web/src/ime_mirror.rs:1-198`, 512 UTF-16 code units each side of the selection, coalesced once per frame) plus an offscreen DOM accessibility mirror (`accesskit_web` pattern).
- **Ship in strict platform order: (1) macOS → (2) iOS + SwiftUI/UIKit host view → (3) Web (WASM + WebGPU) → (4) Windows → (5) Linux (Wayland-first) → (6) Android.** macOS and iOS share ~40% of their platform code (`gpui_apple`: Metal, CoreText, CoreAnimation, `dispatch2`, `objc2`) and serve all of Kit's immediate apps (`scrawl`, `hex`, the launcher and the iOS client), while Web is mandatory for interactive docs, playgrounds, and shareable demos.
---
## 1. `winit` vs Own Per-Platform Shells vs SDL3
### Codebase Size Reality Check (Measured October 2026)
| Codebase | macOS | iOS | Shared Apple | Web | Windows | Linux | Android | Total |
|---|---:|---:|---:|---:|---:|---:|---:|---:|
| **`winit` `0.31.0-beta.3`** (`winit-core`: 7,799) | 8,667 | 3,471 | — | 7,794 | 12,864 | 21,669 (WL 9,897 + X11 11,772) | 1,885 | **64,149 LOC** |
| **Zed `gpui`** (`platform.rs`: 1,731) | 9,711 | 3,561 | 3,865 | 6,994 | 13,187 | 16,422 (WL + X11 + Portals) | — | **55,471 LOC** |
`winit` is not smaller than a purpose-built GUI shell—it is larger, because it carries generality for game engines, legacy OS versions, and raw window handle permutations while omitting the exact primitives a UI toolkit needs (menus, clipboard, drag-and-drop, system dialogs, native backdrop views, and document-aware IME).
### Where `winit` (`0.31.0-beta.3`) Fails a High-Craft UI Framework
1. **macOS IME (`NSTextInputClient`) is stateless and broken for context-aware input:**
In `winit/winit-appkit/src/view.rs:344-414`:
- `selectedRange` (`lines 384-387`) unconditionally returns `NSRange { location: NSNotFound, length: 0 }` with a `// TODO` comment.
- `attributedSubstringForProposedRange` (`lines 344-351`) unconditionally returns `None` (`// TODO`).
- `insertText:replacementRange:` (`lines 285-310`) ignores `_replacement_range` (`// TODO: Implement replacement_range`).
- Without `selectedRange` and `attributedSubstringForProposedRange`, macOS inline predictive text, press-and-hold accents, Japanese/Chinese reconversion, and Emoji replacement (`Ctrl+Cmd+Space` replacing a word) fail or insert at the wrong offset.
- Compare `gpui_macos/src/window.rs:2125-2258`, which routes `selectedRange`, `markedRange`, `attributedSubstringForProposedRange`, `insertText:replacementRange:`, `setMarkedText:selectedRange:replacementRange:`, and `firstRectForCharacterRange:` directly to the focused widget's `PlatformInputHandler`.
2. **iOS (`winit-uikit`) has no `UITextInput` implementation at all:**
In `winit/winit-uikit/src/view.rs:94-156`, `WinitView` only implements the minimal `UIKeyInput` protocol (`hasText`, `insertText:`, `deleteBackward`), and `insertText:` (`lines 102-135`) loops `.chars()` to synthesize fake `WindowEvent::KeyboardInput` key-down/key-up events.
- Because it does not implement `UITextInput` (`textInRange:`, `replaceRange:withText:`, `selectedTextRange`, `markedTextRange`, `setMarkedText:selectedRange:`, `tokenizer`), iOS disables multistage CJK IME composition, autocorrect replacement spans, inline predictive text, Dictation, Scribble (Apple Pencil), and native Loupe/selection drag handles.
- Compare `gpui_ios/src/ios/text_input.rs:1-1180`, which implements all 30+ `UITextInput` selectors in Rust on `GPUITextInputView` with generation-stamped `GPUITextPosition` / `GPUITextRange` objects so UIKit's async text-system queries never apply stale ranges after app state changes.
3. **macOS Live Resize Jank and `RunLoop` Re-entrancy:**
During interactive window edge dragging on macOS, AppKit spins a modal nested run loop inside `-[NSWindow _resizeWithEvent:]` in `NSEventTrackingRunLoopMode`.
- `winit-appkit` (`observer.rs`) uses `CFRunLoop` before-waiting/after-waiting observers to synthesize `RedrawRequested`, which fights AppKit's synchronized `CATransaction` resize pass unless the view implements `displayLayer:` with `CAMetalLayer.presentsWithTransaction = true`.
- In `gpui_macos/src/window.rs:2260-2285`, the content view implements `wantsUpdateLayer -> YES` and `displayLayer:`. During `displayLayer:`, GPUI stops its display link, flips `metal_layer.set_presents_with_transaction(true)` (`gpui_macos/src/metal_renderer.rs:297-300`), renders synchronously at the new `bounds` and `backingScaleFactor`, calls `command_buffer.waitUntilScheduled()`, calls `drawable.present()`, and restores `presentsWithTransaction = false` when the display link resumes (`window.rs:2058-2075`). The window frame and Metal content resize in the exact same WindowServer commit with zero rubber-banding or black gutter.
4. **Embedded View Mode (`UIViewRepresentable` / `NSViewRepresentable`):**
`winit` assumes ownership of `UIApplicationMain` (`winit-uikit/src/event_loop.rs`) or `NSApplication` activation policy and delegate (`winit-appkit`). Embedding a single Rune canvas inside an existing SwiftUI screen in the iOS client or `hex` is awkward and unsupported in `winit`, whereas a thin `RuneHostView` (`UIView` / `NSView`) shares 90% of `rune-ios` / `rune-macos`'s windowing/input/rendering code without owning `UIApplication`.
5. **SDL3 (`sdl3-sys`):**
SDL3 improved GPU and high-DPI APIs over SDL2 and added `SDL_AddEventWatch` for live resize callbacks, but it remains a C game runtime: it lacks native macOS `NSGlassEffectView` / `NSPanel` vibrancy integration, full document-context `UITextInput` on iOS, native macOS `NSMenu` responder-chain validation, and web accessibility trees, while adding a C build dependency across every target.
---
## 2. macOS Deep Dive (`rune-macos`)
### Windowing (`NSWindow`, `NSPanel`, Traffic Lights, Fullscreen, Key Status)
- **Standard vs Floating Utility Windows:**
Support two window classes in `rune-macos` (`gpui_macos/src/window.rs:197-205`):
- `GPUIWindow: NSWindow` for standard document/app windows.
- `GPUIPanel: NSPanel` for floating overlays, HUDs, pills, and launchers (`NSWindowStyleMaskNonactivatingPanel`, `collectionBehavior = CanJoinAllSpaces | FullScreenAuxiliary`, `level = NSFloatingWindowLevel` or `NSPopUpMenuWindowLevel` (`101`)).
- **Non-Activating Key Input & Cold-Start Warm-Up:**
- In both Scrawl (`scrawl/src/native/pill/mod.rs:342-358`) and the launcher (`launcher/native/Launcher.swift:26-44`), subclass `NSPanel` to override `canBecomeKeyWindow -> YES` and `canBecomeMainWindow -> NO`. This allows typing and Escape/shortcut handling in a floating launcher or recording pill without stealing active-app status from the user's frontmost app.
- **Cold-start warm-up:** On first launch, `NSPanel` + Metal/SwiftUI shader compilation can cause a 1-frame flash. The launcher (`launcher/native/Launcher.swift:566-578`) solves this by setting `panel.alphaValue = 0`, calling `orderFrontRegardless()` + `layoutIfNeeded()`, then `orderOut(nil)` and restoring `alphaValue = 1` at startup.
- **Traffic Lights & Titlebar Integration:**
- Use `NSWindowStyleMaskTitled | NSWindowStyleMaskFullSizeContentView` with `titlebarAppearsTransparent = YES` and `titleVisibility = NSWindowTitleHidden`.
- Override `layout` in the `NSWindow`/`NSPanel` subclass or inspect `standardWindowButton:` (`NSWindowCloseButton`, `NSWindowMiniaturizeButton`, `NSWindowZoomButton`) to position the traffic lights at a custom inset (`gpui_macos/src/window.rs:780-865`) and report `WindowControls` geometry to Rune's layout engine so app toolbars automatically pad around traffic lights (and shrink that padding to `0` when entering native fullscreen via `windowWillEnterFullScreen:` / `windowDidExitFullScreen:`).
- Support native double-click-on-titlebar (`AppleMiniaturizeOnDoubleClick` / `performMiniaturize:` / `zoom:`) and `window.performWindowDragWithEvent:` when dragging an empty toolbar region.
### Liquid Glass (`NSGlassEffectView` on macOS 26) + `CAMetalLayer` Composition
Apple's macOS 26 (`Tahoe`) introduced `NSGlassEffectView` (and `NSGlassEffectContainerView` for metaball-style merging of adjacent glass elements).
- **Why a pure Metal shader cannot replicate native Liquid Glass:**
Inside WindowServer, `NSGlassEffectView` builds a layer tree containing `SDFLayer` + `CABackdropLayer` + `CASDFElementLayer`. WindowServer composites the live desktop wallpaper and windows *behind* your `NSWindow` into that `CABackdropLayer` with chromatic refraction and specular rim lighting before compositing your window's layers on top. A client process's `CAMetalLayer` has no read access to behind-window pixels without ScreenCaptureKit permissions and 1-frame latency.
- **How Scrawl composites `NSGlassEffectView` + `CAMetalLayer` in lockstep (`scrawl/src/native/pill/mod.rs`):**
1. **View Hierarchy (`lines 422-455, 644-675`):**
`panel.contentView` (`FlippedRootView`, `wantsLayer = YES`) contains:
- **Underlay:** `NSGlassEffectView` (`setStyle: 0` for Regular or `1` for Clear, `setCornerRadius: h * 0.5`, `setTintColor: NSColor(srgb: 0.04, 0.04, 0.06, 0.25)`).
- **Overlay:** `PillInteractiveView` (`wantsLayer = YES`), hosting a `CAMetalLayer` (`opaque = NO`, `pixelFormat = MTLPixelFormatBGRA8Unorm`, `framebufferOnly = YES`, `presentsWithTransaction = YES`).
2. **Critical AppKit Initialization Quirk (`lines 447-453`):**
`window.displayIfNeeded()` **must** be called once on the main thread while `glass_view` is non-hidden (`alphaValue = 0.0`) so AppKit executes its first `updateLayer` pass and constructs the internal `SDFLayer` + `CABackdropLayer` + `CASDFElementLayer` tree. If `glass_view` starts with `isHidden = YES`, AppKit skips building the backdrop layers until the first visible frame, causing a un-refracted pop.
3. **Zero-Lag Synchronized Morphing (`lines 1111-1147`):**
When the pill morphs size, position, or corner radius at 120 Hz, updating `NSGlassEffectView` outside the Metal frame causes a 1-frame tear between the glass capsule and the GPU-rendered waveform/controls inside it. Scrawl eliminates this by wrapping both in a single explicit `CATransaction`:
```rust
CATransaction::begin();
CATransaction::setDisableActions(true);
// 1. Update NSGlassEffectView frame, cornerRadius, alphaValue + layoutSubtreeIfNeeded()
self.sync_glass_view(glass_rect, corner_radius, glass_alpha, ...);
// 2. Encode Metal render pass into CAMetalDrawable (with clearColor = 0,0,0,0)
// ...
cmd.commit();
cmd.wait_until_scheduled();
drawable.present(); // Because presentsWithTransaction = true, waits for CATransaction::commit()
CATransaction::commit();
```
4. **Fallback on macOS 14–15:** Fall back cleanly to `NSVisualEffectView` (`material = HUDWindow` or `UnderWindowBackground`, `blendingMode = BehindWindow`, `state = Active`) with a `CAShapeLayer` mask.
### Frame Pacing & ProMotion (120 Hz) on macOS
There are two display-link APIs on macOS, each with a sharp edge discovered in our reference codebases:
1. **`NSView.displayLinkWithTarget:selector:` (`CADisplayLink`, macOS 14+):**
Used by Makepad (`makepad/platform/src/os/apple/macos/macos_app.rs:1458-1482`).
- **Gotcha:** By default on ProMotion MacBook Pros, macOS's `CADisplayLink` uses adaptive frame pacing and drops to **30 Hz (33.9 ms)** when it does not detect native CoreAnimation layer animations!
- **Fix (`macos_app.rs:1464-1474`):** Query `window.screen.maximumFramesPerSecond` (120 on ProMotion) and immediately call:
```rust
let rate = max_fps as f32;
let range = CAFrameRateRange { minimum: rate, maximum: rate, preferred: rate };
let _: () = msg_send![display_link, setPreferredFrameRateRange: range];
```
2. **`CVDisplayLink` (CoreVideo):**
Used by GPUI (`gpui_macos/src/display_link.rs:1-86`).
- **Gotcha:** Stopping and deallocating a `CVDisplayLink` when a window closes or switches monitors races with CoreVideo's high-priority background thread and causes intermittent segfaults inside `CVDisplayLink::runIOThread` (`ZED-7XR`, Zed PR `#32116`).
- **Fix (`display_link.rs:16-75`):** Maintain a process-global `Mutex<BTreeMap<CGDirectDisplayID, ImmortalDisplayLink>>` that creates at most one `CVDisplayLink` per display ID, never drops it, and uses `CVDisplayLinkStart` / `CVDisplayLinkStop` with reference counting across active windows on that display.
- **Recommendation for Rune:** Require macOS 14+ and use `NSWindow`/`NSView.displayLinkWithTarget:selector:` (`CADisplayLink`), which runs directly on the main run loop without cross-thread dispatch latency, and pin `preferredFrameRateRange` to `(80.0, max_fps, max_fps)` while animations or gestures are active.
### Pointer, Trackpad Momentum, Gesture Phases & Force Touch
- **`NSTrackingArea`:** Install an `NSTrackingArea` with `NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited` (`gpui_macos/src/window.rs:640-655`) so cursor changes and hover states work even when a floating panel or unfocused window is hovered.
- **Scroll Phases (`phase` vs `momentumPhase`):**
macOS `NSEventTypeScrollWheel` carries two distinct `NSEventPhase` bitmasks:
- `event.phase`: physical finger contact on the trackpad (`Began`, `Changed`, `Stationary`, `Ended`, `Cancelled`, or `MayBegin` when two fingers rest on the trackpad before moving).
- `event.momentumPhase`: synthetic inertial scroll events generated by macOS after fingers lift (`Began`, `Changed`, `Ended`).
- **Crucial detail:** When a user flicks a scroll view on a Mac trackpad and then puts two fingers back down on the trackpad, AppKit sends `event.phase == NSEventPhaseMayBegin` (and an `Ended` on the previous `momentumPhase`). Rune must expose both `phase` and `momentum_phase` plus `hasPreciseScrollingDeltas` (`scrollingDeltaX`/`Y` in points vs line ticks for notched mouse wheels) so custom spring/scroll physics can immediately interrupt momentum on finger touch-down.
- **Magnify, Rotate, SmartMagnify & Force Touch:**
- Forward `magnifyWithEvent:` (`event.magnification`, `event.phase`), `rotateWithEvent:` (`event.rotation`), `smartMagnifyWithEvent:` (two-finger double-tap to zoom), and `pressureChangeWithEvent:` (`event.pressure` in `0.0..=1.0`, `event.stage` `1` = click, `2` = deep press / Force Touch) plus `NSHapticFeedbackManager::defaultPerformer().performFeedbackPattern:performanceTime:` for tactile detents when scrubbing sliders or snapping alignment guides.
### Menus, Menu-Bar Extras, Clipboard, Drag-and-Drop & Services
- **Menus & Responder Chain:** Build real `NSMenu` / `NSMenuItem` trees (`gpui_macos/src/menu.rs`) wired to an action selector that queries `validateMenuItem:` against Rune's focused responder chain. This gives macOS native Help-menu search, native keyboard shortcut learning, and native context menus (`NSMenu::popUpContextMenu:withEvent:forView:`) for free.
- **Menu-Bar Extras (`NSStatusItem`):** Provide a first-class `StatusItem` API on `rune-macos` (`NSStatusBar::systemStatusBar().statusItemWithLength(NSVariableStatusItemLength)`) that can either show a native `NSMenu` or anchor a borderless `NSPanel` popover below the status bar button's `window.frame`.
- **Clipboard (`NSPasteboard`) & Drag-and-Drop (`NSDraggingDestination` / `NSDraggingSource`):**
Register `NSPasteboardTypeString`, `NSPasteboardTypeFileURL`, `NSPasteboardTypePNG`, `NSPasteboardTypeTIFF`, and custom UTI types (`window.registerForDraggedTypes:`). Implement `draggingEntered:`, `draggingUpdated:`, `draggingExited:`, and `performDragOperation:` (`gpui_macos/src/window.rs:2338-2435`) to convert external file/image/text drops into `PlatformInput::FileDrop` events with cursor coordinates.
- **Services & Quick Look:** Forward `validRequestorForSendType:returnType:` for macOS Services and `acceptsPreviewPanelControl:` / `beginPreviewPanelControl:` (`QLPreviewPanel`, as in `launcher/native/Launcher.swift:46-75`) so pressing Space on a file item opens native Quick Look.
---
## 3. iOS Deep Dive (`rune-ios`)
### Lifecycle (`UIApplication`, `UIScene`), `CAMetalLayer` & 120 Hz ProMotion
- **`UIScene` Lifecycle:** Modern iOS (and iOS 26+) requires scene-based lifecycle (`UIWindowSceneDelegate`) rather than legacy `UIApplicationDelegate.window` (`gpui_ios/src/ios/application.rs:145-315`).
- **`CAMetalLayer` Backing:** Subclass `UIView` (`RuneMetalView`) and override `+ (Class)layerClass` to return `[CAMetalLayer class]` (`gpui_ios/src/ios/window.rs:84-98`). Set `view.contentScaleFactor = UIScreen.mainScreen.nativeScale` (or `windowScene.screen.nativeScale`) and update `metalLayer.drawableSize` inside `layoutSubviews` so rotation and iPad Stage Manager / Split View resizes are synchronous.
- **120 Hz ProMotion on iPhone & iPad:**
Two pieces are required—missing either locks the app to 60 Hz:
1. `Info.plist` **must** include `<key>CADisableMinimumFrameDurationOnPhone</key><true/>`. Without this key, iPhone Pro displays ignore `CADisplayLink` requests above 60 Hz for third-party Metal views.
2. On the `CADisplayLink` instance, call `setPreferredFrameRateRange:` with `CAFrameRateRangeMake(80.0, 120.0, 120.0)` during active animations/scrolls, and pause (`setPaused:YES`) when the scene is idle (`gpui_ios/src/ios/application.rs:331-340` currently omits `setPreferredFrameRateRange:`, leaving a ProMotion gap we should fix in Rune).
- **Concentric Corner Radius (iOS 26):** Use `UICornerConfiguration::containerConcentricRadius()` (`gpui_ios/src/ios/window.rs:391-425`) to read the hardware screen bezel corner radius so edge-aligned sheets and cards match the physical display curvature.
### Safe Areas, Keyboard Avoidance & Interactive Keyboard Dismissal
- **Safe Areas:** Observe `safeAreaInsetsDidChange` on the root `UIView` and feed `WindowInsets { top, left, bottom, right }` in logical points to Rune's layout root (`gpui_ios/src/ios/window.rs:342-389`).
- **Keyboard Avoidance & Interactive Frame Tracking:**
Subscribe to `UIKeyboardWillChangeFrameNotification` / `UIKeyboardDidChangeFrameNotification` (`gpui_ios/src/ios/window.rs:285-338`), converting `UIKeyboardFrameEndUserInfoKey` into the view's coordinate space (`convertRect:fromCoordinateSpace:`) and reading `UIKeyboardAnimationDurationUserInfoKey` and `UIKeyboardAnimationCurveUserInfoKey` (curve `7` is Apple's private CASpringAnimation curve).
- **Better on iOS 16+ / iOS 26:** Attach a constraint or observation to `view.keyboardLayoutGuide.followsUndockedKeyboard = YES` (`UIKeyboardLayoutGuide` / `UITrackingLayoutGuide`), which tracks the keyboard frame *frame-by-frame* during interactive scroll-to-dismiss gestures (`UIScrollViewKeyboardDismissModeInteractive`).
### Text Input (`UITextInput`), Selection Handles, Dictation & Scribble
- Do **not** use `UIKeyInput`. Use `gpui_ios/src/ios/text_input.rs` as the blueprint:
- Implement `UITextInput` + `UITextInputTraits` directly on the Metal host view (or a dedicated responder subview).
- Stamp custom `UITextPosition` and `UITextRange` Objective-C subclasses with a monotonically increasing `session_token: u64` (`text_input.rs:42-198`) that increments whenever the underlying Rust text buffer mutates outside UIKit's knowledge. Any stale range UIKit queries returns `nil` instead of panicking on out-of-bounds UTF-16/UTF-8 slicing.
- Before changing selection or text from Rust, bracket the mutation with `[inputDelegate selectionWillChange:self]` / `[inputDelegate selectionDidChange:self]` or `textWillChange:` / `textDidChange:`.
- Implement `firstRectForRange:` and `selectionRectsForRange:` returning `UITextSelectionRect` objects so iOS draws native floating autocorrect bubbles, the magnifying Loupe, Dictation glow, and Apple Pencil Scribble previews at the exact glyph bounds rendered by Rune's GPU text engine.
### Scroll Physics & Gesture Recognizers: Native vs Custom
- **Scroll Physics (`UIScrollView` vs Custom):**
iOS users immediately notice non-native scroll deceleration or rubber-banding. Rather than embedding hidden `UIScrollView` instances for every scrollable list, replicate Apple's exact analytical scroll equations in Rust:
- **Deceleration:** Exponential decay with `UIScrollViewDecelerationRateNormal = 0.998` per millisecond (`v(t) = v_0 * 0.998^t`, stopping threshold `|v| < 0.05 pt/ms`).
- **Overscroll Rubber-Banding:** `offset = (1.0 - (1.0 / ((distance * 0.55 / dimension) + 1.0))) * dimension` (constant `c = 0.55`), transitioning into a critically damped spring (`ζ = 1.0`, response `~0.45s`) on release or boundary impact.
- **Gesture Disambiguation (`UIGestureRecognizer` Interop):**
- Install a `UIScreenEdgePanGestureRecognizer` (`edges = UIRectEdgeLeft`) on the root view (`gpui_ios/src/ios/window.rs:248-275`) so system/navigation back-swipe gestures work naturally.
- When Rune is hosted inside a UIKit/SwiftUI `NavigationStack` or `UIScrollView`, implement `UIGestureRecognizerDelegate` (`gestureRecognizerShouldBegin:` and `gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:`) on a touch-forwarding recognizer on `RuneMetalView` so Rune can claim horizontal drags (e.g., scrubbing a timeline or carousel) while letting vertical drags or left-edge back-swipes pass through to the parent SwiftUI/UIKit container.
### Haptics & Dynamic Type
- **Haptics:** Wrap `UIImpactFeedbackGenerator` (`Light`, `Medium`, `Heavy`, `Soft`, `Rigid`), `UISelectionFeedbackGenerator`, and `UINotificationFeedbackGenerator` behind a zero-allocation `PlatformWindow::trigger_haptic(HapticPattern)` method, plus `CHHapticEngine` (CoreHaptics) for continuous texture/transient curves synced to spring velocity.
- **Dynamic Type:** Read `UITraitCollection.currentTraitCollection.preferredContentSizeCategory` and observe `UIContentSizeCategoryDidChangeNotification` (`registerForTraitChanges:@[UITraitPreferredContentSizeCategory.self]`). Expose the user's Dynamic Type scale factor (`UIFontMetrics.defaultMetrics.scaledValueForValue:`) to Rune's style system.
### Platform View Embedding & Bidirectional Hosting (Incremental Adoption in the iOS Client / Hex)
#### How Existing Frameworks Embed Native Views (and the Cost)
- **Flutter (`FlutterPlatformViewsController.mm:46-210`, `FlutterPlatformViews_Internal.h:23-160`):**
Uses Hybrid Composition. When a Dart widget tree places a native `UIView` (`WKWebView`, `MKMapView`) between two Flutter widgets:
1. The raster thread slices the display list around the platform view (`EmbedderViewSlice`), rendering background widgets to the base `CAMetalLayer` and foreground widgets into a pooled `FlutterOverlayView` (`OverlayLayerPool`) allocated as an extra full-size `CAMetalLayer` above the `UIView`.
2. Every clip path on the platform view requires a `FlutterClippingMaskView` (`UIView.maskView`), which forces an offscreen CoreAnimation alpha mask pass.
3. Every touch goes through `FlutterTouchInterceptingView`, which buffers `UITouch` sequences on the main thread until the Dart UI thread replies over an async hop whether its gesture arena won or lost.
- **Compose Multiplatform (`UIKitView` / `UIKitViewController`):**
Places native `UIView`s in an overlay/underlay `UIView` container synchronized in `layoutSubviews`, punching a transparent hole (`BlendMode.Clear`) into the Skia/Metal canvas when using an underlay.
- **React Native (Fabric):**
Every component *is* a `UIView`, so embedding is free, at the cost of no unified custom GPU canvas and main-thread `UIView` layout overhead.
#### Rune's Bidirectional Strategy
1. **Hosting Rune inside SwiftUI / UIKit (`RuneHostView` — Priority #1 for the iOS client and `hex`):**
- Provide a C-ABI / Swift package wrapper (`RuneKit`) exposing `RuneUIView: UIView` and `RuneView: UIViewRepresentable` (and `RuneNSView` on macOS).
- **Shared GPU Context:** Multiple `RuneUIView` instances in an existing SwiftUI app (e.g., an animated voice orb in `hex`, a streaming code/diff canvas or canvas diagram in the iOS client) share a single singleton `WgpuContext` / `MTLDevice` / `MTLCommandQueue` and glyph atlas in Rust, while each `RuneUIView` owns a lightweight `CAMetalLayer` surface and participates in a single shared `CADisplayLink`.
- **Intrinsic Size & Transparent Background:** `RuneUIView` sets `isOpaque = NO`, `layer.opaque = NO`, and supports `sizeThatFits:` / `intrinsicContentSize` driven by Rune's layout pass so SwiftUI's `ScrollView` or `VStack` can size a Rune component naturally.
2. **Embedding Native Views inside Rune (Underlay / Overlay Slots):**
- Instead of Flutter's arbitrary N-layer `EmbedderViewSlice` interleaving, support two explicit native-view slots per Rune window:
- **Underlay slot** (behind the transparent `CAMetalLayer`, with Rune punching an alpha-0 cutout rect + corner radius in its Metal pass): used for `NSGlassEffectView` / `UIVisualEffectView` (Liquid Glass), `AVPlayerLayer` (zero-copy hardware video), and `MKMapView`.
- **Overlay slot** (child `UIView`/`NSView` positioned above the `CAMetalLayer` synced inside `CATransaction`): used for `WKWebView`, `PHPickerViewController`, `PKCanvasView`, or native sheets/popovers.
- Because Rust runs on the main UI thread (unlike Flutter's separate Dart UI / Raster threads), touch routing and `CATransaction` frame syncing happen **synchronously on the same thread** with zero `FlutterTouchInterceptingView` buffering latency.
### Liquid Glass on iOS 26
As documented in `ios-client/OpenCode/Glass.swift:1-59` and `ios-client/docs/native-ui-guidance.md:11-34`:
- iOS 26 introduces `GlassEffectContainer`, `.glassEffect(glass.interactive(), in: shape)` in SwiftUI, and `UIGlassEffect` / `UIGlassContainerEffect` in `UIVisualEffectView` for UIKit.
- When Rune runs in **Embedded View** mode inside the iOS client, SwiftUI toolbars and floating composer pills use native `OpenCodeGlassContainer` / `.openCodeGlass(in:)` while Rune renders content surfaces or interactive visualizations.
- When Rune owns the full window on iOS 26, `rune-ios` can instantiate `UIVisualEffectView(effect: UIGlassEffect.regular)` in the **Underlay slot** behind the transparent `CAMetalLayer` using the exact same `CATransaction`-synced architecture as Scrawl's macOS pill.
### Rust-to-iOS Build & Deploy Ergonomics
Inspected across `hex/ios/project.yml` and `ios-client/project.yml`:
- **Avoid `cargo-mobile2` and `dx bundle` for serious iOS work:** They generate brittle template Xcode projects that break as soon as an app adds Share Extensions (`OpenCodeShare`), Custom Keyboard Extensions (`HEXKeyboard`), App Groups, or Xcode Cloud (`ci_scripts/ci_post_clone.sh`).
- **Recommended Pipeline (`XcodeGen` + `cargo` staticlib/XCFramework + `xcrun devicectl`):**
1. Define the Xcode project declaratively in `project.yml` (`XcodeGen`, used in both `hex` and the iOS client).
2. Compile Rust as a `staticlib` (`librune_app.a`) for `aarch64-apple-ios` (device) and `aarch64-apple-ios-sim` (simulator) with a header/Swift bridge (`objc2` when Rust owns `main`, or `uniffi` / `@_cdecl` C-ABI when Swift owns `@main`).
3. For simulator iteration: `cargo build --target aarch64-apple-ios-sim` → `xcodebuild` → `xcrun simctl install booted ... && xcrun simctl launch booted ...`.
4. For physical iPhone ProMotion testing: `xcrun devicectl device install app --device <id> <App.app>` + `xcrun devicectl device process launch --device <id> --console <bundle-id>` gives sub-5-second incremental deploy and live stdout/stderr streaming over USB-C or Wi-Fi.
---
## 4. Web Deep Dive (`rune-web`)
### WebGPU in 2026
- **Browser Support:** As of 2026 (including **Safari 26** on macOS 26 and iOS 26, Chrome 113+, Edge 113+, and Firefox 141+), WebGPU (`navigator.gpu`) is enabled by default across all major desktop and mobile browsers.
- **Fallback:** Keep `wgpu`'s WebGL2 backend as a compile-time/runtime fallback (`Backends::BROWSER_WEBGPU | Backends::GL`) only for legacy corporate/Linux browsers or headless test environments without WebGPU adapters.
- **High-DPI Canvas Sizing (`ResizeObserver` `devicePixelContentBoxSize`):**
As implemented in `gpui_web/src/window.rs:161-163, 455-510`, attach a `ResizeObserver` with `{ box: "device-pixel-content-box" }` (falling back to `contentRect * window.devicePixelRatio` on browsers lacking `devicePixelContentBoxSize`). This prevents 1-pixel rounding blur at fractional browser zoom levels (e.g., 110%, 125%).
### Canvas vs DOM Hybrid & Native Scroll Feel
- Render UI into a full-viewport `<canvas tabindex="-1" style="touch-action: none; user-select: none;">` (`gpui_web/src/window.rs:114-135`).
- **Trackpad vs Mouse Wheel on Web:** Browser `WheelEvent`s do not expose macOS's `phase` / `momentumPhase` directly. Distinguish trackpads from discrete mouse wheels using `event.deltaMode == WheelEvent.DOM_DELTA_PIXEL` + fractional/high-frequency deltas vs `DOM_DELTA_LINE`, and detect pinch-to-zoom via `wheel` events with `event.ctrlKey == true` (the standard convention browsers use for trackpad two-finger pinch).
### Text Input on Web: Hidden `<textarea>` Sliding Mirror vs `EditContext`
- **`EditContext` status in 2026:** The W3C `EditContext` API is shipped in Chromium (Chrome/Edge 121+), where it cleanly decouples IME composition from the DOM. However, **Safari 26 (WebKit) and Firefox still do not support `EditContext`**, meaning any production web shell must maintain a hidden DOM input element.
- **The Right Architecture — Steal `gpui_web/src/ime_mirror.rs` (`lines 1-198`):**
- Naively using an empty hidden `<input>` breaks mobile soft keyboards (iOS Safari, Android Gboard) because backspace, swipe-typing, and autocorrect inspect the text surrounding the caret before emitting edits.
- `gpui_web`'s `ImeMirror` creates a fixed `1px × 1px`, `opacity: 0`, `font-size: 16px` `<textarea>` (using `16px` prevents mobile Safari/Chrome from auto-zooming the viewport on focus; using `<textarea>` instead of `<input>` prevents the browser from silently stripping `\n`).
- On touch devices (`matchMedia("(pointer: coarse)")`), it sets `inputmode="none"` until the user completes a tap (not a scroll pan!) on an editable widget (`window.rs:81-86`, `ime_mirror.rs:119-123`).
- It mirrors a sliding window of `CONTEXT_CHARS = 512` UTF-16 code units before and after the current selection (`ime_mirror.rs:40-48`), and coalesces writes to the `<textarea>` at most once per event-loop turn (`schedule_sync`) because every write to `textarea.value` restarts the browser's IME connection.
### Accessibility on Web (DOM Mirror / AccessKit)
- A raw `<canvas>` is invisible to VoiceOver, NVDA, and browser Find-in-Page.
- Synchronize Rune's `accesskit::TreeUpdate` into a visually hidden (`opacity: 0; pointer-events: none; position: absolute`) ARIA DOM subtree positioned over the canvas (using `accesskit_web` or a lightweight semantic DOM projector) so screen readers, Tab navigation, and mobile accessibility gestures highlight exact widget bounding boxes.
### WASM Binary Size, Startup & Threading (`SharedArrayBuffer` / COOP-COEP)
- **Single-Threaded Default on Web:** Requiring `SharedArrayBuffer` (for WASM pthreads / `rayon`) forces every host page to serve `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` headers. Those headers break embedding Rune demos inside documentation sites, GitHub Pages, iframes, or third-party blogs.
- **Rule:** Rune's core layout, animation, and rendering pipeline on `wasm32-unknown-unknown` **must run cleanly on the main browser thread without `SharedArrayBuffer`** (`ForegroundExecutor` + `BackgroundExecutor` backed by browser microtasks / `postMessage` / optional Web Workers via message passing, as in `gpui_web/src/dispatcher.rs`).
- **Binary Size Budget:** Strip debug symbols, compile with `opt-level = "z"` or `"s"` + `lto = "fat"` + `wasm-opt -Oz`, and dynamically stream-load fonts rather than embedding multi-megabyte `.ttf` files in `.wasm`. Target **< 1.5 MB Brotli-compressed `.wasm`** for initial load.
---
## 5. Windows, Linux & Android
### Windows (`rune-windows`)
Grounded in `gpui_windows` (13,187 LOC):
- **Windowing & Composition (`DirectComposition`):**
Create a Win32 `HWND` (`WS_EX_NOREDIRECTIONBITMAP`) paired with `IDCompositionDevice` / `IDCompositionTarget` / `IDCompositionVisual` (`gpui_windows/src/directx_renderer.rs:118-135`). Using DirectComposition with a flip-model swap chain (`DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL`, `DXGI_ALPHA_MODE_PREMULTIPLIED`) enables per-pixel transparency, Windows 11 Mica/Acrylic backdrops (`DwmSetWindowAttribute` with `DWMWA_SYSTEMBACKDROP_TYPE`), and smooth resize.
- **VSync & Frame Pacing (`vsync.rs:1-85`):**
Query the monitor refresh period via `DwmGetCompositionTimingInfo` (`qpcRefreshPeriod`) and wait on `DwmFlush()` on a dedicated VSync thread. As `gpui_windows/src/vsync.rs:45-58` notes, when a monitor sleeps or is occluded, `DwmFlush()` returns immediately (< 1 ms); detect `elapsed < 1ms` and fall back to `sleep(interval)` so the app never busy-loops at 10,000 FPS.
- **Precision Touchpad Gestures (`DirectManipulation`):**
Do **not** rely solely on legacy `WM_MOUSEWHEEL` / `WM_MOUSEHWHEEL` on Windows—they lack gesture phase (`Began`/`Ended`) and trackpad pinch zoom. Steal `gpui_windows/src/direct_manipulation.rs:1-160`: create an `IDirectManipulationManager` + `IDirectManipulationViewport` on the `HWND` and call `viewport.SetContact(pointer_id)` on `WM_POINTERHITTEST` when `pointer_type == PT_TOUCHPAD`. This delivers smooth pixel-accurate translation, inertia, and pinch-scale callbacks with explicit gesture phases.
- **Text & IME:** Use DirectWrite (`IDWriteFactory5`) for system font fallback and ClearType/grayscale contrast parameters (`directx_renderer.rs:32-37`), and `ImmAssociateContextEx` / `ImmSetCandidateWindow` (`IMM32` + TSF compatibility) for candidate window positioning.
- **GPU Backend:** Use `wgpu` on DX12 (or a direct DX11/DX12 backend behind Rune's renderer trait), ensuring `DXGI_ERROR_DEVICE_REMOVED` / `DEVICE_RESET` triggers an atlas wipe and forced full redraw (`gpui_windows/src/window.rs:68-75`).
### Linux (`rune-linux`)
Grounded in `gpui_linux` (16,422 LOC):
- **Wayland-First, X11 Fallback:**
Build the event loop on `calloop` (`gpui_linux/src/linux/wayland/window.rs:10`). Target Wayland natively via `wayland-client` + `wayland-protocols`:
- `xdg_wm_base` / `xdg_toplevel` / `xdg_popup` for windows and popups.
- `wp_fractional_scale_v1` + `wp_viewporter` (`window.rs:21, 28`) for crisp native fractional scaling (125%, 150%, 175%) without XWayland blur.
- `wl_surface::frame` callbacks (`pending_frame_callback`, `window.rs:136`) for compositor-driven VSync per monitor.
- `zwp_text_input_v3` for IME composition and candidate rectangle placement (`set_cursor_rectangle`).
- `zxdg_toplevel_decoration_v1` to negotiate server-side vs client-side window decorations (`CSD`/`SSD`), plus `zwlr_layer_surface_v1` (`wlr-layer-shell`) so Rune can build Linux status bars, launchers, and notifications.
- **XDG Desktop Portals (`ashpd`):**
Steal `gpui_linux/src/linux/xdg_desktop_portal.rs:1-150`: connect an `ashpd` D-Bus listener into `calloop` to reactively track dark/light `ColorScheme`, cursor theme/size, titlebar button layout, and native sandboxed file pickers (`org.freedesktop.portal.FileChooser`) and screen sharing.
### Android (`rune-android`)
- **`GameActivity` / Custom `Activity` + `SurfaceView` vs `TextureView`:**
- Full-screen Rune apps should use a lightweight Kotlin `Activity` hosting a `SurfaceView` (which gets its own hardware compositor layer and avoids extra GPU texture copies) synced to `Choreographer.getInstance().postFrameCallback` for 120 Hz VSync.
- When Rune is embedded inside a scrolling Jetpack Compose / Android `View` hierarchy, use `TextureView` (or `SurfaceView` with `setZOrderMediaOverlay`) so it participates in view clipping and alpha transitions.
- **IME (`InputConnection`) & Accessibility (`AccessibilityNodeProvider`):**
- Android software keyboards (Gboard, Samsung Keyboard) communicate via `View.onCreateInputConnection(EditorInfo)` returning a stateful `BaseInputConnection` (`setComposingText`, `commitText`, `deleteSurroundingText`, `getExtractedText`). Pure native `NativeActivity` cannot implement `InputConnection` without JNI calls to a Java/Kotlin `View`.
- Pair a ~300-line Kotlin host view (`RuneSurfaceView.kt`) that implements `onCreateInputConnection` and `AccessibilityNodeProvider` (bridged to `accesskit`) with JNI calls into `rune-android`.
---
## 6. Platform-Specific Feel: Native vs Rune's Own
| Concern | Use OS Native | Build in Rune (Platform-Tuned) | Why |
|---|---|---|---|
| **Scroll physics** | — | **Rune's own**, parameterized by platform (`MacTrackpad`, `iOSMomentum`, `DesktopWheel`) | Gives deterministic 120 Hz spring interruption, programmatic scroll-to-element, and cross-view coordinated animations while matching iOS `0.998` deceleration + `0.55` rubber-band math and macOS `NSEventPhase` momentum handoff. |
| **Text selection UX** | **OS IME & Mobile Callout Bar** (`UITextInput` / `UIMenuController` / `UIEditMenuInteraction`) | **Rune renders selection highlights, carets & desktop handles** | On iOS, returning `selectionRectsForRange:` from `UITextInput` lets UIKit render the native Loupe and Copy/Paste/Translate pill while Rune renders the glyphs and selection quads at 120 Hz. |
| **Context menus** | **OS Native on macOS** (`NSMenu`) **& iOS** (`UIEditMenuInteraction` / `UIContextMenuInteraction`); **Rune custom** on Web/Win/Linux (or when custom rich previews are needed) | Configurable per menu | macOS users expect native `NSMenu` translucency, screen-edge flipping, and Services integration; rich app-specific command palettes use Rune's own overlay layer. |
| **Focus rings & Keyboard nav** | Respect OS settings (`NSApplication.fullKeyboardAccessEnabled`, `UIAccessibilityIsReduceMotionEnabled`, Windows high-contrast) | **Rune's own focus graph & animated focus ring** | Only Rune knows widget geometry and spring transitions; focus ring thickness, color (`accentColor`), and Tab traversal rules adapt to the active platform's conventions. |
| **File dialogs, Share sheets, Permissions** | **Always OS Native** (`NSOpenPanel`/`NSSavePanel`, `UIActivityViewController`/`PHPickerViewController`, XDG FileChooser Portal, Web `<input type="file">`) | Never custom | Security sandboxes (TCC, App Sandbox, Wayland Portals, browser security) require native OS pickers. |
---
## 7. Steal / Avoid Lists
### Steal
1. **Scrawl's `CATransaction`-synchronized `NSGlassEffectView` + `CAMetalLayer` pipeline** (`scrawl/src/native/pill/mod.rs:447-453, 644-675, 1111-1147`): `presentsWithTransaction = true`, initial `window.displayIfNeeded()` while `alphaValue = 0.0` so AppKit materializes `SDFLayer` + `CABackdropLayer`, and `CATransaction::begin() ... cmd.wait_until_scheduled(); drawable.present(); CATransaction::commit()` for zero-lag glass morphing.
2. **The launcher's non-activating `NSPanel` + cold-start warm-up + Quick Look responder chain** (`launcher/native/Launcher.swift:26-75, 566-578`): `canBecomeKey = true`, `canBecomeMain = false`, invisible warm-up pass on startup, and `QLPreviewPanel` control forwarding.
3. **Makepad's `CADisplayLink` 120 Hz ProMotion pinning on macOS 14+** (`makepad/platform/src/os/apple/macos/macos_app.rs:1458-1482`): pinning `setPreferredFrameRateRange:` to `window.screen.maximumFramesPerSecond` so macOS never throttles custom GPU views to 30 Hz.
4. **GPUI's `displayLayer:` synchronous live-resize dance on macOS** (`gpui_macos/src/window.rs:2058-2075, 2260-2285`): pausing the display link during `displayLayer:`, enabling `presentsWithTransaction = true`, rendering at the new size, and committing inside AppKit's resize transaction.
5. **GPUI's `GPUITextInputView` on iOS** (`gpui_ios/src/ios/text_input.rs:42-350`): full `UITextInput` implementation in Rust with `session_token`-stamped `UITextPosition`/`UITextRange` and deferred `reconcileTextInput`.
6. **GPUI Web's `ImeMirror` sliding-window hidden `<textarea>`** (`gpui_web/src/ime_mirror.rs:1-198`): 512-UTF-16-unit context window around the selection, `font-size: 16px`, `inputmode="none"` until tap completion on touch screens, and single-write-per-frame coalescing.
7. **GPUI Windows' `DirectManipulationHandler` & VSync sleep fallback** (`gpui_windows/src/direct_manipulation.rs:1-160`, `vsync.rs:41-60`): native precision-touchpad scroll/pinch phases on Windows and occlusion-safe `DwmFlush()` frame pacing.
8. **GPUI Linux's `calloop` + Wayland fractional scale + `ashpd` portal stream** (`gpui_linux/src/linux/wayland/window.rs`, `xdg_desktop_portal.rs`): clean event-loop integration of Wayland protocols and D-Bus desktop settings.
### Avoid
1. **Avoid `winit` as a dependency.** Working around its missing `UITextInput` on iOS, incomplete `NSTextInputClient` on macOS, lack of `presentsWithTransaction` resize sync, and inability to mount as a lightweight `UIViewRepresentable` costs more effort than writing thin shells directly with `objc2` / `web-sys` / `windows` / `wayland-client`.
2. **Avoid tearing down `CVDisplayLink` on window close** (`gpui_macos/src/display_link.rs:16-30`); prefer macOS 14+ `NSView.displayLinkWithTarget:selector:` (`CADisplayLink`) or immortal per-display `CVDisplayLink`s.
3. **Avoid Flutter-style general N-layer `EmbedderViewSlice` platform view slicing.** Allocating intermediate full-screen `CAMetalLayer`s and buffering touch events across threads (`FlutterPlatformViewsController.mm`) adds memory, GPU bandwidth, and input lag. Use explicit Underlay and Overlay view slots on the main thread instead.
4. **Avoid requiring `SharedArrayBuffer` (COOP/COEP headers) on Web.** It makes embedding Rune canvases in docs, blogs, and standard web pages impossible without custom server headers.
5. **Avoid `cargo-mobile2` or `dx bundle` for iOS project management.** Use `XcodeGen` (`project.yml`) + a `cargo` staticlib/XCFramework script so app extensions (`OpenCodeShare`, `HEXKeyboard`), entitlements, and Xcode Cloud continue to work like normal Xcode projects.
---
## 8. Recommendations for Rune
### 8.1 Own Thin Shells vs `winit`
**Decision: Write Rune's own thin per-platform shells (`rune-platform-*`).**
- **Rejected alternative (`winit` `0.31`):** Rejected because text input (`UITextInput` / `NSTextInputClient`), live-resize transaction sync (`presentsWithTransaction`), native materials (`NSGlassEffectView` / `UIGlassEffect`), and `UIViewRepresentable` / `NSViewRepresentable` embedding are architectural load-bearing walls, not bolt-on plugins.
- **Rejected alternative (`SDL3`):** Rejected because it adds a large C dependency without solving native Apple/Web text input, accessibility, or SwiftUI/UIKit view hosting.
### 8.2 The Shell API Surface (The Rust Traits)
Keep the boundary between `rune-core` and platform shells narrow—roughly 5 traits in `rune_core::platform` (modeled on a cleaner, slimmer version of `gpui/src/platform.rs`):
```rust
pub trait Platform: 'static {
fn run(&self, on_Ready: Box<dyn FnOnce(&mut AppContext)>);
fn dispatcher(&self) -> Arc<dyn PlatformDispatcher>;
fn open_window(&self, options: WindowOptions) -> anyhow::Result<Box<dyn PlatformWindow>>;
fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
fn clipboard(&self) -> &dyn PlatformClipboard;
fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
}
pub trait PlatformWindow: 'static {
fn bounds(&self) -> Bounds<LogicalPixels>;
fn scale_factor(&self) -> f32;
fn safe_area_insets(&self) -> Edges<LogicalPixels>;
fn appearance(&self) -> WindowAppearance;
fn request_frame(&self, FrameRequest); // ActiveAnimation (120Hz) vs SingleFrame
fn draw(&mut self, scene: &Scene, glass_underlays: &[GlassRegion], native_overlays: &[NativeOverlay]);
fn set_input_handler(&mut self, handler: Option<PlatformInputHandler>);
fn set_cursor(&mut self, cursor: CursorStyle);
fn trigger_haptic(&self, pattern: HapticPattern);
fn update_accessibility_tree(&mut self, update: accesskit::TreeUpdate);
// Callbacks registered by rune-core:
fn on_frame(&mut self, cb: Box<dyn FnMut(FrameInfo)>);
fn on_input(&mut self, cb: Box<dyn FnMut(PlatformInput) -> EventResult>);
fn on_resize(&mut self, cb: Box<dyn FnMut(Size<LogicalPixels>, f32, Edges<LogicalPixels>)>);
}
pub trait PlatformTextInput {
fn text_for_range(&mut self, range_utf16: Range<usize>, adjusted: &mut Option<Range<usize>>) -> Option<String>;
fn selected_range(&mut self, ignore_marked: bool) -> Option<SelectionUtf16>;
fn marked_range(&self) -> Option<Range<usize>>;
fn replace_text_in_range(&mut self, range_utf16: Option<Range<usize>>, text: &str);
fn replace_and_mark_text_in_range(&mut self, range_utf16: Option<Range<usize>>, new_text: &str, selected_utf16: Option<Range<usize>>);
fn unmark_text(&mut self);
fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<LogicalPixels>>;
fn character_index_for_point(&mut self, point: Point<LogicalPixels>) -> Option<usize>;
}
```
Notice `draw(&mut self, scene: &Scene, glass_underlays: &[GlassRegion], native_overlays: &[NativeOverlay])`: passing native glass/underlay regions alongside the GPU `Scene` lets `rune-macos` and `rune-ios` synchronize `NSGlassEffectView` / `UIVisualEffectView` frames and corner radii inside the **same `CATransaction`** as the Metal drawable presentation (`scrawl/src/native/pill/mod.rs:1111-1147`).
### 8.3 Native View Embedding Strategy
Support two complementary mechanisms:
1. **Rune-in-Native (`RuneHostView`):** Every platform shell exposes a constructor that wraps an existing native view (`UIView`, `NSView`, `<canvas>`, `HWND`, `SurfaceView`) instead of creating a top-level OS window. On iOS and macOS, ship a thin Swift wrapper (`RuneView: UIViewRepresentable` / `NSViewRepresentable`) so the iOS client, `hex`, `scrawl`, and the launcher can drop a 120 Hz Rune view into any SwiftUI screen today, sharing one process-wide `MTLDevice` and `CADisplayLink`.
2. **Native-in-Rune (Underlay & Overlay Slots):** Within a Rune window, support declarative `NativeUnderlay` (for `NSGlassEffectView` / `UIGlassEffect`, `AVPlayerLayer`, `MKMapView` behind a transparent hole in the Metal pass) and `NativeOverlay` (for `WKWebView`, system pickers, and popovers above the Metal layer), synced synchronously on the main thread inside `CATransaction`.
### 8.4 Platform Order & Effort Estimates
| Priority | Platform Shell | Est. Size | Est. Effort | Why This Order |
|---:|---|---:|---:|---|
| **1** | **macOS (`rune-macos` + `rune-apple`)** | ~4,500 LOC (`macos`) + ~2,000 LOC (`apple` shared) | **2–3 weeks** | Fastest local compile/debug cycle; directly powers `scrawl` and the launcher; establishes the `objc2` + `CAMetalLayer` + `CATransaction` + `NSGlassEffectView` + CoreText foundation shared with iOS. |
| **2** | **iOS (`rune-ios` + `RuneKit` Swift host)** | ~3,000 LOC Rust + ~400 LOC Swift | **2 weeks** | Reuses `rune-apple` (CoreText, Metal/wgpu, `dispatch2`, `objc2`); unlocks 120 Hz ProMotion touch/spring validation on iPhone and immediate incremental adoption inside the iOS client and `hex` via `RuneView: UIViewRepresentable`. |
| **3** | **Web (`rune-web`, WASM + WebGPU)** | ~3,500 LOC | **2 weeks** | Safari 26 + Chrome/Firefox/Edge now all support WebGPU; essential for interactive documentation, motion playgrounds, and zero-install demos shared over Tailscale or the web. |
| **4** | **Windows (`rune-windows`)** | ~6,500 LOC | **3–4 weeks** | Largest desktop user base outside macOS; `gpui_windows` provides a complete blueprint for DirectComposition, `DwmFlush` VSync, and `DirectManipulation` trackpad gestures. |
| **5** | **Linux (`rune-linux`, Wayland-first)** | ~6,000 LOC (Wayland + `ashpd` portals) | **3 weeks** | Focus on Wayland (`xdg-shell`, `wp-fractional-scale-v1`, `text-input-v3`, `wlr-layer-shell`, `ashpd`); defer native X11 unless XWayland proves insufficient for specific users. |
| **6** | **Android (`rune-android`)** | ~2,500 LOC Rust + ~400 LOC Kotlin | **2–3 weeks** | Lowest immediate priority for Kit's apps; architectural requirements (JNI `InputConnection` + `Choreographer` + `SurfaceView`/`TextureView`) are already accommodated by the `PlatformWindow` and `PlatformTextInput` traits designed in steps 1–3. |
---
## 9. Open Questions
1. **Multiple `NSGlassEffectView` instances vs `NSGlassEffectContainerView` on macOS 26 / iOS 26:** When a Rune window contains multiple floating glass pills that morph and merge (metaball effect), should `GlassRegion` group them under a single `NSGlassEffectContainerView` / `UIGlassContainerEffect` underlay, and how many concurrent glass regions can WindowServer composite at 120 Hz before backdrop bandwidth drops frames?
2. **Swift 6.2 `@MainActor` interop with `RuneKit`:** In the iOS client (`SWIFT_DEFAULT_ACTOR_ISOLATION: MainActor`), what is the cleanest zero-boilerplate Swift macro or `@MainActor` wrapper so TCA reducers/views can drive `RuneView` state props without copying large buffers across FFI?
3. **Web `EditContext` progressive enhancement:** Should `rune-web` use Chromium's `EditContext` API when `window.EditContext !== undefined` and fall back to `ImeMirror` (`<textarea>`) on Safari/Firefox, or use `ImeMirror` everywhere on Web to avoid maintaining two browser IME codepaths?
4. **Linux X11 support:** Is Wayland + XWayland sufficient for Rune's Linux target in 2026–2027, saving ~6,000 LOC of legacy X11/XCB/XIM code (`gpui_linux/src/linux/x11`), or do target Linux users still require a native X11 backend?
+288
View File
@@ -0,0 +1,288 @@
# 12. Rendering research and tricks for Rune (2D/UI GPU rendering, 2023-2026)
Scope: analytic AA and coverage, sparse strips, Slug, Rive feathering, blur and backdrop, glass lensing, SDF shapes,
GPU-driven UI, Apple TBDR, damage tracking, HDR, dithering, colour. Written 2026-10-21. Sources were fetched via search
snippets and (where quoted) real source; items marked *(from memory)* or *(estimate)* were not re-verified. Nothing was
built or measured here.
## Summary
- **Most of the PLAN §4.3 primitive list is already right.** Research mostly confirms it and sharpens details. Nothing
found says "change the architecture".
- **Biggest new finds:** (1) `vello_cpu` is a fast, SIMD, multithreaded CPU renderer, so it can be the *reference
renderer* tenet 7 asks for, for free. (2) Rive's *vector feathering* is an analytic Gaussian blur of arbitrary
paths, and its "never blur above 16 px, scale up instead" rule applies to Rune's backdrop too. (3) Evaluating the
closed-form springs *in the vertex shader* is a trick only a render-thread-owns-animation design can use.
- **Backdrop blur:** the Jimenez 13-tap down / 9-tap tent up pyramid is still the right tool (2014, still current).
The new problem is temporal: an animated blur radius must be continuous, so blend between pyramid levels.
- **Glass in-app:** open-source "liquid glass" shaders (WebGL, Metal gist, a GPUI fork) all use the same recipe: SDF
height field, normal, refraction offset, chroma split, Fresnel/specular, blurred copy. It is cheap *given* a
backdrop copy. The copy is the expensive part, so scissor it to the glass bounds.
- **Slug:** patent dedicated to public domain 2026-03-17; MIT reference shaders now include dynamic dilation and drop
the band-split and supersampling complications. Good for scale-animated text and icons.
- **Skip or defer:** GPU-driven indirect rendering (UI scenes are too small), partial present (power, not feel; Metal
gives no buffer age), HDR UI, Apple tile shaders for blur (tiles cannot see neighbours).
- Exact-count perf gates (tenet 7) fit every technique below: all are countable (taps, passes, instances, bytes).
## Ranked ideas
### 1. `vello_cpu` as the CPU reference renderer (and `vello_gpu` as the complex-vector lane) — **adopt now / spike**
- Sources: [Stampfl thesis, ETH, Oct 2025](https://ethz.ch/content/dam/ethz/special-interest/infk/inst-pls/plf-dam/documents/StudentProjects/MasterTheses/2025-Laurenz-Thesis.pdf);
[Vello ARCHITECTURE.md](https://cdn.jsdelivr.net/gh/linebender/vello@main/ARCHITECTURE.md);
[Linebender Jul 2025](https://linebender.org/blog/tmil-19/), [Oct 2025](https://linebender.org/blog/tmil-22/);
[sparse-strips v0.0.8](https://github.com/linebender/vello/releases/tag/sparse-strips-v0.0.8);
[benchmarks](https://laurenzv.github.io/vello_chart/).
- What it is: paths flatten, bin into tiles, and become run-length "sparse strips" (coverage kept only at edges,
solid runs stored compactly). One CPU pipeline (`vello_common`) feeds `vello_cpu` (SIMD via `fearless_simd`
NEON/SSE4.2/WASM, optional multithreading) and `vello_gpu` (plain vertex/fragment, wgpu and WebGL2, no compute).
Compute Vello moved to `research/`, matching PLAN. Measured (M1 Pro, Blend2D harness, preliminary): vello_cpu is
second to Blend2D in many tests and often beats Skia and Cairo, more so on large geometry. It already has blurred
rounded-rect paints, opacity layers, non-isolated blending, and early image filters including blur.
- Rune use: (a) the **reference path** from tenet 7 / §6b "same pixels on every platform": render the same scene
description through vello_cpu and diff against the GPU lane (tolerance per primitive). (b) The deterministic
headless lane for agents on machines with no GPU (CI, Linux boxes). (c) `vello_gpu` as the `SparseStrips`
primitive for icons/illustrations. API is explicitly unstable; pin a version and wrap it.
- Cost/risk: alpha-quality, API churn, MSRV bumps. CPU AA differs slightly from GPU analytic AA, so diff tolerance
must be calibrated per primitive, not zero. Verdict: adopt vello_cpu as oracle now; spike vello_gpu.
### 2. Evaluate analytic springs in the vertex shader — **spike** *(my idea; no source)*
- Rune already uses closed-form springs (position, velocity, target, t0, omega, zeta). Upload those few floats as
instance data and evaluate `x(t)` in the vertex shader with a per-frame `time` uniform. While anything animates,
the app thread does nothing, and the render thread rewrites only the uniform. Instance buffers become retained,
rewritten only on retarget or tree change, instead of rebuilt per frame.
- Gains: zero CPU per animated node per frame (a list of 500 sliding rows costs the same as one); sample time is the
display-link target timestamp, so late frames still land on the right pose; the GPU and CPU copies of the same
function make a perfect differential test (render the same `t` on both).
- Caveats: hit-testing, clip tables, text positions and layout children need the CPU value too (same function, run
lazily only when queried, e.g. on input). Float32 vs f64 drift: define springs relative to t0 so `t - t0` is small.
Properties that feed other computations (shadow offset depends on position) need the shader to evaluate several
springs per instance; budget a fixed number of tracks per instance (e.g. 4) in the layout of the instance struct.
- Verdict: spike, measuring encode CPU time with 1k animating nodes vs the baseline of per-frame instance rebuild.
### 3. Pyramid backdrop blur (Jimenez dual filter) with continuous radius — **adopt now**
- Sources: [Jimenez, SIGGRAPH 2014](https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/);
[three.js port with numbers](https://tobis.vision/notes/three-js-bloom-jimenez-dual-filter) (claims 9x faster than
the stock bloom; a radius-22 Gaussian is 86 taps at one level vs 9 on the pyramid);
[WGSL downsample with Karis average](https://docs.rs/crate/myth_render/latest/source/src/pipeline/shaders/entry/post_process/bloom/downsample.wgsl).
Dual Kawase (ARM, SIGGRAPH 2015) is the cheaper 5-tap cousin, *(from memory)*.
- Mechanics: 13-tap downsample (weights 0.125/0.0625/0.03125, sum 1), 3x3 tent upsample added into the finer level,
Karis luminance weighting on the first level only for stability against sparkle. Wide blur comes from depth of the
pyramid, not kernel width.
- Rune use for the `Backdrop` primitive: (a) scissor everything to the union of glass bounds plus the blur margin;
(b) pick pyramid depth from the requested sigma; (c) **fractional radius**: crossfade the two nearest pyramid
levels by the fractional part so an animated radius never steps (the actual risk for Kit's motion rules: a radius
spring must not snap between integer levels); (d) store the pyramid in rgba16f or rg11b10 to avoid banding and
dither at the final composite (see idea 9); (e) cache the blurred pyramid when the underlying scene is unchanged
(glass over static content costs one composite).
- Rive's rule is a useful twin: [`draw.cpp`](https://github.com/rive-app/rive-runtime/blob/f4e896a4/renderer/src/draw.cpp)
never renders a blur wider than 16 px at the render scale; it renders smaller and scales up. The pyramid is the same
idea.
- Cost/risk: low. Downsampled upsample can leak the glass edge into the blur; premultiply and use the glass mask at
composite (the three.js liquid-glass repos premultiply on the first pass for this reason).
- Peak-alpha boost (Scrawl) is orthogonal and composes after the blur.
### 4. Liquid-glass-style lens as an in-app material — **spike**
- Sources (all MIT-ish, small): [liquid-glass-js `webgl.ts`](https://github.com/Amir-Abushanab/liquid-glass-js/blob/main/packages/core/src/webgl.ts)
(SDF mask, baked displacement map RG, specular B, chroma split, adaptive specular: additive on dark, multiplicative
on bright, plus a vibrancy pull toward mid grey for legibility);
[liquid-glass-studio](https://github.com/iyinchao/liquid-glass-studio/) (refraction, dispersion, Fresnel,
superellipse shapes, **smooth-union blob merging**, spring-driven shape animation, WebGL2 and WebGPU);
[Metal gist](https://gist.github.com/destefanis/b69545e63b38eb91a13c7c5d330d1345);
[GPUI fork PR adding BlurRect and LensRect primitives](https://github.com/df49b9cd/zed/pull/1) (Apr 2026, shows the
same shape of primitive in GPUI).
- What Rune would do: one `Lens` material on `UberQuad`: compute the SDF, derive a height profile from the distance
(smoothstep or erf edge falloff), normal = gradient of height, refracted sample offset = normal * strength, sample
the backdrop at three offsets for dispersion, mix with the blurred pyramid for frost, add Fresnel and a
specular rim. For rounded rects and superellipses the height and gradient are closed-form per pixel, so the
baked displacement map in those repos is unnecessary and the shape can animate every frame (no map regeneration).
- The real cost is the backdrop copy (render pass break, see idea 7). Scissor-copy only the glass bounds plus
displacement margin; for several glass shapes copy their union rect once.
- The "adaptive specular + vibrancy" trick matters for §6b "real contrast": it is a legibility control, and the
contrast checker can verify it.
- This is the in-app answer to PLAN §4.4's limit ("Rune can't draw Liquid Glass"): the system's own shader is out of
reach, but a plausible lens is not, and it works on web/Windows/Linux too, which native underlays never will.
- Risk: it will not match Apple's exactly; design decision for Kit. Verdict: spike with one hero element, compare
against `NSGlassEffectView` side by side.
### 5. Slug for scale-animated text and icons — **spike** (already in the plan; new facts)
- Sources: [A Decade of Slug](https://terathon.com/blog/decade-slug.html) (patent #10,373,352 dedicated to the public
domain 2026-03-17), [reference shaders, MIT/Apache](https://github.com/EricLengyel/Slug), the JCGT 2017 paper,
[dilation write-up](https://terathon.com/blog/glyph-dilation.html).
- New facts: the 2026 pixel shader is "a significant upgrade"; the vertex shader has **dynamic dilation** (expand the
bounding polygon by half a pixel in viewport space per vertex, using the MVP and viewport, so no wasted padding and
no missing edge pixels under perspective or scale); adaptive supersampling and the band-split optimisation were
removed (simpler). Curve and band data live in textures (fixed 4096-wide); per pixel it solves quadratic roots in
two directions.
- Rune use: text or icons under scale springs (a title growing 0.9 to 1.0) re-rasterise glyph-atlas entries at
every size, which pops; Slug has no atlas. Pair with a coverage-based weight boost (their `SLUG_WEIGHT` sqrt) to
keep light-on-dark text from thinning. Keep the atlas for body text at 1x (cheaper per pixel).
- Cost/risk: fragment cost is higher than atlas sampling; quadratic outlines only (TrueType native, CFF cubics need
conversion); no hinting. Gate with a per-scene counter of Slug pixels. Verdict: spike after the glyph atlas works.
### 6. Rive-style analytic feathering for soft shapes — **later / steal one trick now**
- Sources: [Rive blog (Apr 2025)](https://rive.app/blog/how-rive-reinvented-feathering-for-the-vectorian-era),
[intro (Feb 2025)](https://rive.app/blog/introducing-vector-feathering),
[renderer source: `draw.cpp`, `tessellate.glsl`](https://github.com/rive-app/rive-runtime/blob/5360c834/renderer/src/shaders/tessellate.glsl),
[Khronos slides](https://www.khronos.org/assets/uploads/developers/presentations/Rive.pdf).
- What it does: widens the one-pixel AA ramp into a Gaussian CDF ramp (`erf`) of the chosen width, computed
procedurally from the same coverage triangles. A 1D lookup texture holds the CDF and its inverse. At corners the
integral is done with about four samples per fragment; in the tessellator, curvature dims the feather by
flattening the curve's control points (`dimming = 1 - curvature/pi`). No offscreen blur pass, resolution
independent, cheap on weak GPUs. Large radii fall back to an atlas path rendered small then scaled up.
- Rune use: free-form soft glows and inner/outer shadows of arbitrary paths (icons, blobs) without an offscreen
pass. For rounded rects the Levien closed form (idea 8) is simpler and exact; feathering matters only for
non-rect paths. It needs an own tessellator with signed-winding triangles (Rive's coverage scheme), which Rune does
not have; `vello_cpu`'s blur filter or an offscreen blur is the pragmatic route until then.
- Steal now: (1) CDF 1D texture trick for any ramp (it replaces `erf` approximations in the shader); (2) "design-tool
blur = 2 sigma wide" convention (feather radius = amount * stddevs / 2) so Figma-like numbers match.
- Verdict: later, behind Rune having its own path tessellator.
### 7. Apple TBDR discipline (framebuffer fetch, memoryless, load/store) — **later, Metal backend only**
- Sources: [WWDC20 Harness Apple GPUs](https://developer.apple.com/videos/play/wwdc2020/10602/),
[WWDC21 image processing on Apple silicon](https://developer.apple.com/videos/play/wwdc2021/10153/),
[Metal 2 on A11: imageblocks](https://developer.apple.com/videos/play/tech-talks/603/) and
[tile shading](https://developer.apple.com/videos/play/tech-talks/604/),
[Tailor your apps for TBDR](https://developer.apple.com/documentation/metal/tailor-your-apps-for-apple-gpus-and-tile-based-deferred-rendering).
- Key facts: alpha blending runs in tile memory and the target is written once per pass; programmable blending lets a
fragment read the tile's current colour (merges multi-pass effects with no intermediate store); memoryless
textures live only in tile memory (must be `DontCare`/`Clear` load and `DontCare` store, no sampling, no blit or
compute); `LoadActionDontCare`/`Clear` avoids reading what is overwritten.
- Rune use: (a) **group opacity** and non-trivial blend modes (multiply, screen, plus-lighter) via framebuffer fetch
in the one pass, avoiding offscreen layers (matches PLAN §4.2). (b) Always `DontCare` loads where the frame is
fully redrawn. (c) MSAA is unnecessary for UI (analytic AA), so memoryless MSAA is not a lever.
- Limits: a backdrop *sample* (blur, lens) reads neighbouring pixels, which tile memory cannot provide; tile shaders
see only their own tile. So glass still needs a pass break (store, then load) and the copy in idea 4. Raster order
groups (also used by Rive on D3D11/Metal) serialise overlapping fragments; Rive uses them for exact path
blending, which Rune does not need for the uber-quad lane.
- wgpu: **I could not confirm** any framebuffer-fetch or pixel-local-storage support in wgpu *(treat as unsupported)*;
this is a concrete reason to keep the raw-Metal HAL on the plan as a later optimisation. Verdict: later, justified
only by measured offscreen-layer cost.
### 8. Closed-form blurred rounded rects, inset shadows, and squircles — **adopt now**
- Sources: [Levien, blurred rounded rects](https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html)
(rounded-rect distance field, effective radius `sqrt(rc^2 + 1.25 rb^2)`, 1D erf cross-section, `erf7` using a
reciprocal sqrt); [Evan Wallace, fast rounded-rect shadows](https://madebyevan.com/shaders/fast-rounded-rectangle-shadows/)
(product of two erf boxes; CC0 code); [Vello's implementation, #665](https://github.com/linebender/vello/pull/665)
plus the active inset-shadow work ([#1374](https://github.com/linebender/vello/issues/1374),
[#1718](https://github.com/linebender/vello/pull/1718)) and [#1724](https://github.com/linebender/vello/pull/1724)
(cutting `powf` calls).
- Rune use: the `UberQuad` already plans analytic Gaussian shadows (PLAN §4.3). Take Levien's formula as the base,
differential-test it against numerically integrated results (the CPU reference) per radius and sigma, and add
inset shadows as `1 - blurred` per Vello's design. The same field gives soft per-side gradient edges for the "no
hard clip edges" rule, since a blurred rounded rect is exactly a soft mask.
- **Squircles (continuous corners):** iOS-style corners are not circles; Figma's "corner smoothing" parameter is the
common reference and a superellipse is the cheap stand-in *(from memory)*. Implicit shapes have no exact distance,
so use `f / |grad f|` as an AA distance (valid near the edge, wrong far away; fine because only the edge band is
shaded). Test against a high-resolution CPU rasteriser for AA ramp error.
- **Smooth union for morphing shapes:** polynomial `smin` (Quilez) over a handful of SDFs gives the metaball merge
seen in liquid-glass-studio; lerping two SDFs is a cheap shape morph. Fix a maximum number of operands per `Blob`
primitive (4) so the shader stays branch-free. This is how Rune can do the launcher's glass morph without SwiftUI on
non-Apple platforms.
- Cost/risk: low; the main risk is the AA width under non-uniform scale and rotation: derive the pixel footprint
from the Jacobian (`fwidth` or explicit inverse transform), not a scalar scale. Add a rotation/skew scene.
### 9. Dithering and perceptual colour — **adopt now**
- Sources: Jimenez interleaved gradient noise (same CoD talk as idea 3; cheap per-pixel hash, good temporal
behaviour); Christoph Peters, free blue-noise textures *(from memory, no link fetched)*; Ottosson's Oklab and
gamut-clipping posts *(from memory)*; PLAN §4.3 already cites Kit's GPUI fork (`kitlangton/gpui`) dithering fixes.
- Rune use: interpolate gradients in Oklab (or OKLCH for hue ramps) and blend in linear light on Display P3, as the
plan says; then dither once at the final write, with triangular-PDF noise of about +/-1 LSB, using a tiled blue
noise texture or IGN. One shared function for gradients, shadows, backdrop output, and video.
- Two traps worth encoding as tests: (1) **noise swim**: a screen-space-fixed pattern over scrolling content shimmers
relative to the content; use content-local coordinates for scrolling layers (or accept it for static UI). Never
animate the noise per frame (breaks "zero cost at rest" and snapshot determinism); the seed must be a pure function
of pixel coordinates. (2) **Banding in blurred backdrops**: a blur of 8-bit content upsampled by a pyramid bands;
dither after the final upsample and keep intermediates in 16-bit.
- Deterministic golden images then stay stable because the dither is deterministic and the same on CPU and GPU lane.
### 10. Damage tracking / partial redraw — **skip for now; design the hook**
- Sources: [Flutter Impeller partial repaint, issue #124526](https://github.com/flutter/flutter/issues/124526) and
[PR #40959](https://github.com/flutter/engine/pull/40959); [Flutter damage-rect discussion](https://github.com/flutter/flutter/issues/33939)
(Metal has no buffer-age API; track which of the 2-3 drawables you got by texture identity);
[Slint's Metal surface keeping per-drawable ages](https://github.com/slint-ui/slint/blob/507b650e/internal/renderers/skia/metal_surface.rs);
[EGL_KHR_partial_update](https://registry.khronos.org/EGL/extensions/KHR/EGL_KHR_partial_update.txt).
- Findings: Metal drawables are not preserved, so partial repaint means keeping your own full-frame texture and blitting
the damaged area into the drawable (Impeller measured the blit at about 0.5 us on iPhone 13, only bypassing partial
repaint above 70 % damage; I would treat that figure as encode time rather than GPU time) *(estimate)*; drawable
ages can drift, so track per drawable.
- For Rune: the benefit is battery and thermals, not feel; frames that animate usually damage most of the window or a
big glass region anyway, and at rest Rune submits nothing. Verdict: skip. Keep a per-frame damage rect in the scene
(cheap: union of changed instance bounds) so a counter shows how much a frame *could* skip; revisit if Scrawl or the launcher
idle-animation power shows up in profiling.
### 11. GPU-driven UI (indirect draws, bindless, compute culling) — **skip**
- A UI frame is one pass with one or a few instanced draws and a few thousand instances (PLAN §4.3). CPU encode cost is
already tiny; indirect command buffers or compute culling pay when there are tens of thousands of distinct draws
*(general knowledge)*. The pieces worth taking are the cheap ones: bindless-style texture arrays or one atlas to avoid
rebinding, and instance buffers written once per change (idea 2). Compute culling is useful only for huge scrolling
lists, where CPU range queries over a sorted arena are simpler and exactly testable.
### 12. HDR / EDR UI — **later**
- *(From memory, not re-fetched.)* On Apple, `CAMetalLayer.wantsExtendedDynamicRangeContent` with an
`rgba16Float` extended-linear Display P3 layer gives headroom above 1.0, and the headroom is queried per screen
and changes with brightness. For Rune it means HDR video/photos and specular highlights could exceed SDF white.
The cost is double the bandwidth for the frame. Keep the pipeline format-generic and linear (already planned) so EDR is
a switch, not a rewrite; keep chrome in SDR. Verdict: later.
## Steal list
- `vello_cpu` as reference and headless renderer; Vello's blurred-rounded-rect code as a CPU oracle for the analytic
shadow.
- Levien `erf7` + effective-radius formula; Evan Wallace's product-of-erf boxes (CC0).
- Jimenez 13-tap/tent pyramid with Karis first level; fractional-level crossfade (new for Rune).
- Rive: 16 px blur cap then upscale; CDF lookup texture; "2 sigma = design blur amount" convention.
- Liquid-glass recipe: SDF height, normal-based refraction, per-channel dispersion, adaptive specular, vibrancy toward
mid grey, polynomial smooth union for merging shapes.
- Slug dynamic dilation and the MIT reference shaders; sqrt coverage for optical weight.
- Slint/Impeller per-drawable age tracking if partial repaint is ever added.
- TBDR load/store discipline and framebuffer fetch group opacity (Metal backend).
## Avoid list
- Pre-baked displacement maps for glass: closed-form SDF is exact and animatable.
- Gaussian convolution with large kernels or a separable pass at full resolution for backdrop.
- MSAA for UI primitives (analytic AA is cheaper and deterministic).
- Per-frame animated dither noise (breaks determinism and zero cost at rest).
- Compute-shader Vello as a dependency (moved to `research/`; needs compute, memory-hungry).
- Indirect/bindless engines for a UI-sized draw count.
- Assuming wgpu exposes framebuffer fetch.
- Treating Apple tile shaders as a blur tool (tiles cannot read neighbours).
## Recommendation for Rune
1. Adopt now: closed-form blurred rounded rect and inset shadow (idea 8), pyramid backdrop with fractional radius
(3), Oklab + deterministic dither (9), `vello_cpu` as the reference renderer (1).
2. Spike next, each with an exact counter and a differential test: vertex-shader springs (2), glass lens (4), Slug for
animated text (5), `vello_gpu` lane (1).
3. Later: feathering (needs a tessellator), framebuffer-fetch group opacity (needs raw Metal), HDR.
4. Skip: GPU-driven draws, partial present, MSAA.
Rejected alternatives: compute Vello (compatibility, memory); SDF/MSDF text (corner rounding, atlas pops, Slug
supersedes it now the patent is gone); full-resolution separable Gaussian (cost, banding); wrapping SwiftUI/CA for
all glass (does not reach web, Windows, Linux).
## Open questions
- How does fractional pyramid crossfade look at the transition between a thin and a thick blur while the glass also
moves? Needs a scene in the deterministic harness plus the motion linter.
- Does the vertex-shader spring path survive retarget bursts (a drag) without per-frame instance rewrites? Measure
encode time at 1k animating nodes.
- Can wgpu on Metal skip the drawable's initial clear and use an `IOSurface`-backed texture presented via CALayer
contents (retained, damage-friendly)? Unverified.
- Apple's real glass is likely a different material model (not a plain lens); is "close enough" acceptable to Kit
for non-Apple platforms, with native underlays kept on Apple?
- Slug quadratic-only limit: do Rune's fonts (SF, CFF fonts) need an offline cubic-to-quadratic step, and what is the
fragment cost at 120 Hz on iPhone-class GPUs?
- Dither noise swim on scrolling content: local-coordinate dither vs screen-space; needs a visual test.
+123
View File
@@ -0,0 +1,123 @@
# 13 – Startup and input-to-photon latency tricks for Rune
Written from existing knowledge of the sources below; no web crawl this pass and nothing was built or benchmarked. Numbers are from the cited sources unless marked *(estimate)*. Verify each link before relying on it.
## Summary
- Instant first frame is mostly a **compositor-handoff problem**, not a rendering problem. The cheapest route is a `CALayer`/`IOSurface` (or Android splash) holding pre-rendered pixels that the OS shows before our code runs. The live tree then replaces it without a visible change.
- A pre-rendered frame is only invisible if the live first frame is **bit-identical**. Rune's deterministic headless renderer makes that testable, which GPUI/Flutter lack. This is the strongest unique advantage.
- Cold-start cost on macOS is dominated by dyld, page faults, and wgpu device/pipeline creation. Static linking, page-ordering and a pipeline cache attack all three.
- Input latency wins come from three places: **late latching** (sample input as late as possible), **predicted touches**, and **present-time control** (`CAMetalDisplayLink`, `presentAfterMinimumDuration`, DirectFlip, Wayland commit-timing).
- Perceptual thresholds justify the targets: touch-to-photon around 1 ms is perceptibly better for direct manipulation, and 100 ms is the floor for "instant" launch.
- Most of these ideas are impractical for humans to maintain (order files, generated pixel blobs per appearance and size, per-platform present loops). They are cheap if the build pipeline regenerates them.
## Findings
### 1. Static first-frame layer shown by the OS (iOS/macOS) — **adopt now**
- iOS: launch screen storyboard, plus the app-switcher snapshot taken by the system (`applicationDidEnterBackground` snapshot, state restoration). Apple's guidance is that the launch image must match the first screen ([HIG: Launching](https://developer.apple.com/design/human-interface-guidelines/launching)).
- Rune use: the build generates a launch storyboard-equivalent or, more flexibly, a `CAMetalLayer`/`CALayer` whose `contents` is an `IOSurface` or `CGImage` embedded in the binary (decoded lazily from a compressed blob). It is installed in `applicationDidFinishLaunching` before any wgpu work. The Metal layer later takes `contents` over, with the static layer removed in the same CA transaction as the first live present.
- On macOS, show a borderless window with that layer before the runtime initialises. Set window background to match, which avoids a white flash.
- Variants: per appearance (light/dark), per scale factor, per common window size. Generate by running the headless renderer in CI and storing as AVIF/zstd'd BC7 or raw 8888 for tiny sizes. A 1280×800 8888 frame is about 4 MB *(estimate)*, so prefer zstd/lz4. Decode cost is roughly 2–5 ms at that size *(estimate)*.
- Risk: dynamic content (user data, restored window sizes). Mitigate by snapshotting the **last session's** frame at quit (see 2) and falling back to the build-time frame.
### 2. Last-session snapshot, as in iOS app-switcher snapshots — **adopt now**
- Same mechanism as 1 but the pixels come from the final frame of the previous run (written at quit/background, keyed by appearance + size + scale). This is what iOS does for backgrounded apps and what browsers do with bfcache/tab thumbnails.
- Rune use: store `IOSurface` bytes in the app cache dir. Shown first on relaunch. Falls back to the build-time frame on mismatch (version hash changed).
- Risk: showing stale data. Require a "snapshot-safe" flag per view, with sensitive views excluded.
### 3. Chrome paint holding / View Transitions-style handoff — **adopt (principle)**
- [Chrome paint holding](https://developer.chrome.com/blog/paint-holding) keeps the previous page painted during same-origin navigation until the new page's first contentful paint, avoiding white flashes. The same principle applies: **never present until the live frame is ready; keep the old pixels up until then.**
- Rune use: handoff rule is "live swap occurs on the first live frame that passed the visual-equality gate or is ready". A transition (e.g. 80 ms cross-fade, springs-based) is used only when the golden diff is non-zero.
- Cost: low. It is a presentation policy in the shell.
### 4. Bit-identical handoff gate via deterministic rendering — **adopt now (Rune-specific)**
- The plan's guarantee ("golden diff = 0") needs the live GPU frame to equal the pre-render. Different GPUs and drivers produce different antialiasing/gamma/subpixel text; a CPU-rendered snapshot will differ from a GPU render by a few LSBs.
- Options: (a) render the snapshot with the same wgpu path on a reference GPU, accepting a small tolerance (e.g. ≤ 1/255 per channel) and fading over ~1 frame; (b) have the **first live frame** be the snapshot itself (a textured quad) and then re-render live, fading differences below the perceptual threshold; (c) snapshot per GPU family at first run (see 8).
- Ship (a)+(c). Measure max delta per device class in CI.
### 5. Android SplashScreen API + Baseline Profiles — **later (Android is last), but the idea transfers**
- [SplashScreen API](https://developer.android.com/develop/ui/views/launch/splash-screen) and [Baseline Profiles](https://developer.android.com/topic/performance/baselineprofiles/overview): Google reports around 30% faster cold start from AOT-compiling hot code paths (varies per app).
- Transfer: the profile-guided idea is generic. Collect page-fault and call-order traces from a headless launch, and feed them to binary ordering (item 7). The splash handoff is the same as items 1–3.
### 6. Process snapshotting: V8/Node startup snapshots, Emacs portable dumper, CRIU/CRaC — **spike (partial) / skip (full)**
- [Node startup snapshot](https://nodejs.org/api/cli.html#--build-snapshot) and V8 snapshots deserialize the heap in milliseconds instead of re-running init. [Emacs pdumper](https://www.gnu.org/software/emacs/manual/html_node/elisp/Dumping.html) does the same for Lisp state: startup drops from seconds to tens of ms. [CRaC](https://openjdk.org/projects/crac/) and CRIU restore a process after warmup (JVM startup from seconds to roughly 40–100 ms in the published demos).
- Rune use, practical subset: do not snapshot the process (GPU contexts and window system handles cannot be restored). Instead **snapshot the pure-CPU state**: initial tree, resolved layout, shaped text runs (Parley glyph clusters + positions), glyph atlas contents, and font tables, serialized in a zero-copy format (`rkyv`-style, mmap'd). Loading is `mmap` plus pointer fix-up (or none with relative pointers), so no parse or shape work at startup.
- Cost: format versioning. Agents can regenerate on every build. Risk is stale caches; key by content hash of the binary + fonts.
- Full-process CRIU on macOS is not available; skip.
### 7. Binary layout: order files, PGO, BOLT, static linking, dyld costs — **adopt now (cheap), measure first**
- macOS dyld: each dylib adds mapping, rebinding and initializer cost. dyld 4 plus [chained fixups](https://developer.apple.com/videos/play/wwdc2022/110362/) reduce it. A single statically linked Rust binary with system frameworks only is near the floor (about 10–15 ms for a hello-world process on Apple silicon *(estimate)*).
- Page-in dominates cold launch: first execution of code pulls pages from disk (each 16 KB page fault is about tens of µs warm and much more cold). Linker `-order_file` (ld64/lld) places startup-touched functions contiguously. Apple documents order files and [Xcode's "Generate Link Map"/order file profiling](https://developer.apple.com/documentation/xcode/improving-your-app-s-performance). Meta/Google report double-digit % launch improvement from function ordering ([LLVM Propeller](https://research.google/pubs/propeller-a-profile-guided-relinking-optimizer-for-warehouse-scale-applications/), [BOLT](https://github.com/llvm/llvm-project/tree/main/bolt); BOLT is ELF-focused, so use Propeller/order-files on Linux and `-order_file` on Mach-O).
- Rune use: CI runs the headless startup under a tracer (e.g. `-finstrument`-style or sampling plus page-fault logging), emits an order file, and release links with it. Also: `opt-level=3` + `lto="fat"` + `codegen-units=1`, `panic=abort`, no `std::fmt` heavy init in startup, avoid `lazy_static` fan-out; `mach_absolute_time` stamps at `main`, post-window, post-device, first-present. Hot/cold splitting for the startup path.
- Cost: low-medium; an agent can maintain the pipeline. Gain *(estimate)*: 10–30% of cold launch before first frame.
### 8. Pipeline/shader prewarming and caches — **adopt now**
- Metal pipeline creation (MSL compile + PSO) costs 5–50 ms each cold; [Metal binary archives](https://developer.apple.com/documentation/metal/mtlbinaryarchive) store compiled GPU binaries to avoid it. WebGPU/wgpu: pipeline caches exist in recent wgpu (`PipelineCache` on Vulkan; use naga → MSL ahead of time for Metal).
- Rune use: precompile all shaders (naga → MSL → `metallib`) at build time and load the library from the bundle; build a binary archive per GPU family on first run (and ship one for common Apple GPU families in the bundle). Bound the number of pipelines (small fixed set of uber-shaders plus specialization constants) so prewarm is a handful of calls, which can be issued on a background thread while the static frame is already on screen.
- Also prewarm the glyph atlas for the first frame (from item 6's cached shaped runs).
### 9. Lazy / parallel init: critical path = pixels — **adopt now**
- Order: (1) main thread: window + static layer (≤ 20 ms); (2) thread A: wgpu instance/adapter/device; (3) thread B: font load via mmap, Parley shaping from cache; (4) thread C: tree build from snapshot; then render. Everything else (a11y tree, IME, network, hot reload server) is after first present.
- Known costs to measure: `wgpu` adapter enumeration (~5–30 ms on macOS *(estimate)*), `CAMetalLayer.nextDrawable` first call, font fallback enumeration with CoreText (can be 50+ ms; avoid system font enumeration at startup).
- Flutter comparison: [Flutter AOT](https://docs.flutter.dev/resources/faq#what-technology-is-flutter-built-with) removes JIT cost, and [Impeller](https://docs.flutter.dev/perf/impeller) precompiles shaders because Skia's runtime shader compilation caused first-run jank. Rune's analogue is already planned (item 8).
### 10. Late-latching input before present (VR technique) — **adopt now**
- VR runtimes sample head pose as late as possible, after CPU frame construction and just before GPU submit ([Oculus late latching](https://developer.oculus.com/blog/optimizing-vr-graphics-with-late-latching/), reported roughly one frame of latency saved on mobile).
- Rune use: the render thread (analytic springs, GPU-driven) reads the **latest pointer position/drag velocity** from a lock-free atomic slot immediately before encoding the final uniform buffer. Because springs are analytic and evaluated at a presentation timestamp, drag-following transforms can be written into a small "late" uniform region that is patched after the main command buffer is built (a ring-buffer slot written right before `commit`). Layout and text are not re-done; only transforms of the dragged node are late-latched.
- Cost: moderate; requires a "late uniform" concept for dragged transforms. Gain: up to 1 frame (8.3 ms at 120 Hz).
### 11. Predicted touches and pointer events — **adopt (iOS first), spike model choice**
- iOS: [`UIEvent.predictedTouches(for:)`](https://developer.apple.com/documentation/uikit/uievent/1613844-predictedtouches), and coalesced touches for the full-rate samples. Apple's own documentation recommends drawing predicted points then discarding them next frame. Chrome: [`getPredictedEvents()`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/getPredictedEvents) and the Chromium input predictor (kalman, least squares, linear/quadratic variants, [Chromium input prediction design](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/ui/base/prediction/)), which found Kalman filter preferable for scrolling and least-squares for drawing.
- Rune use: for direct-manipulation gestures, use `coalescedTouches` at 240 Hz for the real sample path (smooth velocity for spring handoff), and predict ~1 frame ahead using a constant-velocity or damped-acceleration Kalman model, rendering the predicted position but never committing it to state. On release, hand over the **measured** (not predicted) velocity to the spring. On macOS trackpad/mouse, use prediction only for drag.
- Risk: overshoot artifacts at direction changes; clamp prediction horizon by confidence (cap at 1 vs. 2 frames) and check with recorded real traces replayed deterministically (a good agent-verification fit: record input traces, replay headless, measure prediction error).
### 12. Present timing: CAMetalDisplayLink, minimum-duration, DirectFlip, Wayland — **adopt on Apple, spike elsewhere**
- Apple: [`CAMetalDisplayLink`](https://developer.apple.com/documentation/quartzcore/cametaldisplaylink) (iOS 17 / macOS 14) fires with a target present timestamp and a deadline for drawable submission, so a render thread can wake just-in-time rather than at vsync after a fixed offset. Use `drawable.present(afterMinimumDuration:)`/`present(at:)` to hold frame cadence, and `maximumDrawableCount = 2` for lowest latency on macOS (CAMetalLayer property). Set `displaySyncEnabled`, and `wantsExtendedDynamicRangeContent` off unless needed. Use `presentedTime` / `MTLDrawable.addPresentedHandler` for measured latency.
- Windows: DXGI flip model with [independent flip / DirectFlip](https://devblogs.microsoft.com/directx/dxgi-flip-model/) skips DWM composition when the swap chain covers the window (requires `DXGI_SWAP_EFFECT_FLIP_DISCARD`, a waitable object via `SetMaximumFrameLatency(1)` and `GetFrameLatencyWaitableObject`), cutting about a frame of latency in published tests.
- Linux/Wayland: [`wp_presentation`](https://wayland.app/protocols/presentation-time) feedback gives real present timestamps; [`wp_commit_timing_v1`](https://wayland.app/protocols/commit-timing-v1) (staging, 2024–25) lets clients target a presentation time; [`wp_fifo_v1`](https://wayland.app/protocols/fifo-v1) gives proper vsync-paced commits. Use for pacing when supported.
- Rune use: a `PresentClock` trait per shell that exposes `next_present_deadline()` and `actual_present_time(frame)`. The render thread schedules: input latch → spring eval at *target present time* → encode → submit with slack about 1–2 ms before deadline. This unifies with the analytic springs (evaluated at the exact predicted display time, which removes judder).
- Risk: per-platform code and wgpu limits (wgpu hides presentation timing; may need to bypass wgpu surface presentation on Apple via `CAMetalLayer` directly, which the plan seems to allow). Verify `wgpu` exposes a frame-time hint, else raw `CAMetalLayer`.
### 13. Frame pacing research — **adopt (principles)**
- [Android Frame Pacing / Swappy](https://developer.android.com/games/sdk/frame-pacing) and Apple's own docs agree: pace on the display timeline, not on a timer; drop to a stable lower rate instead of oscillating; and measure present-to-present deltas, not frame times. Related research on input-to-photon (e.g., [Nvidia Reflex](https://www.nvidia.com/en-us/geforce/technologies/reflex/) cuts system latency by pacing CPU submission so the queue stays empty) is the same just-in-time idea as item 12.
- Rune use: keep render queue depth at 1; the render thread **sleeps until deadline minus a measured encode+GPU time budget (EWMA with a p99 margin)**, then latches. Trace it per frame in the frame traces the plan already wants.
### 14. Perceptual latency thresholds — **use as targets**
- Ng, Lepinski, Wigdor, Sanders, Dietz, [*Designing for Low-Latency Direct-Touch Input* (UIST 2012)](https://dl.acm.org/doi/10.1145/2380116.2380174): people notice improvement down to about 1 ms in direct touch dragging; 10 ms is the commonly noticed "feels connected" edge; and the follow-up [*How Fast is Fast Enough?* (CHI 2013, Jota et al.)](https://dl.acm.org/doi/10.1145/2470654.2481317) found dragging at 1 ms vs 10 ms vs 50 ms are differentiable. Microsoft Research's demo of 1 ms touch is the source of the "1 ms touch" claim.
- Rune use: budget for drag-follow: iOS hardware floor is about 2 frames at 120 Hz (≈16 ms) with prediction offsetting about 1 frame; set CI gates on measured touch-to-present (via high-speed camera in the lab later; via `presentedTime` minus event timestamp in software now). Launch: ≤ 100 ms is "instant"; the plan's 50 ms is well inside it.
### 15. Immediate draw on input for small updates — **spike**
- Draw feedback (press state, caret, drag handle) directly in the render thread without waiting for the main/UI thread to run layout/tree diff: input thread → render thread message → patch a retained "overlay" layer. This is what Core Animation's render server gives SwiftUI for free (`CAAnimation` runs out of process).
- Rune use: the render thread owns an "interaction layer" of transform/opacity/color overrides keyed by node id, updated by input events directly with analytic springs, so a press response never waits on the app thread. The app tree later confirms. Risk: two sources of truth; mitigate by making overrides explicit, ephemeral and traced.
## Steal
- iOS snapshot + paint-holding handoff policy (1–3).
- Impeller's "no runtime shader compilation" rule (8).
- Late latching and Reflex-style just-in-time submission (10, 13).
- Chromium's predictor families and its habit of testing predictors on recorded traces (11).
- Emacs/Node idea of loading precomputed state instead of computing it, restricted to pure data (6).
- Order files / Propeller for page-in (7).
## Avoid
- Full process checkpointing (CRIU/CRaC) — not portable to macOS/iOS and GPU state does not survive.
- Showing a stale snapshot for user-private or fast-changing views without a flag.
- Predicting beyond ~1 frame or committing predicted state to model data.
- Relying on BOLT for Mach-O (ELF-centric); use `-order_file`.
- Per-frame heap allocation or lock contention in the late-latch path.
## Recommendation for Rune (ranked)
1. **Static pixel layer + bit-identical handoff gate** (items 1–4). Make it the first milestone shell feature; CI asserts max-delta and launch timeline.
2. **Precompiled shaders + Metal binary archive + parallel init critical path** (8, 9). Biggest controllable chunk of the 50 ms budget.
3. **Frame clock built on `CAMetalDisplayLink` with just-in-time latch and analytic springs evaluated at the target present time** (12, 13, 10).
4. **Coalesced+predicted touch pipeline with recorded-trace replay tests** (11).
5. **Order-file/PGO startup layout pipeline and cached shaped-text/atlas snapshot** (6, 7).
Rejected: process snapshot (6, full); runtime shader JIT; fixed-offset vsync timers.
## Open questions
- Does wgpu expose enough presentation control on Metal (target timestamps, drawable count, `presentedTime`), or must the Apple shell own `CAMetalLayer` directly?
- Achievable max pixel delta between the CPU/headless snapshot and live GPU frame on each Apple GPU family; is tolerance + 1-frame fade enough to be invisible?
- Real wgpu device init and first-`nextDrawable` costs on M-series cold boot (measure on a reserved Mac, not a developer's desk display).
- Size and decode cost of embedded snapshots across appearance × scale × window-size variants; do we store raw, lz4, or BC7?
- iOS: can a launch-screen replacement be a CALayer image set before `didFinishLaunching`, or must it be a storyboard/`UILaunchScreen` image? (The latter requires a static asset, so the build must emit a PNG into the asset catalog.)
- Which predictor (Kalman vs least-squares) performs best on Rune's own recorded drag traces?
@@ -0,0 +1,255 @@
# 14. Determinism, verification and testing: cutting-edge ideas for Rune
Scope: tenet 7 (fast path + reference path, exact counters, instant checks) and §6b (same pixels everywhere,
bug reports are replays, every pixel traces to code). Written 2026-10-21.
**Provenance note.** Web search was down while writing. Items marked **[read]** I verified in source or docs this
session (vello checkout, WGSL spec, gungraun/FLIP/Kani/shuttle READMEs). Items marked **[recalled]** are from
memory of papers and tools and need a link check before anyone relies on a number.
## Summary
- The right architecture is already proven upstream: **Vello ships a `cpu_gpu_differential` cargo-fuzz target** that
generates bounded structured scenes (shapes, strokes, gradients, clips, layers), renders with `vello_cpu` and
`vello_gpu`, and compares RGBA8 with a per-channel tolerance (default 2, ≤4 outlier pixels)
[read: `vello/fuzz/README.md`]. Rune's "reference renderer vs fast renderer" is this, with Rune's own scene model.
- **Bit-exact across GPUs is not available from WGSL/wgpu**: the spec lets an implementation reassociate, fuse
(FMA), and use lower accuracy [read: WGSL §15.7.4–5]. So "same pixels everywhere" must be a *CPU-reference* lane
(integer/fixed-point, exact), and GPU lanes are tolerance lanes. Don't chase GPU bit-exactness; chase a *bounded
error with a proven budget*.
- A **u8/fixed-point CPU pipeline is the determinism anchor.** `vello_cpu` has a `u8_pipeline` (integer math) and an
optional `f32_pipeline`, plus a `libm` feature so float functions don't depend on the platform libc [read:
`vello_cpu/src/lib.rs`]. Integer math + `libm` + no FMA contraction gives identical bytes on x86 and arm64.
- **Perf gates by instruction count** (gungraun / iai-callgrind, CodSpeed) are exact and noise-free in virtualised CI
[read: gungraun README], but Valgrind does not run on macOS arm64; run those on Linux (a Linux
runner) and use Apple counters (`kpc`/Instruments) only for reserved-hardware confirmation.
- **Record/replay at the app level beats `rr`.** Rune owns the clock, input and randomness, so a deterministic
event-log replay (KBs) gives most of rr/Pernosco's value on macOS/iOS, where rr does not run [read: rr README lists
Linux only; Apple Silicon unsupported].
- **Concurrency**: the render thread/main thread handoff is small enough for **shuttle** (randomized, replayable
schedules) and **loom** (exhaustive, tiny models) [read: shuttle README]. Cheap, high value.
- **Verification**: Kani (bit-precise model checking, strong for `unsafe` and overflow in fast-path kernels) is the
practical formal tool; Verus only for 1–2 core invariants. Agents are good at writing Kani harnesses and
specifications, which was the bottleneck for humans.
## Findings
### 1. Differential fuzzing of fast path vs reference (adopt now)
- Source: Vello's [`fuzz/` target](https://github.com/linebender/vello/tree/main/fuzz) [read]; cargo-fuzz +
`arbitrary` for structured inputs; Vello also keeps `fuzz_regression.rs` so every crash becomes a snapshot test
(tolerances recorded with the case) [read].
- Achieves: finds backend divergences automatically; the README notes known-different features (image quality
Medium/High) are excluded so they don't drown new findings. That is the workflow lesson: **grow the generator
feature by feature with a ratchet**.
- Rune: one `Scene` generator (`arbitrary`) feeding *all* subsystems: layout (fast SoA Taffy-like vs a naive
recursive reference), springs (analytic closed form vs fine-step RK4 integration at 1e-6 dt), text (cached shaping
vs fresh), renderer (GPU vs CPU reference). Tolerance modelled as (max channel diff, max outlier count), exactly
Vello's. Every fuzz crash is auto-minimised (`tmin`) and committed as a named regression scene.
- Cost: low; generator maintenance. Risk: tolerance creep. Mitigation: tolerance is per-primitive and recorded;
CPU fast path vs CPU reference is **zero tolerance**.
- Verdict: **adopt now.** Spike S: copy Vello's harness shape in the first renderer milestone.
### 2. A zero-tolerance exact lane built on integer/fixed-point CPU rendering (adopt now, scoped)
- Source: `vello_cpu` u8 pipeline + `libm` feature [read]; `tiny-skia` (Skia subset, SIMD with scalar fallbacks)
[read README]; Skia's own GM tests live on a CPU "raster" backend as the baseline for GPU backends (Skia Gold
compares across OS/arch/backend dimensions, >500k images per commit) [read:
[docs](https://docs.skia.org/docs/dev/testing/skiagold/)].
- Achieves: bytes identical on any machine, so goldens are hashes, not images with fuzz.
- Rune: canonical goldens come from the CPU reference renderer. Rules for exactness: no FMA contraction (`-C
llvm-args=-fp-contract=off` or explicit `mul_add` ban via clippy `disallowed_methods`), no float `sum()` with
platform-dependent order, `libm` for transcendental functions, fixed iteration order, no HashMap iteration in
render paths, pinned font bytes. Add a CI job that runs the *same* binary tests on x86-64 Linux and arm64 macOS and
compares hashes; a mismatch is a hard failure that names the first differing scene.
- Cost: the CPU path must implement every primitive (UberQuad, glyph sprites, gradients, blur). That is already in
the plan (§4.3 differential renderer). Risk: reference renderer drifts from "what the GPU should do"; the
differential fuzz in item 1 is the leash.
- Verdict: **adopt now**; this is the plan's "canonical lane".
### 3. GPU float divergence: bound it, don't forbid it (adopt now as policy)
- Source: WGSL spec §15.7.4/5: implementations may reassociate, fuse, and be more or less accurate than the
reference formula [read]; NVIDIA FLIP's precision note lists FMA, sqrt precision, and loop order as the reasons
five implementations of one metric never match bit-for-bit [read:
[precision.md](https://github.com/NVlabs/flip/blob/main/misc/precision.md)].
- Rune: write shaders in a **conservative numeric style**: premultiplied u8 / unorm in, fixed-point coverage
(analytic AA from integer edge functions where possible, e.g. 8.8 subpixel positions snapped on CPU), quantize
positions to 1/64 px on CPU before upload (already in §6b), keep the GPU doing only blend/sample of values the CPU
decided. The more decisions are made in integers before the GPU, the smaller the cross-vendor surface. Then measure
the residual: render the scene corpus on M-series, an NVIDIA box, and software Vulkan (lavapipe) via wgpu, record
max per-channel error per primitive, and make that table the tolerance budget.
- Metal on Apple is one vendor family, so for macOS/iOS exact GPU hashes on a pinned device are plausible; treat
as a bonus lane, not the contract.
- Verdict: **adopt now** (policy + a one-off measurement spike, 1 day).
### 4. Perceptual diff: FLIP plus a "does it matter" gate (spike)
- Source: [NVIDIA FLIP](https://github.com/NVlabs/flip) (LDR/HDR-FLIP, v1.7, in Ray Tracing Gems II; Rust port exists
in the wild [recalled]); Skia Gold's triage model (positive/negative digests, baselines outside git) [read].
- Achieves: error maps that weight differences by human sensitivity; pooled score per image.
- Rune: for the *tolerance lanes* only (GPU vs CPU reference, cross-vendor), fail on `max(FLIP) > t` **or** a
count of outlier pixels, whichever is stricter; exact lane stays hash-equal. Output FLIP heatmaps next to
expected/actual/diff so an agent (or Kit) sees where. Don't use SSIM as the gate (blind to smooth gradient banding,
which Rune cares about: dithering).
- Gold-style: store baselines as content hashes outside git (or in a `goldens/` manifest of hashes + a blob store),
triage by "blame" commit. Overkill for a solo repo now; useful once multi-platform baselines multiply.
- Verdict: **spike** FLIP on the tolerance lane; **later** a Gold-like service.
### 5. Metamorphic testing for layout and rendering (adopt now; cheap, finds real bugs)
- Source: metamorphic testing literature applied to GUIs/renderers (e.g. graphics-shader compiler testing with
semantics-preserving transforms in GraphicsFuzz/glsl-reduce, Donaldson et al. [recalled]; browser-layout
differential/metamorphic work such as "Hidden costs of browser layout" style studies [recalled]). Treat as
technique, not a specific citation.
- Relations Rune can assert without any oracle:
1. **Translation invariance**: shift a subtree by integer px → output identical, shifted (exact on CPU lane).
2. **Wrap invariance**: wrapping a node in a zero-style container or a no-op opacity(1) layer does not change
pixels (catches layer/clip bugs; should be bit-equal).
3. **Order independence** of non-overlapping siblings.
4. **Resize monotonicity**: widening a container never increases text line count; height never shrinks when text
scale grows (catches layout/shaping cache bugs).
5. **Scale equivariance**: 2x scale-factor render, downsampled, is within tolerance of 1x render for vector content.
6. **Retained vs immediate**: building the tree fresh vs mutating from a prior state gives identical output
(catches stale-cache bugs: the classic retained-UI bug class). This is the highest-value relation.
7. **Time-split invariance for springs**: stepping 1×16.6 ms == 2×8.3 ms == 1×(seek 16.6 ms) within 1e-9 (analytic
springs make this *exact up to rounding*; a rare property few frameworks can claim).
8. **Interrupt composition**: retarget at t, then evaluate: position and velocity continuous at t.
- Cost: tiny; each is ~30 lines over the scene generator. Verdict: **adopt now.**
### 6. Property-based and model-based UI testing with stateful shrinking (adopt now)
- Source: proptest state-machine testing / `proptest-state-machine` and quickcheck-style model tests; Hypothesis
stateful testing [recalled]; Elm/Redux reducers as the model [recalled].
- Rune: model = a trivial `Vec<Item>` / form state; SUT = the real tree + reconciler + keyed diff + enter/exit.
Generated operations = insert/remove/move/reorder, input events with timestamps, resize, time advance. Properties:
identity preserved across moves (same node id → same spring state), no node unmounted at opacity > 0, a11y tree
equals view tree, scroll offset clamped, no panics. Shrinking yields a *minimal event script* that is directly a
replay file (item 8). Agents love this: the failing case is a 6-line JSON.
- Verdict: **adopt now.** Pair with the same generator as item 1.
### 7. GUI fuzzing and agentic exploration (later / spike)
- Source: Android GUI testing research (Monkey, Sapienz, Stoat, APE) [recalled]; LLM-driven GUI exploration papers
2023–2025 (e.g. GPTDroid-style, VisionDroid-style) [recalled; unverified numbers]; Skia's fuzzing doc [link in
Skia docs sidebar, not read].
- Rune advantage: no need for pixel/OCR-based exploration. The inspector exposes the semantic tree (roles, rects,
actions), so **coverage-guided event fuzzing over the a11y tree** is straightforward: choose among actionable
nodes, inject scripted input, coverage = distinct (node-role, state-hash) pairs plus code coverage (`-C
instrument-coverage`). Run the fuzzer with a fake clock so it's thousands of interactions per second headless.
- Oracles: no panic, no layout or motion linter finding, no hitch beyond budget in the counter model, tree
invariants. The internal motion linter as a *fuzz oracle* is a genuine differentiator (finds pops under random interrupt
sequences).
- Verdict: **spike** after the scene/inspector exist; the LLM-guided variant is **later**.
### 8. Record/replay: app-level event log, with rr only as a Linux escape hatch (adopt now)
- Source: [rr](https://github.com/rr-debugger/rr) (Linux; README lists kernel ≥4.7, and some AArch64 parts) [read],
[Pernosco](https://pernos.co) (omniscient debugging on rr traces) [recalled], Replay.io (browser/Node
record-replay with app-level instrumentation) [recalled], Elm/Redux time-travel [recalled].
- Why not rr: it records syscalls and hardware events on Linux; Metal/CoreAnimation/AppKit are out of reach on macOS.
- Rune: inputs + clock + RNG + window metrics + font/asset manifest + environment hash are the *only* nondeterminism
inputs (tenet: fixed clock, seeded randomness). Log them as a compact binary/JSONL stream; replay through the
headless CPU renderer to identical pixels (the §6b "bug reports are replays" guarantee). Add:
- **Periodic keyframes**: snapshot of state (arena dump) every N frames so replay can *seek* in O(N frames) and
support reverse-step by replaying from the previous keyframe (cheap time-travel debugging, the Elm trick).
- **State-hash per frame** in the log; on replay, first mismatching frame hash localises nondeterminism instantly
(this is how deterministic game engines and lockstep netcode find desyncs [recalled]).
- A `--chaos` mode that perturbs scheduling (shuttle, item 10) and asserts frame hashes unchanged.
- On Linux CI only, run failing replays under `rr record` and attach the trace for Pernosco if a crash is native.
- Verdict: **adopt now** (log + state-hash + keyframes); rr/Pernosco **skip** for macOS, **later** for Linux crashes.
### 9. Exact performance counters in CI (adopt now, with a platform split)
- Source: [gungraun](https://github.com/gungraun/gungraun) (successor of iai-callgrind; instruction counts,
estimated cycles, DHAT, one-shot runs, usable in noisy virtualised CI; v0.20 on crates.io) [read];
[iai](https://github.com/bheisler/iai) the cachegrind original [read]; CodSpeed (CPU-simulation instrument
based on Valgrind, plus walltime on dedicated macro runners) and Bencher (tracks metrics incl. iai instruction
counts with statistical thresholds) [recalled; docs pages 404'd on fetch, verify].
- Rune: bench the *pure* functions (layout of a fixed scene, spring step for N springs, glyph run encode, CPU
rasterise a tile) under gungraun on Linux: instruction count, L1/LL misses, and **DHAT heap allocations** (this is
the "zero allocation per frame" gate, stronger than a counting allocator because it also reports bytes and sites).
Gate: >0.5% instruction regression fails the PR; the failing report includes callgrind diff by function so an
agent can fix it. Wall-clock on reserved hardware only as confirmation, because instruction count ≠ time on Apple
silicon.
- Caveat: Valgrind is not supported on macOS arm64, and instruction counts on x86-64 Linux don't predict Apple
cache/NEON behaviour. Use for regression detection and algorithmic cost, not absolute 8.33 ms claims. For the
latter: model budgets in counted units (instances, glyphs, nodes) which are platform independent (already planned).
- Verdict: **adopt now** (gungraun; pick CodSpeed/Bencher later only if a hosted trend UI is wanted).
### 10. Deterministic concurrency testing of the render-thread handoff (adopt now)
- Source: [shuttle](https://github.com/awslabs/shuttle) (randomized scheduler incl. PCT with probabilistic
guarantees; replayable failing schedules; wrappers for tokio/rand) [read]; [loom](https://github.com/tokio-rs/loom)
(exhaustive C11 memory-model exploration; small models only) [recalled]; Antithesis-style whole-system
deterministic simulation [recalled, commercial, skip].
- Rune: the main↔render thread protocol (triple-buffered target/command queue, spring track updates, input timestamp
handoff, frame-in-flight counting) should be a small isolated module whose sync primitives go through a `rune_sync`
facade (`std::sync` in prod, `shuttle::sync`/`loom::sync` under `cfg`). Test: random schedules x thousands; the
invariant is "presented frame sequence is a function of (input log, clock) only", which is the §6b replay
guarantee under concurrency. Failing schedule is a seed that reproduces exactly.
- Cost: facade discipline (agents handle that well). Risk: loom state explosion; keep models to 2–3 threads.
- Verdict: **adopt now** for the handoff; the rest of the app is single-threaded by design.
### 11. Practical formal methods: Kani first, Miri always, Verus selectively (spike)
- Source: [Kani](https://github.com/model-checking/kani) (bit-precise model checker, UB detection for `unsafe`,
function contracts, Linux/macOS) [read]; AWS/Rust Foundation [std-library verification
effort](https://github.com/model-checking/verify-rust-std) with Kani, Verus-adjacent tools, VeriFast, Flux, etc.
[read]; [Verus](https://github.com/verus-lang/verus) (SMT-checked Rust subset; Atmosphere/other large proofs)
[read README; case studies recalled]; Miri for aliasing/UB in `unsafe` SIMD-adjacent code [recalled].
- Rune fits: small `unsafe` kernels (SoA arena index math, SIMD tile blend, arena free-list, fixed-point rounding)
are exactly where Kani proves "no overflow/OOB for all inputs" in seconds and where an agent can write both the
harness and the `#[kani::proof]`. Examples worth proving: `blend_u8(a,b)` equals the reference
`(a*b+127)/255`-style formula for all 2^16 inputs (exhaustive, can also just be a brute-force test: **prefer
brute-force for 8/16-bit domains**); arena generation counters never alias; 26.6 fixed-point snap is idempotent.
- Verus: only if a core invariant resists testing (e.g. keyed-diff reconciliation preserves identity). Heavy; mark
**later**.
- Miri: run the whole unit suite under Miri nightly on the non-GPU crates; any `unsafe` merged without Miri green is
rejected. Verdict: Miri **adopt now**, Kani **spike** (1 kernel), Verus **later**.
### 12. Pixel provenance / trace-to-source (adopt now, half of it is already in the plan)
- Source: general ideas: Chrome DevTools paint-flashing/"layer reasons", Flutter DevTools "creation location" of
widgets (`debugCreator`/inspector `creationLocation`) [recalled], React `__source`.
- Rune: stamp each node with `file:line` at construction (`#[track_caller]` is free); renderer emits a compact
**ID buffer** (u32 node id per pixel/tile) *only in debug/CI snapshot mode*, a second attachment on the CPU
reference renderer (zero cost on the fast path). With it, `mk inspect --at x,y` returns the topmost node, the whole
stack of contributors at that pixel (blend order), their `file:line`, and spring tokens. Diff reports then
*blame by node*: "37 px differ, all belong to node #412 `pill.rs:88`, whose shadow radius changed from 12.0 → 12.5".
That turns a screenshot diff into a semantic diff that an agent can act on without looking.
- Extension: **semantic diff first**: diff the (tree, layout rects, style hashes, spring states) before pixels;
report "layout unchanged, only shadow colour changed" so pure-visual changes are separated from layout changes.
- Cost: modest on the CPU renderer; risk none to production. Verdict: **adopt now** (CPU ID buffer + semantic diff).
### 13. Frame-hash goldens with auto-explanation (adopt now)
- Rune: golden = BLAKE3 of the CPU frame plus the stored PNG only on failure (artifacts as expected/actual/diff/
FLIP/ID-blame). `mk snap --bless` rewrites hashes; blessing prints which scenes changed and their semantic diff so
an agent reviewing a PR sees intent. Per-scene sequence goldens (hash at t = 0, 0.1, … s) cover motion
deterministically, because the clock is fixed; this *is* motion regression testing with no video.
- Verdict: **adopt now.**
## Steal
- Vello's `cpu_gpu_differential` fuzz target, tolerance model and regression-snapshot loop.
- `vello_cpu`'s dual u8/f32 pipeline idea (fast integer vs accurate float) and `libm` feature for portable floats.
- gungraun's one-shot instruction/DHAT gating; callgrind per-function diffs in the failure report.
- shuttle seeds as replayable schedules; Elm-style keyframed time travel; lockstep-game state-hash desync detection.
- Skia Gold's baselines-by-hash with blame-based triage (later).
- FLIP for tolerance lanes, with its explicit precision caveats.
## Avoid
- Promising GPU bit-exactness across vendors (WGSL forbids relying on it).
- SSIM/PSNR as the sole gate. Wall-clock benchmarks on shared CI. Full-system rr/Pernosco on macOS.
- Verus across the codebase; proof effort exceeds benefit outside tiny kernels.
- Fuzzing with tolerances so loose that they hide regressions; keep exact lanes exact, record every tolerance.
## Recommendation for Rune
1. Build CPU reference renderer as integer/`libm`, zero-FMA, hash-golden canonical lane; GPU lanes use measured,
per-primitive tolerance budgets (items 2, 3).
2. One structured `Scene` generator drives differential fuzz, metamorphic relations, and stateful model tests (1, 5,
6). Failures auto-minimise to replay scripts.
3. App-level replay with state hashes and keyframes (8); gungraun gates on Linux (9); shuttle for the handoff (10);
Miri on every PR (11).
4. CPU ID-buffer and semantic diff for blame (12). FLIP and Kani as spikes.
Rejected: rr/Pernosco as the main replay story (platform), CodSpeed/Bencher as required infra (nice-to-have),
Verus broadly, GPU-exact hashing as the contract, Gold as a service (premature).
## Open questions
- Can arm64 macOS and x86 Linux give identical CPU-lane bytes with auto-vectorised code? Needs an actual two-machine
hash test (the CPU lane may need explicitly-scalar or fixed-width `fearless_simd`-style kernels for exactness).
- Is the Apple GPU deterministic enough run-to-run (same device, same driver) for exact hashes as a bonus lane?
Likely yes; unmeasured.
- Does text shaping (Parley/HarfRust) output remain bit-stable across versions and platforms with pinned fonts?
Pin versions and add a shaping-hash lane.
- Instruction counts on Linux x86-64 vs Apple arm64: how well do they correlate for Rune's kernels? Calibrate once on
a Mac with `kpc` counters.
- Exact figures for CodSpeed/Bencher/Replay.io/GUI-fuzzing papers need verification when search is back.
@@ -0,0 +1,231 @@
# 15 · Motion, perception and feel: research and tricks Rune can exploit
Scope: smoothness/judder perception, frame-time variance, motion blur at high refresh, direct-manipulation latency,
spring vs easing, interruptibility, Apple/Google fluid-interface research, crisp moving text, layout animation, velocity
estimation, scroll physics, and automatic smoothness metrics. Written 2026-10-21 for Rune ([PLAN §4.9, tenet 7, §6b](../PLAN.md)).
**Source quality legend.** *[read]* = I opened the source/paper page in this session. *[recall]* = from memory of the
talk/paper/source; cite-check before it goes into a spec. Numbers I could not verify are marked *(est.)*.
Rune's differentiators used throughout: analytic springs (exact x and v at any time), a render thread that owns every
presented value, a deterministic clock, and agents who can maintain fast-path + reference-path pairs.
## Summary
1. **Sample at the presentation time, not at "now".** Frame-time *variance* matters more than average fps, and with
analytic tracks the cure is free: evaluate every track at the display's *target presentation timestamp*. A late
frame then shows the right place instead of a velocity hiccup. (NVIDIA/UCSB: 12 ms of frame-time variation
measurably degrades perceived smoothness, 4 ms barely does. [read])
2. **Smoothness metric = pixel error, not frame count.** Judder visibility is `velocity × timing error` in px/arcmin.
Rune can compute, per frame and per node, `|rendered_pos − ideal_pos(t_present)|` exactly, plus Apple's hitch-time
ratio. No other toolkit can score smoothness this precisely, because none owns both the ideal and the presented value.
3. **Late-latch input on the render thread.** Direct-manipulation latency down to ~1–10 ms is perceptible in dragging
(Ng/Jota, Microsoft Research [recall]). Sample the pointer at the last moment before encode, resample to the
presentation time like Android does, and extrapolate ≤ ~8 ms.
4. **Velocity: ship Android's impulse estimator** plus an LSQ2 reference, with a 100 ms horizon and a 40 ms "stopped"
rule. Differential-test both against a recorded gesture corpus, and tune the choice by post-release prediction error.
5. **Text under motion is a policy, not a flag**: vertical snap + ¼-px horizontal phases in grayscale while moving,
exact analytic settle time, then a sub-¼-px rest snap. Verify with a phase-sweep harness an agent can run.
6. **Layout animation by rect-space FLIP on presented rects**, never scale correction (Rune's edge tracks already avoid
it), with *glyph/word-level FLIP* for text reflow as a distinctive spike.
7. **Effects springs ≠ spatial springs** (Material 3 Expressive): opacity/colour/blur channels never overshoot.
8. **Scroll/fling are analytic**: `x(t)` closed form (iOS 0.998/ms, Android spline) so they are frame-rate independent
and retargetable; project the landing point and hand velocity to a spring for snapping.
9. **Synthetic motion blur: skip at 120 Hz**; keep a velocity-gated spike for flings, because Rune knows `v` exactly.
10. **Perception ground truth is thin for springs vs easing**; use Kit's blind A/B chooser (Bradley–Terry) as the oracle
and build it into `mk tune`.
---
## Findings
### 1. Present-time sampling and frame pacing — **adopt now**
- **Source:** NVIDIA Research, Klein/Spjut/Boudaoud/Kim, "Variable Frame Timing Affects Perception of Smoothness in
First-Person Gaming," IEEE CoG 2024 ([page](https://research.nvidia.com/publication/2024-08_variable-frame-timing-affects-perception-smoothness-first-person-gaming),
[arXiv](https://arxiv.org/abs/2306.01691)) [read]. Android FrameTimeline classifies jank by *predicted vs actual
present time*, and flags BufferStuffing as a latency state even when cadence is smooth ([Perfetto](https://perfetto.dev/docs/data-sources/frametimeline)) [read].
- **What it shows:** frame-time variation of ±4–12 ms around 30–240 Hz; 12 ms degrades perceived smoothness, 4 ms has a
diminished effect. Average fps alone doesn't predict it. A 120 Hz period is 8.33 ms, so *one* skipped vsync is already
in the "visibly bad" regime. Practical corollary: at 120 Hz a frame that misses by half a period matters, at 60 Hz
the same absolute miss is a smaller fraction.
- **Rune use:** on Apple use `CAMetalDisplayLink`/`CADisplayLink` `targetTimestamp` / `targetPresentationTimestamp`
as the sample time `t_present` for all tracks; on other platforms use the compositor's predicted present time
(Android Choreographer vsync id/`AChoreographer` frame time, Wayland presentation-time, DXGI `GetFrameStatistics`,
WebGPU: `rAF` timestamp + one period). Never `Instant::now()`. A hitch becomes a one-frame *temporal* gap with
correct geometry instead of a speed discontinuity. Use `wgpu` `desired_maximum_frame_latency = 1` (2 = stuffing).
- **Cost/risk:** low; one-time plumbing per platform. Risk: platforms that don't expose a prediction (web). Fallback: previous frame timestamp + period.
- **Verdict:** adopt now. It is the single highest-leverage item: all other metrics presuppose it.
### 2. Metrics a frame trace can compute that track perceived smoothness — **adopt now**
Rune records, per frame: `t_target`, `t_actual_present` (where the OS reports it), `t_sample`, and per animated node
`x_rendered`, `x_ideal(t_actual)` (exact from the track), `v`. From that (all computable headlessly with the fake clock
injecting synthetic delays):
| Metric | Definition | Why it correlates |
|---|---|---|
| **Hitch time ratio** | Σ(excess present-interval over expected) ÷ animation duration, ms/s | Apple's own: WWDC20 "Eliminate animation hitches with XCTest" and WWDC21 "Detect and diagnose hitches" use thresholds ≈ < 5 ms/s good, 5–10 warn, > 10 critical [recall]. Use as the CI gate shape. |
| **Cadence deviation** | σ and max of `present_interval − period`, in periods | NVIDIA result above: variance, not mean. |
| **Position error px** | `|x_rendered − x_ideal(t_actual)|` per node per frame; report p99 and max | Judder visibility ≈ `v · Δt` in px; threshold in arcmin using the device's ppi and viewing distance (iPhone ≈ 460 ppi @ 35 cm ⇒ 1 px ≈ 0.55 arcmin, below acuity, but motion hyperacuity is finer). |
| **Visual jerk** | 3rd difference of presented position over *presented* frames, normalised by peak speed | Catches velocity snaps that hit-time metrics miss (e.g., retarget bugs). The motion linter's "velocity snap" rule, made exact. |
| **Velocity continuity at retarget** | `|v_after − v_before|` at every segment boundary (should be 0 up to float eps) | Exact in analytic tracks; interruption bugs show instantly. |
| **Input-to-photon (virtual)** | `t_present − t_input_hw` per touch-driven frame | Latency budget; reported per frame; trend on reserved hardware. |
| **Scroll Jank v4-style** | Chrome's per-frame scroll jank counting across input/frames ([blog, 2023](https://blog.google/chromium/smoother-scrolling-how-we-halved-scroll-jank-in-chrome-on-android/); [Chromium post](https://blog.chromium.org/2023/08/smoothing-out-scrolling-experience-in.html)) | Halved scroll jank by ensuring consistent input-to-frame delivery [read headline]. Copy the *definition*, not the code. |
- Android **JankStats / FrameMetrics / FrameTimeline** give the vocabulary ("deadline missed", "buffer stuffing",
"prediction error") that Rune's hitch attribution should reuse: charge each hitch to a phase (view, layout, shape,
encode, GPU) as PLAN §6b already says.
- **Agent trick:** since the clock is fake, run every scene through a *jitter fuzzer* (inject present-interval noise of
0/4/12 ms σ, drop 1 in N frames) and assert that position-error stays ≤ ε. This proves "time-correct sampling" holds
for every animated property, which nobody can claim for hand-written animation systems.
- **Verdict:** adopt now; it is mostly arithmetic over the trace Rune already plans to emit.
### 3. Direct-manipulation latency, late latching, resampling, prediction — **adopt now (late latch + resample), spike (prediction)**
- **Sources:** Ng, Lepinski, Wigdor, Sanders, Dietz, "Designing for Low-Latency Direct-Touch Input," UIST 2012;
Jota, Ng, Dietz, Wigdor, "How Fast is Fast Enough?" CHI 2013 ([PDF](https://www.tactuallabs.com/papers/howFastIsFastEnoughCHI13.pdf)) [recall; the PDF did not extract here].
Headline as I remember it: drag-tracking differences are perceptible at single-digit ms (≈ 1 ms vs 10 ms users could
tell), tapping tolerates more (tens of ms), and performance degrades measurably by ≈ 10–25 ms. *Verify exact numbers before quoting.*
- **Android input resampling** (read in AOSP `InputConsumer.cpp` [read]): sample time is `frame_time − RESAMPLE_LATENCY (5 ms)`;
interpolate between two events if available; otherwise extrapolate, only if events are ≥ `RESAMPLE_MIN_DELTA (2 ms)`
apart, treating gaps > `RESAMPLE_MAX_DELTA (20 ms)` as too stale, and cap extrapolation at
`min(delta/2, RESAMPLE_MAX_PREDICTION = 8 ms)`. These are tuned constants Rune can start from.
- **Android MotionPredictor / AndroidX `motionprediction`:** Kalman-based pointer predictors whose prediction amount
depends on "speed and jank" ([AndroidX source](https://android.googlesource.com/platform/frameworks/support/+/57cb7c62c62fe4c95643d4777db) , Kalman `SinglePointerPredictor`) [read search result]. iOS: `UIEvent.predictedTouches`
and `coalescedTouches` (UIKit) [recall]. Chrome: input resampling + scroll prediction filters [recall].
- **Rune use:** (a) the render thread reads raw pointer events (hardware timestamps) and *samples the latest position
immediately before encode*, instead of reading app-thread state; (b) resample to `t_present − ~5 ms` with the AOSP
rules; (c) coalesced events go into the velocity estimator at full rate (see §4); (d) optional: Kalman/linear
extrapolation capped at 8 ms *only for dragged objects*, with a no-snap blend when the real sample arrives; never for scroll content under the
user's finger unless measured as better.
- **Cost/risk:** (a–c) low and fits PLAN §4.9 "drags apply 1:1 on the render thread". (d) prediction overshoot at
reversals; gate by position-error metric on a recorded gesture corpus; ship off by default.
- **Verdict:** a–c adopt now; d spike.
### 4. Gesture velocity estimation — **adopt now**
- **Source:** Android `VelocityTracker` impulse strategy ([AOSP `VelocityTracker.cpp`](https://android.googlesource.com/platform/frameworks/native/+/refs/heads/main/libs/input/VelocityTracker.cpp)) [read].
The file documents a physical model: treat the touch as an object whose kinetic energy at release equals the total work
done by the finger; `v_final = sqrt(2·Σ(Δv·|v|))` per segment, with the sign handled by `|v|` so braking subtracts
energy; an initial-condition choice (v₀ = 0 vs already moving → ½v₁² start) is spelled out. Uses a ~100 ms history horizon;
`ASSUME_POINTER_STOPPED_TIME = 40 ms` means a pause before release gives ~0 velocity [read]. The old default was LSQ2
(2nd-order least squares over the horizon), now an alternative strategy; Flutter's tracker is a polynomial LSQ with a similar horizon and stop rule [recall].
- **Why it matters:** velocity handoff is the "release feel" (Apple's central rule: continue with the finger's velocity).
LSQ is noisy at the endpoint (it fits the middle of the window), impulse is robust to jitter and un-ringing.
- **Rune use:** implement both (reference = LSQ2 in f64, fast = impulse over a ring buffer), use hardware timestamps,
include coalesced samples, apply the 40 ms stopped rule, clamp to a platform max fling speed. **Agent trick:** record a corpus of real
gestures (Kit's iPhone + Mac trackpad) with the trace recorder; score each estimator by how well `x(t_release) + ∫v`
predicts the *finger's next 30–50 ms if it hadn't lifted* (use gestures cut at random points); pick/tune constants by minimising that error.
Fixed hand-tuned constants are the norm elsewhere; an offline fit is cheap for agents.
- **Cost/risk:** tiny. Risk: trackpad momentum on macOS is OS-generated (§8), so this is for touch and pointer drags.
- **Verdict:** adopt now.
### 5. Springs, retargeting, projection, effects vs spatial (Apple and Material) — **adopt now**
- **WWDC18 "Designing Fluid Interfaces"** (session 803, Karunamuni/Alonso) [recall]: response/damping ratio over
duration; interrupt and redirect without waiting; fluid gestures never wait for the previous animation; momentum
projection `dest = x + v·rate/(1−rate)` using the scroll deceleration rate; rubber banding `f(x) = (1 − 1/(x·c/d + 1))·d`
(c ≈ 0.55); velocity handed from the gesture into the spring. WWDC23 "Animate with springs" introduces duration+bounce
and `.smooth/.snappy/.bouncy`: Rune's parameterisation already matches it.
- **Material 3 Expressive (2025)** [recall; check [m3.material.io motion](https://m3.material.io/styles/motion/overview/specs)]:
spring tokens come in two families, **spatial** (position, size, rotation; may overshoot) and **effects** (colour,
opacity; never overshoot), each fast/default/slow. Direct support for Kit's "bounce 0 default" and avoids opacity > 1 or negative-alpha glitches.
- **Perception evidence is thin:** I found no controlled study that springs beat easing curves; the case is
physical continuity (velocity preservation, interruptibility) and animation-principles heritage. Chevalier et al.,
"Animations 25 Years Later" (AVI 2016) [recall] is the review. So treat "springs feel better" as design rationale, and let Kit's
blind A/B chooser (Bradley–Terry) settle specific values.
- **Rune use:** add a per-track `class: Spatial | Effect`; Effect tracks clamp to [min,max] of start/target and use the
critically damped solution even when asked for bounce; settle rule = analytic time at which `|x−target|<ε_px and |v|<ε_v`
(ε_px = 1/64 px for geometry per Kit's snapping rule, 1/256 for opacity), then snap exactly and stop the clock (zero-cost-at-rest).
Accept additive-animation behaviour (UIKit/CA retarget semantics) only if it matches exact segment retargeting; differential-test
the two on random retarget sequences.
- **Verdict:** adopt now.
### 6. Interruptibility as a testable property — **adopt now**
- Retargeting `(x, v)` is exact for analytic segments. Test generator: random event scripts (retarget at random times,
random spring class), asserting (i) `x` continuous, (ii) `v` continuous, (iii) no extra pop at settle, (iv) `x` bounded by
physical envelope. This is the motion linter's "reversal / velocity snap / stop-dead" family, but checked on *every frame
of every fuzzed script* rather than on recorded clips.
- **Layered interruption (Apple "pause then redirect"):** a gesture that grabs a running animation must read the *presented*
value and velocity (not model state), pause the track, drive 1:1, then restart from the finger's velocity. Rune's presented-tree design does this by construction.
- **Verdict:** adopt now (cheap, rides on §5).
### 7. Keeping text crisp while it moves — **adopt policy now, spike the harness**
**Facts:** macOS dropped LCD subpixel text AA in Mojave (10.14, 2018), so Apple text is grayscale and safe to resample [recall].
Core Animation text inside a layer is rasterised to a texture, so fractional translation is *bilinear resampling*
(stable but soft); Chrome snaps composited-layer raster translation to integers where it can, otherwise text blurs [recall].
GPUI/Zed rasterise glyphs into an atlas at a few quantised horizontal subpixel phases (4 in x; verify the y count in
`crates/gpui/src/platform.rs`) [recall]; Rune lifts that code ([01](01-gpui-zed-warp.md)).
**Policy proposal** (the trick is making it *state-driven by the analytic track*):
1. **Y snaps, X doesn't:** snap baselines to whole device pixels whenever the text is not translating vertically; keep x at ¼-px phases (8 on non-retina). Stem thickness is then constant, only horizontal phase varies.
2. **Moving fast (> ~0.5–1 device px/frame):** allow exact fractional positions (grayscale AA, no hinting). Eye tracking blurs the stems anyway, and the atlas phase quantisation is invisible.
3. **Settling (spring tail):** the tail crawls through sub-pixel phases for a long time, which is the visible "shimmer/crawl". Because Rune knows the analytic time `t_end` when `|x−target|<ε`, **end the track there** (ε = ¼ px for text; Kit's 1/64 px rule applies to shape edges) and snap. A ¼-px final pop is invisible, a 300 ms crawl is not. Also try quantising the *phase* of text only after speed < threshold.
4. **Never mix:** text and its container share one track so there's no relative sub-pixel drift between a label and its pill (Kit's rule on snapping both edges).
5. **Hypothesis to test:** with linear coverage, no gamma/contrast fiddling and no hinting, total ink coverage per glyph is phase-invariant
(box filter conserves area), so brightness shimmer comes from nonlinear text contrast/gamma and atlas quantisation, not from AA itself. A harness renders
"lHEx" at 64 phases per size/weight and reports variance of per-glyph ink and per-stem width; CI-gate it. Agents can do this in seconds on the CPU reference renderer.
- **Vernier caution:** even at 460 ppi, motion *hyperacuity* (≈ 5–10 arcsec) makes 1-px stepping visible at slow speeds, so "round to device pixel while moving" is not safe; hence fractional-x while moving, snap at rest.
- **Verdict:** adopt the policy now (it's configuration of existing pieces); spike the phase-sweep harness.
### 8. Scroll physics — **adopt now, analytic**
- **iOS:** `UIScrollView.DecelerationRate.normal = 0.998` per ms; closed form `x(t) = x0 + v0·(r^t − 1)/ln r`, stop time where `|v|<ε`; rubber band `c = 0.55` ([WWDC18 803](https://developer.apple.com/videos/play/wwdc2018/803/)) [recall]. Android: `OverScroller` spline fling (friction ≈ 0.015, inflexion 0.35) and Compose `splineBasedDecay` [recall]. Both are analytic in *time*, so fling is frame-rate independent and exactly retargetable: perfect for tracks.
- **Snap/targeting trick (Apple):** project the landing point with the decay, choose the snap target from the *projection*, then run a spring from the current `(x, v)` to that target; the user perceives "it knew where I was going".
- **macOS trackpad:** momentum phases arrive from the OS as events ([PLAN §4.9](../PLAN.md)); don't re-simulate. Resample them with the §3 rules, and
keep your own decay only for programmatic scroll and for non-Apple platforms.
- **Verdict:** adopt now; implement as another track kind `Decay{v0, rate}` with the same retarget/present API.
### 9. Motion blur for UI at high refresh — **skip by default; spike for flings**
- **Physics:** on sample-and-hold displays, perceived blur ≈ tracking speed × persistence; 1 ms ⇒ 1 px per 1000 px/s ([Blur Busters](https://blurbusters.com/blur-busters-law-amazing-journey-to-future-1000hz-displays-with-blurfree-sample-and-hold/) [recall]). 120 Hz halves hold blur vs 60 Hz, and per-frame displacement halves too, so stroboscopic/"phantom array" stepping disappears at moderate speeds.
- **Do UIs need synthetic blur?** Apple's UI doesn't use it for ordinary motion [recall]. It helps when per-frame displacement exceeds roughly 4–8 px *(est.)*, e.g. a hard fling of a text list; and Kit's rules already ban blur on persistent items (3–4 px defocus blur is only for in-place entry/exit). A directional shutter blur is a different thing from defocus blur, but Kit should decide whether it conflicts.
- **Rune advantage:** velocity is exact, so blur length `= v · shutter` (180° ≈ half a frame) costs nothing to compute. Implement as N instanced taps of a layer/sprite along `x(t_present ± shutter/2)` (analytic, no velocity buffer, no reprojection), applied only when `|v|·period > threshold`; it is the same shape as FLIP interpolation but in time.
- **Cost/risk:** N× fill for the layer; text readability; fights Kit's crispness rule. **Verdict:** skip at rest and normal speed, spike as a fling-only effect (opt-in token), test with a blind A/B.
### 10. Layout animation: FLIP, Motion projection, shared elements — **adopt rect-space FLIP; spike text-reflow FLIP**
- **Prior art:** FLIP (Paul Lewis, 2015: First-Last-Invert-Play) [recall]; Motion/Framer Motion layout projection (Matt Perry): a projection tree measures old/new boxes, animates a transform delta, and **scale-corrects** children, border-radius and box-shadow so scaling doesn't distort them ([Motion layout docs](https://motion.dev/docs/react-layout-animations); internals in Perry's "Inside Framer Motion's layout animations") [recall]; SwiftUI `matchedGeometryEffect`; Compose `SharedTransitionLayout` (1.7, 2024); CSS View Transitions (browser snapshots old/new and morphs the pair) [recall].
- **Why Rune differs:** FLIP and projection exist because DOM layout is expensive and transforms are the only cheap animatable. Rune lays out once to the final geometry and animates each node's *edges* (PLAN §4.9), and draws at the presented size, so there is nothing to scale-correct. Keep that. Two extras worth taking from Motion:
1. **Read the presented rect as "first"**, not the last target, so interrupting a layout animation resumes from where it is (Motion calls this latest-snapshot; matches Kit's retarget rule).
2. **Single progress for shared-element travel** (Kit rule 12): interpolate source→dest rects from one value per element; never separately-sprung camera plus element.
- **Spike: word/glyph-level FLIP for text reflow.** When a container resizes and a paragraph rewraps, SwiftUI/CSS snap lines. Because text content is stable, each cluster has a perfect identity (its character index). Parley gives us old and new cluster rects, so each word's track runs old→new in rect space, and glyphs outside the visible clip fade via the soft mask. Impractical by hand (identity bookkeeping everywhere); trivial with a generated per-run track table. No mainstream precedent I know of, so it is a feel differentiator. Risks: words crossing each other mid-flight (monotonic-path rule: lines reflow in reading order so usually fine), cost on long text (cap by visible lines/word count), ligatures/shaping across the move (move *runs*, not glyphs).
- **Verdict:** rect-space FLIP adopt (already planned); text-reflow FLIP spike.
### 11. Dirty/idle correctness and display pacing details — **adopt now**
- ProMotion/VRR: request the display's max rate during motion and drop to idle with zero wakeups once all tracks settle (PLAN §6b). `CAMetalDisplayLink` (iOS 17 / macOS 14) provides the target present timestamp and a latency preference [recall]. Pace with the OS, never sleep-based loops: Kit's own HUD lessons (no per-frame window resizes, `TimelineView` idle pause) apply.
- **Verdict:** adopt now (cheap, already in the plan).
### 12. Auto-tuning feel from comparisons — **later**
Kit's chooser (blind A/B with Bradley–Terry stopping rule) generalises: let agents sweep 3–5 values of duration/bounce for one interaction and ask Kit for ← / → picks, update the preset JSON. That puts *Kit's perception* in the loop at 10 comparisons per parameter, replacing guessing about spring-vs-easing. Cost: UI in `mk tune`. Verdict: later, after presets exist.
---
## Steal
- Android `InputConsumer` resampling constants (5 / 2 / 20 / 8 ms) and the `VelocityTracker` impulse model with 100 ms horizon and 40 ms stop rule.
- Apple's hitch-time-ratio thresholds (5 / 10 ms/s) and the commit-vs-render hitch split.
- Perfetto FrameTimeline's jank taxonomy (deadline missed, buffer stuffing, prediction error).
- Chrome's "consistent input-to-frame delivery" framing for scroll jank.
- M3 Expressive's spatial vs effects spring classes.
- Motion's "measure presented rect as First" for interrupted layout animation.
- WWDC18's project-then-spring pattern for snapping and flings.
## Avoid
- Sampling animation by wall-clock "now" or by frame count/accumulated dt (error accumulates and hides hitches).
- Rescaling children to fake size animation (distorts text, radii, shadows).
- Rounding text to whole device pixels while moving slowly (crawl) or leaving it fractional forever after (shimmer, blur).
- Prediction on scroll content by default (overshoot at direction reversals, feels "swimmy").
- Quoting the 1 ms / 10 ms latency numbers without checking the primary PDF (unread here).
- Synthetic motion blur on persistent items (violates Kit rule 11/persistent-items).
- Treating average fps or "no dropped frames" as the smoothness gate.
## Recommendation for Rune
1. Build the present-time sampling and trace fields first (§1, §2); everything else is measured against them.
2. Put input on the render thread with late latching and Android-style resampling (§3); add the impulse + LSQ2 estimators and the gesture-corpus harness (§4).
3. Add track classes (Spatial/Effect/Decay), analytic settle times, and fuzzed interruption tests (§5, §6, §8).
4. Encode the text policy as defaults plus the phase-sweep harness (§7).
5. Spikes, in order: text-reflow FLIP (§10), fling-only blur (§9), capped prediction for drags (§3d), A/B chooser in `mk tune` (§12).
**Rejected:** a CA-style additive-animation model (equivalent to exact retarget but harder to reason about and lint);
average-fps gates; Motion-style transform/scale-correction projection (solves a DOM problem Rune lacks); always-on
motion blur (conflicts with Kit's rules, little benefit at 120 Hz); relying on OS compositor snapping for text.
## Open questions
- Exact ms numbers in Ng/Jota (PDF unreadable via the fetch tool; run `pdftotext` locally or read it).
- How much display latency does Metal/wgpu add on macOS ProMotion with `maximumDrawableCount = 2` vs 3, and does `presentAfterMinimumDuration`/`CAMetalDisplayLink` remove it? Needs a reserved-hardware spike (not a developer's desk display).
- GPUI glyph atlas subpixel phase counts in x and y (read `platform.rs` before reusing).
- Whether iOS exposes enough touch-sample timestamps to a Rust render thread outside UIKit's main-thread delivery (coalesced touches arrive via the main run loop); see [11](11-platform-shells.md).
- Apple hitch thresholds and the Material 3 Expressive spring tokens were recalled, not re-read; confirm before they become policy.
- Does Kit want a directional (shutter) blur at all, given rule 11 and the "persistent items never blur" rule?
@@ -0,0 +1,308 @@
# 16. Agent-native and generative UI: what Rune should steal
Scope: LLMs generating UI at runtime, how agents perceive and operate UIs, token-efficient UI representations, LLM
codegen failure modes for UI frameworks, self-verifying loops, design-system-constrained generation. Today is 2026-10-21.
Evidence quality is marked per item: **[read]** = I read the primary source this session; **[recall]** = from memory of the
paper/post, not re-verified now, treat numbers as approximate.
## Summary
- Every serious generative-UI system converged on the same shape: **a closed catalog of components, a flat
id-referenced element list (adjacency list), a separate data model, and a streamed patch/message protocol.** Google's A2UI,
Vercel's json-render, and Airbnb-style server-driven UI all look like this. Rune's command channel (tree diff + targets +
text runs) is already the same shape, one level lower. Expose it, don't build a second system.
- Two safety models exist: **declarative data against a trusted catalog** (A2UI, json-render: no code runs) and **sandboxed
code** (MCP Apps / OpenAI Apps SDK: HTML in a locked iframe). For a native-feel renderer, declarative is the only option that
gets real springs, native text and a11y. Code runs only in a separate, capability-limited process (WASM), later.
- Models are good at this now but not at first-try correctness of *novel framework APIs*. Failure evidence points at
spatial/structural errors (missing elements, wrong size/position) and at strict type/trait semantics in Rust. Both are
answered by the same fix: a small closed vocabulary, a schema the decoder is constrained to, and a validator that returns
fixes.
- Agents operate UIs best from a **semantic tree plus screenshots**, with element ids in both (set-of-marks style). Rune owns the
tree, so it can emit a compact, stable-id, diffable text form that no web or native framework can match.
- The biggest wedge is not "LLM makes the UI at runtime" but **"the agent's design-time loop is a first-class product":**
scene → render → critique → patch, with exact lint results, so first-try correctness comes from the loop, not the prompt.
## Findings (ranked roughly by value to Rune)
### 1. Catalog + flat element list + data model + streaming messages (A2UI) → **adopt now (as Rune's own "Surface" protocol, A2UI-compatible)**
- Source: [A2UI v0.9.1 spec](https://a2ui.org/specification/v0.9.1-a2ui/), [v1.0 candidate](https://github.com/a2ui-project/a2ui/blob/main/specification/v1_0/docs/a2ui_protocol.md) (Jun 2026), [Google launch post](https://developers.googleblog.com/introducing-a2ui-an-open-project-for-agent-driven-interfaces/) (Dec 2025). **[read]**
- What it does: four messages (`createSurface`, `updateComponents`, `updateDataModel`, `deleteSurface`). Components are a flat
list with `id`s and child id references, so the model can emit them in any order and the client renders progressively
(placeholders for missing children). Properties bind to a JSON-Pointer data model or to catalog-declared functions
(`formatCurrency`, `pluralize`, `required`…). Catalogs are JSON Schema documents with an optional `instructions` markdown
field that is fed to the model. User actions go back as `action` messages; `sendDataModel` returns the surface state with each.
- Rune use: define Rune's runtime-UI surface as A2UI-shaped (flat elements, ids, data model, patch messages) with the **Rune
design system as the catalog** (Stack, Text, Button, List, Sheet, Glass…). Map `updateComponents` onto the existing keyed
`El` tree diff, so identity-preserving enter/exit and springs come free: a model that re-sends a component with the same id and
changed props gets a retargeted spring, not a pop. A2UI has no motion vocabulary; Rune's catalog adds `transition` and
`layout` tokens (named, from the theme), never raw durations.
- Cost/risk: low. It is JSON, Rune already needs a serializable channel. Risk is spec churn (v0.8→0.9→1.0 renamed
everything in 6 months) so keep an adapter layer, don't make A2UI the internal format.
- Verdict: **adopt now.** Design the internal wire format first (see §Recommendations), ship an A2UI adapter second.
### 2. Constrain decoding to the catalog schema (XGrammar and structured outputs) → **adopt now**
- Source: [XGrammar, MLSys'25](https://arxiv.org/abs/2411.15100): up to 100x faster CFG-constrained decoding, near-zero
overhead end-to-end in serving. **[read]** Provider-side structured outputs (OpenAI/Anthropic/Gemini JSON-schema modes) **[recall]**.
- What it does: the model cannot emit an unknown component, a misspelled prop, or an enum value outside the set. Syntax errors
go to zero by construction.
- Rune use: generate the JSON Schema for the catalog **from the Rust component definitions** (one source of truth, `rune
schema` command), publish it for provider structured-output modes, and run the same schema as the runtime validator. Use
`oneOf` discriminated by `component`, props `additionalProperties: false`, enums for every theme token (spacing, color
role, spring name). Keep the schema small: structured-output modes cap schema size/depth and large `oneOf` unions slow
compile (estimate: keep under ~50 component variants, depth under ~5).
- Cost/risk: low. Constrained decoding fixes syntax and vocabulary, not layout quality or semantics; still needs the lint loop (§6).
- Verdict: **adopt now.**
### 3. Semantic tree as the agent's eyes, with ids shared with screenshots (set-of-marks) → **adopt now**
- Sources: Set-of-Mark prompting (Yang et al., 2023) **[recall]**; UGround ([arXiv 2410.05243](https://arxiv.org/html/2410.05243v3)): vision-only grounding beats prior models by up to 20% absolute, i.e. pure-pixel agents are viable **[read snippet]**; [ScreenSpot-Pro](https://www.alphaxiv.org/abs/2504.07981) shows high-res professional UIs are where pixel grounding is still weak **[read snippet]**; a 2026 process-centric benchmark evaluates Screenshot vs Screenshot+a11y-tree vs SoM inputs ([ACL Findings 2026](https://aclanthology.org/2026.findings-acl.750.pdf)). OSWorld-Verified has passed the 72.36% human baseline; aggregator sites list leaders at ~85% ([benchlm](https://benchlm.ai/benchmarks/osworld-verified), unverified numbers, treat as indicative only).
- What it does: the two channels are redundant. Trees give exact, cheap, scriptable targets but miss custom-drawn UI (GPU UIs
such as GPUI/Flutter canvases have empty trees, which is the failure that makes agents fall back to pixels). Screenshots
see everything but ground imprecisely and cost many tokens per frame. Marks (numbered boxes drawn on the screenshot, same
numbers in the text tree) combine them.
- Rune use: because the a11y tree *is* the render tree (tenet 3), Rune can guarantee **100% of visible interactive nodes are in
the tree with rect, role, label, state, source `file:line`**, and render a **marked screenshot** (`mk snap --marks`) where each
mark id = node id. Agents say `tap n17`, not coordinates. Inject input through the inspector, not synthetic OS events, so a
tap on a node is exact and timestamped.
- Cost/risk: low; mark overlay is a debug-lane draw pass. The real risk is label quality: models can only use what authors
write, so make `label` required for every interactive control (compile or lint error with fix).
- Verdict: **adopt now.**
### 4. Token-efficient tree text format (compact, stable ids, diffs) → **adopt now, measure**
- Sources: browser-agent practice (Playwright MCP snapshots, browser-use, Stagehand) all converged on "pruned a11y tree as
indented text with ref ids", and [the GUI-agents paper list](https://github.com/OSU-NLP-Group/GUI-Agents-Paper-List)
tracks work on linearizing a11y trees into compact forms because raw trees are costly and noisy **[read snippet]**.
- What it does: raw DOM/AX dumps run to tens of thousands of tokens per page; pruned role+name+ref outlines are roughly 5-20x
smaller (estimate from experience, I did not benchmark here).
- Rune use, a concrete format:
```
window "Inbox" 390x844
list key=threads (scroll y=0/2310)
row n17 key=thread:42 "Ana: lunch?" [selected] 358x64 @16,120 <ThreadRow src=inbox.rs:88>
text n18 "Ana" ; text n19 "lunch?" ; button n20 "Archive"
```
Rules: only semantic and visible nodes; collapse pure layout wrappers; ids derived from keys (stable across frames, so
`tap n17` survives re-render); layout rects optional (`--rects`); **diff mode** returns only changed nodes since frame id
N (the channel already carries tree diffs; surface the same diff as text). Add a token counter to every inspector reply so
size is a tracked metric.
- Cost/risk: trivial to build; the work is deciding what is "semantic" and keeping it stable. Add a golden test per scene on
the text tree: it doubles as a cheap, deterministic UI regression test that is far less flaky than pixels.
- Verdict: **adopt now.**
### 5. Self-verifying loop: render, lint, critique, patch → **adopt now (this is the product)**
- Sources: Google's Generative UI paper uses **post-processors for error reporting and page analysis** and notes JS/CSS/HTML
errors still occur occasionally ([arXiv 2604.09577](https://arxiv.org/abs/2604.09577)), plus prompt ablation: full
prompt ELO 1553 vs minimal 1496 vs no-"philosophy" 1451, so instructions matter more than examples-free brevity **[read]**.
DesignBench ([arXiv 2506.06251](https://arxiv.org/abs/2506.06251)) separates generation, edit and repair tasks and finds
framework-specific limitations and that generation tasks fail mostly on spatial/structural errors ("wrong element size",
"element missing") **[read abstract+snippet]**. Design2Code (484 real pages, [Si et al. 2024](https://salt-nlp.github.io/Design2Code/)): omission of elements and
layout distortion are the dominant visual failures; text and color are easy **[recall]**.
- What it does: failures are *spatial and structural*, which is exactly what exact layout lint can catch without a vision
model. A visual critique by a model is the second pass, not the first.
- Rune use: the PLAN §6 tools already are this. Make it one command an agent runs after every edit: `rune check <scene>` =
compile + render scene + the internal layout linter (overflow, overlap, tap target < 44, off-grid, contrast) + the internal motion linter on a scripted
interaction + tree diff vs golden, and print **findings as fixes keyed to source locations** ("`Row` at inbox.rs:88 is 312
pt wide in a 290 pt parent; set `.fill()` or wrap in `Scroll`"). Return a marked screenshot only when lint passes or the
agent asks. One structured result, small text, hot-reload speed (<1 s). This is what turns first-try into
second-try-within-seconds.
- Cost/risk: moderate engineering, but all pieces are already in the plan. Risk: findings must be precise; a noisy linter
trains agents to ignore it.
- Verdict: **adopt now.**
### 6. Design-system-constrained generation (tokens, not values) → **adopt now**
- Sources: A2UI catalog `instructions` + `theme` ([spec](https://a2ui.org/specification/v0.9.1-a2ui/)); json-render's
`defineCatalog` with Zod props and `catalog.prompt()` that auto-generates the system prompt
([repo](https://github.com/vercel-labs/json-render), 18.8k stars, Apache-2.0; has an `@json-render/mcp` package and Ink/RN/Remotion/PDF renderers) **[read]**.
Google's paper adds "consistent styling" as an option ([arXiv 2604.09577 §2.1](https://arxiv.org/html/2604.09577)) **[read]**.
- What it does: the model picks `spacing: "md"`, `color: "text.secondary"`, `motion: "snappy"` instead of `13px`, `#8E8E93`,
`0.35s ease`. No off-palette color, off-grid spacing or unspecified curve is expressible. This also makes output
automatically consistent with the app's theme (tenet 5).
- Rune use: the catalog's prop types are **enums of theme tokens only** plus a few numeric ranges with units. No raw hex, no
raw durations, no free-form style objects in the generative lane (they stay available in the trusted app lane). Generate the
prompt from the catalog (`rune prompt` emits catalog + rules + 3 scenes as few-shot) so docs and validator can't drift.
- Cost/risk: the catalog needs to be expressive enough that models don't hit walls; plan an escape hatch component (`Canvas`
with a restricted vector DSL) rather than loosening the main catalog.
- Verdict: **adopt now.**
### 7. Generative UI quality and latency envelope (Google) → **calibrate expectations; later**
- Source: [Google Research blog](https://research.google/blog/generative-ui-a-rich-custom-visual-interactive-user-experience-for-any-prompt/) (Nov 2025), [paper](https://arxiv.org/abs/2604.09577). **[read]**
- Numbers: LMArena prompts, human pairwise preference: Generative UI beats markdown 82.8%, beats top search result 90%, loses to
human-expert sites (35-43% win depending on revision; paper versions disagree: v1 says 35.3%, the PDF says 43%). ELO ~1736 vs
expert 1800 vs markdown 1438. Capability is *emergent*: newest models show far fewer generation errors. **Generation takes
"a minute or two"; streaming halves the time-to-interaction.** Output is a single full HTML page rendered as-is, i.e. maximal
freedom, no catalog.
- Rune use: two lessons. (a) Latency is the problem, so a protocol that renders progressively on partial output (A2UI's
flat list + placeholder rule) is mandatory, and the 1-2 minute whole-page approach is not something to copy. (b) Quality
is model-driven and improving, so a catalog design that is slightly too restrictive today is a bet that models will not need
raw HTML. Plan the catalog to grow.
- Verdict: **later** for Rune-as-chat-surface; the research mostly validates #1, #2, #6.
### 8. Sandboxed-code lane: MCP Apps and the OpenAI Apps SDK → **skip for rendering; adopt as the delivery pipe**
- Sources: [SEP-1865 MCP Apps, Stable 2026-01-26](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx); [MCP Apps overview](https://modelcontextprotocol.io/extensions/apps/overview); [Microsoft Cowork adoption](https://learn.microsoft.com/en-us/microsoft-365/copilot/cowork/mcp-apps-support). **[read]** OpenAI Apps SDK (Oct 2025) is the same pattern (tool declares a UI template, sandboxed iframe, host bridge) **[recall]**.
- What it is: servers declare `ui://` HTML resources (`text/html;profile=mcp-app`) on tools via `_meta.ui.resourceUri`; hosts
render them in a sandboxed cross-origin iframe, CSP built from declared domains (default: no network), JSON-RPC over
`postMessage`, template/data separation, host-mediated tool calls with user consent. Adopted by Claude, ChatGPT, VS Code, Cowork.
- Why it matters for Rune: it is the **de facto distribution channel** for agent UI: any Rune-hosting product (OpenCode
Desktop) that wants to show third-party agent UI will be asked for it. But HTML-in-iframe is the opposite of native feel:
no shared springs, text, a11y tree or glass.
- Rune use: (a) **steal the security model verbatim for any untrusted code lane:** predeclared templates, no ambient network,
declared capabilities, all host calls as auditable messages with consent. (b) Offer a **Rune-native MCP Apps profile**: a new
`mimeType` for a Rune surface (A2UI-shaped JSON) behind the same `ui://` + `_meta.ui` linkage. The SEP reserves other content
types for future extensions. Tools stay unchanged; hosts that support the Rune profile render natively, others fall back to text.
- Cost/risk: spec is Stable so safe to target; a native profile needs host adoption, so spike with OpenCode Desktop first.
- Verdict: **spike** (native profile), **skip** (iframe rendering inside Rune).
### 9. Server-driven UI in production (Airbnb Ghost Platform, Lyft, Shopify) → **steal the lessons**
- Sources: Airbnb "Ghost Platform" series (2021), Lyft Bikes and Scooters SDUI (2022-23), Shopify Mobile SDUI/"Remote UI" **[all recall, older than 2023, not re-fetched]**.
- Lessons that recur: (1) a **section/component registry versioned with the client**, because old clients must ignore or degrade
unknown components (negotiate capabilities up front, like A2UI's catalogId + capabilities exchange); (2) **layout and
data separated** so data refreshes don't resend structure; (3) **actions are a closed set** (navigate, setState, call
tool), never scripts; (4) the failure mode is the **escape-hatch creep** where "just one more prop" turns the schema
into a bad programming language (json-render's `$cond/$state/$computed` already shows the slope); (5) debuggability needs
a spec-inspector (json-render ships devtools: spec tree, state editor, action log, stream log).
- Rune use: version the catalog with semver per component, advertise `catalogId`+version on connect, define degrade rules
(`unknown → Placeholder with label`). Keep expressions to a deliberately tiny set: bind, cond, template, a registered
function list; no arithmetic beyond the catalog's `format*` functions. Ship a `rune surface` inspector that shows incoming
messages next to the resulting tree.
- Verdict: **adopt now** (as design constraints).
### 10. Rust codegen failure modes → design the API against them → **adopt now**
- Sources: [Rust-SWE-bench, ICSE 2026](https://arxiv.org/abs/2602.22764): 500 tasks, 34 repos; best ReAct agents resolve up to 21.2%; the two named
bottlenecks are **repo-wide structure comprehension and compliance with Rust's strict type and trait semantics**; their RustForger
(issue reproduction + metaprogramming tracing) reaches 28.6% **[read]**. [Microsoft Research on LLMs fixing Rust compile errors](https://www.microsoft.com/en-us/research/wp-content/uploads/2024/08/paper.pdf) (2024) and
[Fortytwo's Strand-Rust-Coder report](https://huggingface.co/blog/Fortytwo-Network/strand-rust-coder-tech-report) both report borrow-checker violations as
the dominant base-model failure **[read snippets]**. Caveat: these are issue-resolution benchmarks on 2025-vintage models; no
published study I found measures *Rust UI framework* first-try compile rates. Treat any number about Rune specifically as
unmeasured until Rune runs its own eval (see §Recommendations: "Rune-Bench").
- What it implies: errors come from (a) lifetimes and borrows, (b) deep generics/trait bounds, (c) misremembered APIs
(training data predates Rune; GPUI/Iced/Xilem APIs shift and models hallucinate them).
- Rune use: view code should require **no lifetimes, no generic bounds, no borrows crossing closures** in the common path:
`Copy` ids and handles, owned values, closures take `&mut Model` passed in, no `impl Trait` returns that need naming, one
concrete `El` type (the PLAN's type-erased debug mode helps). Fewer distinct concepts than SwiftUI. Ship `llms.txt` plus
**an examples directory that compiles in CI** and prefer many small canonical examples over prose (models copy examples).
Make compiler errors actionable via custom `#[diagnostic::on_unimplemented]` and `compile_error!` messages with the fix.
- Verdict: **adopt now.**
### 11. Two lanes: trusted Rust app code vs generated surfaces → **adopt now (architecture)**
- Argument: a model can write Rust app code *at design time* (agent in the loop with a compiler) or emit a **surface** at
runtime (no compiler). The same Rune renderer must serve both. They differ in trust, latency and expressiveness:
| Lane | Who writes | Trust | Latency to pixels | Expressiveness |
|---|---|---|---|---|
| App code (Rust, hot reload) | coding agent + human | full | ~300 ms hot patch | everything |
| Surface (A2UI-shaped JSON over the channel) | model at runtime, or server | **untrusted**: catalog only, validated, capability-limited | first partial in one token chunk | catalog + data bindings + closed actions |
| Plugin (future, WASM) | third party | sandboxed, capabilities declared | compile-time | restricted |
- Rune use: the surface lane is just another *producer* feeding the same render-thread channel the app side feeds. Each
surface gets its own **sub-tree root with a resource budget** (node count, text bytes, image count, spring count, depth, layout
cost) enforced before commit; exceeding it truncates with a visible placeholder, never a frame drop (§6b "no dropped frames by budget" applied at runtime).
- Verdict: **adopt now** (shapes the channel protocol: tree producers are pluggable, ids are namespaced per producer).
### 12. Runtime safety for model-generated surfaces → **adopt now (checklist), spike (fuzzing)**
- Threats: prompt-injected content rendering deceptive UI (fake system dialog, fake "Allow" button), resource exhaustion
(10^6 nodes), exfiltration via image URLs or `openUrl`, action spoofing, layout-time bombs (deep nesting, huge text).
- Rune use (all enforceable because Rune owns the pixels):
- **Provenance chrome:** every surface lives inside a visually distinct container the model cannot style away (inset glass
border, optional "generated" badge); surfaces cannot draw outside their bounds (soft mask, the same mechanism as no-hard-clip) or over app chrome.
- **Closed action set** with host-side policy: `setState` on the surface's own model, `emit(action)` back to the producer,
`openUrl` only via allowlist and user gesture. Anything that touches the app or network goes through a **capability grant**
(same shape as MCP Apps `permissions`/consent).
- **Resource budget + deadline** per surface, enforced at validate time and each frame; image loads through a host proxy
with domain allowlist (MCP Apps' `connectDomains/resourceDomains` model).
- **Validate then commit atomically:** patches that fail schema or budget are rejected whole and reported back to the model as
a structured error (the model fixes it next turn). No half-applied surfaces.
- **Input from surfaces is data, never code:** no expression language beyond the tiny set in §9.
- Fuzz the validator + layout with generated surfaces (property tests; the PLAN's scene fuzzing applies).
- Verdict: adopt the checklist; **spike** a validator fuzzer early.
### 13. Native feel for model output: motion and layout come from the catalog, not the model → **adopt now**
- Insight: models can't be trusted to tune springs, and shouldn't. The catalog gives each component built-in
enter/exit/layout behavior from theme tokens (bounce 0 default, duration-based), identity from `id`, so streaming in a new
card, reordering a list, or the model rewriting the whole surface all animate correctly with no motion authored by the model.
Progressive rendering becomes a feature: A2UI-style streamed `updateComponents` inserts nodes that **fade/scale in with presence
tracks while text streams**, and layout animates as siblings arrive. The internal motion linter's rules (pop, jump, reflow) run on
surfaces too, so you can **prove** a streaming surface never jumps.
- Specific risk: streaming makes *layout churn* (content height grows token by token). Policy: reserve space (skeleton
placeholders by component default size), apply layout edge tracks with the standard spring, never animate every token; text
grows with a soft trailing mask rather than reflowing the box each token (precedent: the private iOS client's streaming text).
- Verdict: **adopt now**, as a test scene: "stream a 40-component surface at 30 tokens/s, the internal motion linter must be clean."
### 14. Rune-Bench: our own eval of first-try correctness → **adopt now (small)**
- Why: no public benchmark measures LLM first-try correctness for a new Rust UI framework or catalog. Closest: DesignBench
(React/Vue/Angular generation/edit/repair), Design2Code, WebGen-Bench (end-to-end web apps, pass rate by UI tests; [recall]), Sketch2Code.
Their taxonomy (generation / edit / repair; structural vs visual errors) is what to copy.
- Rune use: 30-50 tasks as scenes (spec + fixture + reference tree/golden): *generate from prompt*, *edit* ("make the row
tappable"), *repair* (given lint failure). Metrics: compiles first try, lint-clean first try, tree-match vs reference, turns to green, tokens spent. Run per model on
every API change. **This turns "API agents can't misuse" into a number**, bisectable like the perf counts.
- Verdict: **adopt now** (week 1 of M1-ish); cheap and pays back on every API decision.
## Steal / avoid
**Steal**
- A2UI's flat element list + ids, separate data model, four-message envelope, catalogId negotiation, catalog `instructions`.
- json-render's: catalog → auto-generated prompt; SpecStream (streamed JSON patches compiled into a partial spec); devtools panel (spec tree, state, action log, stream log).
- MCP Apps's security model: predeclared templates, restrictive default, declared capabilities, auditable messages, user consent for UI-initiated calls; `ui://` linkage as a delivery vehicle.
- Browser-agent snapshot practice: indented role/name/ref text, ref ids stable within a snapshot.
- Set-of-marks overlay for pixel+tree grounding.
- Google's "post-processors for common issues": auto-repair passes (e.g. clamp, wrap in Scroll, add missing key) before showing an error to the model.
- DesignBench's generate/edit/repair task split for evals.
**Avoid**
- Whole-page generation as raw HTML/code at runtime (1-2 minute latency, no safety, no catalog, JS errors) as the default.
- A general expression language in the schema (the slope from `$cond` to a bad scripting language).
- Raw style values in the generative lane (hex, px, durations).
- Coordinate-based agent actions as the primary interface; always prefer node ids.
- Making A2UI (still 0.9 → 1.0 candidate, renamed once already) the internal format.
- Screenshot-only verification as the first gate: slow, token-heavy, imprecise; use exact lint first.
- Relying on prompt text to teach the API; models' training data will not contain Rune (unlike SwiftUI/React). Compile-checked examples beat docs.
## Recommendation for Rune
**View API (for the Rust app lane), so models are right the first time**
1. One concrete tree type (`El`), builders only, no macro DSL, no lifetimes or generic bounds visible in signatures. Props via a
small fixed set of chainable modifiers whose names mirror SwiftUI where semantics match (models know SwiftUI deeply; reuse the
vocabulary: `Stack`/`HStack`/`VStack`, `.padding`, `.frame`, `.animation`), because **vocabulary alignment with training data is the cheapest first-try-correctness lever**.
2. Tokens, never numbers, in the public API for color, spacing, type, radius, motion (raw numbers only through an explicit `raw_*` escape that lint flags).
3. Explicit `.key()` required in dynamic lists; `label` required for interactive nodes; the compile error text says exactly what to write.
4. Every component registers a **catalog entry** (name, props schema from the Rust type, doc string, 2 scenes). The catalog JSON
Schema, the `llms.txt` section, the inspector's queryable names, and the generative lane's validator are generated from that single registry.
5. Examples dir compiled and run in CI; `rune check` as the single feedback command (§5 above).
**Wire protocol (command channel, used by app side, hot reload, tests, agents, generated surfaces)**
- Messages (a superset of A2UI's four): `surface.create{id, catalog, version, budget}`, `surface.patch{id, ops}` (ops: upsert
element by id, remove, reorder children, set data path), `surface.delete`, plus lower-level render commands (targets, springs, text runs) that only trusted producers may send.
- Elements are a flat table `{id, kind, props, children[]}`; ids namespaced `producer/surface/local`; props reference data
paths or theme tokens; a validate step produces a typed `Rejection{path, rule, fix}` that goes back to the producer (and into the model's context).
- Events back: `action{surface, element, name, payload}`, `settled{frame}`, `data{surface, model}` (A2UI `sendDataModel`).
- Same stream recorded for replay (already planned), same stream carried over the inspector socket, same stream a `--agent` text view renders as the compact tree. One protocol, four consumers.
- Negotiate on connect: catalog id + semver, budget limits, supported motion tokens, max protocol version.
**Rendering model-generated UI at runtime with native feel**
- Surface lane = declarative catalog only, validated + budgeted + provenance-marked (§12); trusted components provide springs,
text, a11y, glass. A2UI/MCP Apps adapters sit at the edge: A2UI JSON → surface patches; a Rune MCP Apps profile for hosts that opt in.
- Untrusted code (later): WASM component with host-granted capabilities, emits surface patches, never touches the render
thread; MCP Apps' consent/CSP model as the template. Not before M-late.
**Rejected alternatives**
- *Embed a WebView for generated UI (MCP Apps iframe):* gives universal compatibility, loses everything Rune is for. Allow only as a clearly separate "web card" component if a host demands it.
- *Let the model write Rust at runtime and compile:* seconds-to-minutes compile, borrow-checker failure rates (Rust-SWE-bench: up to 21% issue resolution), no safe sandbox. Keep for design time only.
- *Adopt A2UI wholesale as the one format:* its component model has no motion, no layout animation, no a11y labels as required fields, and is mid-churn. Adapter, not foundation.
- *Screenshot-only agent operation:* strong models now handle it (OSWorld-Verified past the human baseline per aggregators), but it's costlier, noisier and misses state that the tree gives for free.
## Order of work (suggested)
1. Define component registry → JSON Schema + `llms.txt` + prompt generator (items 2, 6, 10).
2. Compact tree text + marks screenshot + stable ids in inspector (3, 4).
3. `rune check` single-command verify loop with fix-oriented findings (5).
4. Rune-Bench v0 with 30 scenes (14).
5. Surface lane: patch protocol, validator, budgets, provenance chrome, fuzzer; A2UI adapter (1, 11, 12).
6. Streaming-surface motion scene under the internal motion linter (13).
7. Spike: Rune MCP Apps profile in OpenCode Desktop (8). Later: WASM plugin lane.
## Open questions
- What is first-try compile + lint-clean rate for Rune's API per model today? Unknown until Rune-Bench exists; set the target
(suggest ≥80% generate, ≥90% edit within 2 turns) and track.
- How small can the catalog stay (estimate 30-50 components) before models hit walls, versus how big before constrained-decoding schema compile hurts per provider?
- Can the surface lane share the exact `El` diff path (zero extra work on the render thread), or does namespacing/budgeting need its own tree? Probably shared; prove with the counting allocator.
- Do hosts (OpenCode Desktop, Claude, ChatGPT) have any appetite for a native-surface MCP Apps profile? Needs a conversation with OpenCode before building.
- Text-tree vs marks: which gives better agent success per token on Rune scenes? Needs an A/B over Rune-Bench with two agent configs.
- Evidence gaps in this note: Set-of-Mark, Design2Code specifics, WebGen-Bench, Sketch2Code, Airbnb/Lyft/Shopify SDUI details, and the OpenAI Apps SDK are **[recall]**, not re-read; OSWorld-Verified leaderboard figures come from aggregator sites and could be wrong. Re-verify before quoting externally.
@@ -0,0 +1,298 @@
# 17. Performance architecture: cutting-edge tricks for Rune
Scope: UI-engine performance architecture, incremental computation, dirty tracking, render-thread handoff, GPU upload,
Rust compile speed, hot patching, PGO/BOLT. Written 2026-10-21 for tenet 7 (agents maintain the code, so fast-path +
reference-path and differential testing make "ugly but fast" safe).
**Provenance.** Marked **[fetched]** = I read the page this session. Marked **[memory]** = from my own knowledge, link
given but not re-read; verify before relying on numbers. Estimates are labelled.
## Summary
- Rune's biggest structural win is already in the plan: animation on the render thread with analytic springs. The
cleverest extension is to **evaluate springs on the GPU** from a track table, with draw instances referencing
property-tree node ids, so an animating frame costs ~one uniform write on the CPU (idea 1).
- Slate's invalidation measurement shows the cost model: a 10k-widget UI paying full price "to do nothing" took
34.29 ms/frame; with caching it took 0.35 ms [fetched]. Rune's "zero work at rest" needs per-node dirty classes, not
just a global "something changed" flag (idea 2).
- Cheapest big compile win on macOS, measured: `[profile.dev.package."*"] debug = false` cut a clean nushell debug
build 22-30%; `split-debuginfo = "packed"` adds ~16 s per edit [fetched]. Linking is not the bottleneck on macOS (idea 10).
- Cranelift is **not ready on macOS** (no unwinding on macOS, arm64-macOS ABI mismatches with LLVM as of the June 2025
report [fetched]); skip for Rune dev builds on Apple.
- Deterministic channel replay (PLAN §6) doubles as a perfect PGO training corpus (idea 12).
- Don't adopt Salsa/SwiftUI-AttributeGraph-style general dependency graphs; take only **early cutoff** (equal recompute
→ no propagation) and **constraint-based memoization** (comemo) at layout/text boundaries.
---
## Ideas
### 1. GPU-evaluated spring tracks + property trees (Chromium `cc` shape) — verdict: **spike (S-new, high value)**
- **Source.** Chromium compositor property trees, the transform/clip/effect/scroll trees separate from layers, so
compositor-thread animation only mutates a tree node
([docs](https://chromium.googlesource.com/chromium/src/+/main/docs/how_cc_works.md), [memory]; older but the design
still stands). Flutter/Impeller and Core Animation's render server do the same split. Analytic spring segments are
Psychopomp's model (PLAN §4.9).
- **What it achieves.** In Chromium, a transform animation never re-runs paint or layerization. Number: none I can cite.
- **How Rune uses it.** Scene build emits instances that carry `(transform_node, clip_node, effect_node)` u16/u32
indices instead of baked positions. Tracks live in a GPU buffer as SoA `{t0, x0, v0, target, omega, zeta}`; a vertex
shader (or a tiny compute pre-pass per node level) evaluates `x(t)` closed-form for the frame's target timestamp. The
CPU per-frame cost while springs run becomes: write one `time` uniform, encode the same command buffer (or reuse an
Indirect Command Buffer). Retargeting writes one 24-byte segment. Hit-testing/culling still needs CPU-side values:
keep the CPU evaluator as the **reference path** and differential-test it against GPU readback in scenes
(floating-point: use `f32` with identical formula; allow 1/64 px tolerance, which matches the plan's edge snapping).
- **Cost/risk.** Layout-edge animation changes node rects, so text/glyph positions that depend on them need the
property-tree indirection to cover size as well as translation (an affine can't express an edge-only resize of a
rounded rect with unscaled corners; those need per-instance `rect = lerp(edges)` evaluated in-shader). Hit-testing at
presented positions needs the CPU evaluator anyway (it's cheap: a few flops per animating node).
- **Verdict.** Spike on the first scene with 1,000 animating cards: compare CPU instance-buffer rewrite vs GPU evaluate.
Expected (estimate) win is CPU time per animating frame dropping from O(animating instances) to O(1).
### 2. Per-node dirty classes with a "volatile" escape hatch (Slate invalidation) — verdict: **adopt now**
- **Source.** Unreal Slate [Invalidation docs](https://dev.epicgames.com/documentation/unreal-engine/invalidation-in-slate-and-umg-for-unreal-engine?lang=en-US)
[fetched]: four classes (Volatile/Visibility → Paint → Layout → Child) in increasing cost, each implying the later
steps, dirty list processed once per frame; Volatile widgets bypass paint caching but keep layout caching. Independent
measurement ([ta-dah.tech, Aug 2026](https://www.ta-dah.tech/blog/retainer-box-vs-invalidation-box-what-10000-updating-widgets-taught-me-about-umg-performance/)
[fetched]): 10,000 widgets, one updating: **34.29 ms → 0.35 ms** (Retainer) / **0.39 ms** (Invalidation Box);
`SWidget::Paint` count 4,487 → 29. Gotcha they hit: a Retainer set to render on a fixed phase *re-rendered every
frame* and ran at 50.9 ms, worse than no cache. Retainer gives about no extra CPU win over invalidation, costs a
render target per retainer (Epic: "try Invalidation Boxes first").
- **How Rune uses it.** Dirty bits per node, SoA bitset: `PAINT`, `LAYOUT`, `CHILDREN`, plus `PRESENCE`/`VOLATILE`.
Tree diff sets the minimal class (colour change = PAINT only, no Taffy call; key add/remove = CHILDREN). Bits
propagate up as "subtree has dirty descendants" so traversals prune. Property tracks never set bits (they're
render-thread data). Cached subtree textures (retainers) only for provably static, expensive-to-draw subtrees
(blur, big vector art) with an exact invalidation rule; never on a phase timer.
- **Perf gate.** Count `nodes_visited_per_frame` and `nodes_painted` in the exact-counters harness; at rest both must
be 0 and the display link stopped.
- **Cost/risk.** Missed invalidation = stale pixels. Mitigation (tenet 7): reference path re-runs everything every
frame in test mode and diffs pixels against the incremental path ("paranoid mode", Slate itself ships a
`Slate.InvalidationDebugging` equivalent).
- **Verdict.** Adopt. It's the cheap 100× for scrolling lists and big static chrome.
### 3. Early cutoff and "durability" from Salsa/Adapton/Incremental; skip the general graph — verdict: **adopt the cutoff, skip the engine**
- **Sources.** [Salsa](https://salsa-rs.github.io/salsa/) (backdating: if a query recomputes to an equal value, its
dependents are not invalidated; durability levels skip re-validating stable inputs), [Adapton](https://docs.rs/adapton)
(demand-driven incremental, paper "Adapton: Composable, Demand-Driven Incremental Computation", PLDI 2014),
[Jane Street Incremental](https://github.com/janestreet/incremental) (cutoff functions on nodes; heap by height),
SwiftUI's AttributeGraph (not public; known via reverse engineering write-ups, [memory]). All [memory].
- **What it achieves.** Salsa's rust-analyzer reuses work across edits; no UI-frame numbers.
- **How Rune uses it.** Three specific uses, none a general graph:
1. After Taffy runs, compare each node's new rect to the old; only changed rects emit layout-edge commands to the
render thread (cutoff). Likewise text: new shaped-run hash equal → no re-upload.
2. View-function inputs: `cx.read(model)` records a version number; if every read version is unchanged and props
hash equal, skip re-running the view and reuse its `El` subtree (React Compiler does exactly this by
auto-memoizing per-component values, [docs](https://react.dev/learn/react-compiler), [memory]).
3. Durability: tag models as `static-ish` (theme, fonts, locale) vs `hot` (cursor, hover); a theme change is the only
thing that revalidates the world.
- **Why not the full engine.** PLAN §4.8 already rejected signals because state must survive hot patches; a graph keyed
by code identity breaks across patches. Version numbers on typed models don't.
- **Verdict.** Adopt cutoff + version-stamp memoization; skip Salsa/Adapton as dependencies.
### 4. Constraint-based memoization (comemo) for layout and text — verdict: **spike**
- **Source.** [comemo](https://github.com/typst/comemo) (Typst): memoize pure functions whose arguments are *tracked*
types; the cache entry records only which methods of the tracked argument were called and their results, so a changed
argument that doesn't change *those answers* still hits. [memory]
- **How Rune uses it.** Layout of a subtree depends on `(available space, style, children)`. Taffy already caches per
node with a small fixed set of slots keyed by available-space (known behaviour, [memory]); comemo-style tracking would
go further for text: shaping depends on `(text, font, size, features)` but wrapping depends only on *width bucket*;
record "line breaks stayed identical for any width in [w1, w2]" so container resizes during a spring don't re-wrap
(the plan's two-tier cache does a cruder version of this). Valuable for **layout animation** where width changes
continuously but the target layout is computed only at target (so it matters less); useful for resizable windows.
- **Cost/risk.** Tracked-call bookkeeping costs more than recomputing small nodes. Only worth it above a node-size or
text-length threshold.
- **Verdict.** Spike, only for paragraph wrap intervals. Cheap to try because Parley exposes break opportunities.
### 5. Lock-free handoff: SPSC byte ring for commands, triple buffer for "latest state", left-right for read-mostly trees — verdict: **adopt now**
- **Sources.** [triple_buffer](https://docs.rs/triple_buffer) (non-blocking, wait-free latest-value handoff where the
producer may overwrite; reader always sees a complete snapshot) [fetched via search page]; [left-right](https://github.com/jonhoo/left-right)
(Jon Gjengset: two copies of a structure, writers apply an op log to the idle copy, readers never block) [memory];
[rtrb](https://github.com/mgeier/rtrb)/ringbuf for SPSC rings [memory]; seqlocks for tiny POD [memory].
- **How Rune uses it.** The command channel is semantically two things; use two primitives:
- *Ordered, lossless*: tree diffs, spring targets, text runs → one SPSC ring of **length-prefixed POD records**
(bump-encoded, no per-command allocation, trivially serializable for the USB/replay path: the ring's bytes *are*
the replay log).
- *Latest-wins*: gesture/scroll offsets, viewport, presented-frame id back to the app → triple buffer / atomics.
- *Read-mostly shared structure*: hit-test data (presented rects) that the **main thread** queries for input while
the render thread updates → left-right with a per-frame "swap" at the end of scene build. Alternative: render thread
answers hit tests via a message (adds a hop); left-right avoids the hop.
- **Numbers.** None I can cite for UI; triple buffering's whole point is that reader/writer collisions cost no waiting
vs mutexes (crate docs).
- **Risk.** Exact memory-ordering bugs. Mitigation: loom tests for each primitive (agents write these well), or use
the published crates and skip custom code.
- **Verdict.** Adopt, using published crates first; hand-roll the byte ring only when the allocator counter says so.
### 6. Struct-of-arrays subtree-contiguous tree + SIMD hit-test/cull — verdict: **adopt layout; spike SIMD**
- **Sources.** [Clay](https://github.com/nicbarker/clay) (flat arrays, arena, two-pass flex layout, "microsecond layout"
claim from its README; author's walk-through video is the best explainer) [memory/search snippets]; Dear ImGui (ID
stack + immediate draw lists with a single vertex/index buffer per window) [memory]; Xilem/Masonry's per-pass dirty
flags (`needs_layout`, `needs_paint`) [memory].
- **How Rune uses it.** Store nodes in DFS pre-order with `subtree_end[i]`. A subtree is a contiguous index range, so:
dirty propagation = range ops; clipping/culling = skip `i..subtree_end[i]`; "is this subtree animating" = one flag;
scene build is a linear scan. Rects as four `f32` columns (`x0,y0,x1,y1`) so a hit test or visibility test over 4 or 8
nodes is one NEON/AVX compare + movemask (`std::simd` is still unstable; `wide` or hand-`core::arch::aarch64` works).
Keep a `Vec<Node>` (AoS) reference implementation behind the same trait for differential tests (tenet 7).
- **Numbers.** None measured. **Estimate**: hit-testing 10k nodes goes from ~10-20 µs scalar to ~3-5 µs with NEON; at
120 Hz neither matters unless pointer-move storms run every frame, so SIMD is low priority.
- **Cost/risk.** DFS ordering is awkward on keyed insertion mid-tree (renumbering). Mitigate with generational ids plus a
per-frame compaction; the tree is rebuilt from views anyway.
- **Verdict.** Adopt DFS-contiguous SoA now; SIMD hit-test later, behind a counter that proves it matters.
### 7. Per-frame bump arena + counting allocator as a test gate — verdict: **adopt now**
- **Sources.** [bumpalo](https://github.com/fitzgen/bumpalo) [memory]; a counting `GlobalAlloc` (e.g.
[stats_alloc](https://docs.rs/stats_alloc), or ~30 lines hand-written) [memory]; PLAN tenet 7 already mandates it.
- **How Rune uses it.** Scene build, diff scratch and El construction go in an arena that resets per frame; long-lived
data (tracks, atlas, node SoA) are pre-sized `Vec`s with capacity reuse. A test asserts `allocations == 0` between
`begin_frame` and `present` for a fixed catalog of scenes, **at rest and while animating**. Note `El` trees built by
views each rebuild will allocate unless `El` children are arena slices; plan for `&'frame [El]` not `Vec<El>`, a
signature decision that is expensive to retrofit.
- **Verdict.** Adopt now and make the arena lifetime part of the `El` type from day one.
### 8. Apple Silicon unified-memory upload: write instance data in place — verdict: **spike (after wgpu baseline)**
- **Sources.** Apple [Metal Best Practices: Resource Options](https://developer.apple.com/library/archive/documentation/3DDrawing/Conceptual/MTLBestPracticesGuide/ResourceOptions.html)
(unified memory: CPU and GPU share system memory; `Shared` is the natural mode; triple-buffer dynamic data with a
semaphore) [search page]; `newBufferWithBytesNoCopy` needs page-aligned, page-multiple-length memory (and gotchas
on StackOverflow when contents read as zero) [search page].
- **How Rune uses it.** Per-frame instance buffer = a ring of 3 persistently mapped `Shared` buffers; scene build writes
`UberQuad` instances **straight into the mapped slice** (no intermediate `Vec`, no memcpy). Atlas uploads: write into a
`Shared` staging region and `blit`/replaceRegion only dirty rects; glyph atlas on Apple can be `Shared` texture
directly. The shaped-text path can emit instances directly from cached glyph runs.
- **wgpu caveat.** wgpu's `queue.write_buffer` copies through an internal staging belt; to avoid that use
`mapped_at_creation` or `Buffer::map_async` rings, which on Metal map to the same unified allocation, but verify that
claim by reading wgpu-hal's Metal buffer code before relying on it [unverified].
- **Cost/risk.** Honest answer: the memcpy of a few hundred KB of instances is ~tens of µs on M-series (**estimate**), so
this is a polish item not a bottleneck. Prioritize it only if frame traces show `encode` dominated by copies.
- **Verdict.** Spike with raw Metal in the §4.2 later backend; don't contort the wgpu path.
### 9. Damage tracking on a TBDR GPU — verdict: **later**
- **Source.** Apple GPUs are tile-based; load/store actions control bandwidth [memory]. `CAMetalLayer` presents the whole
drawable and rotates 2-3 of them, so partial redraw requires "buffer age" bookkeeping (EGL `EXT_buffer_age`-style) to
re-copy or re-draw regions that were stale in this drawable [memory].
- **Opportunity.** Idle-ish frames (caret blink, a tiny spinner) draw a scissored rect. PLAN §4.3 already lists dirty-rect
scissoring. Win is **power**, not frame time. A caret blink at 2 Hz is "zero ticks" anyway if you present only on change.
- **Verdict.** Later. First measure whether a full pass at rest-with-small-change costs notable energy (Instruments
energy log) before building damage-history machinery.
### 10. Rust compile-speed levers, measured — verdict: **adopt the cheap ones now**
| Lever | Result | Source | Verdict |
|---|---|---|---|
| `[profile.dev.package."*"] debug = false` | clean build −22% / −30% (nushell, 799 units, M-series, Rust 1.99); `target/` 4.3→2.3 GB | [ImportStatic, Oct 2026](https://importstatic.com/rust/rust-debug-build-cargo-profile) [fetched] | **adopt** |
| leave `split-debuginfo` at macOS default (`unpacked`) | `packed` took edit→build from ~2 s to ~18 s | same [fetched] | **adopt** (never set `packed` in dev) |
| `debug = false` everywhere | clean −16/−20% but rebuild-after-edit *slower* (3.1-3.7 s vs 1.6-2.8 s, extra `strip=debuginfo` pass, likely cause unproven) | same | avoid |
| Linker choice on macOS | final link only ~2-4 s of a 112-216 s clean build; ~2 s incremental | same [fetched] | linker is not the bottleneck on Mac |
| mold | 4.9× lld, 1.9× wild at median; M1 Ultra (Linux) debug links 1.5-10× lld; README lists `macho/` in repo and says it's now written in Rust with an ASPLOS 2027 paper | [mold README](https://github.com/rui314/mold), [paper](https://arxiv.org/abs/2608.23228) [fetched] | watch: its Mach-O status unverified; check before assuming |
| wild | Linux-focused ("a very fast linker for Linux") | [wild](https://github.com/wild-linker/wild) [search snippet] | no use on macOS |
| Cranelift backend (`rustc_codegen_cranelift`) | reported 20-30% less clean-build time on some projects [reddit anecdote]; **no unwinding on macOS, several arm64-macOS ABI incompatibilities with LLVM** (June 2025 report) | [bjorn3 report](https://bjorn3.github.io/2025/06/30/progress-report-june-2025.html) [fetched] | **skip on Apple**; maybe on Linux CI |
| Parallel front end (`-Zthreads=N`) | claimed 20-30% on nightly; stabilization is a 2026 goal; known deadlock/ICE/incremental issues being fixed, no robust test suite yet | [Rust goals 2026](https://goals.rust-lang.org/2026/parallel-front-end.html) [fetched] | spike on nightly in a throwaway profile, not for the main loop |
| rustc itself | ~4.6% mean wall-time gain over two months of compiler work | cited in ImportStatic from Nethercote's Sept 2026 roundup [fetched, secondhand] | free over time |
**Rune-specific levers (mostly my recommendations, not measured):**
- **Crate split along the hot-patch boundary:** `rune-core` (arena, tree, tracks, protocol; changes rarely) /
`rune-render` / app view crates. Subsecond patches the app crate only; keeping the patched crate tiny is the main
determinant of patch time (estimate: patch time ≈ incremental compile + thin link of that crate).
- **Dev profile:** `opt-level = 1` for the rune crates (springs/layout at `opt-level = 0` are too slow to feel right at
120 Hz) and `opt-level = 3` for Taffy/Parley/skrifa/wgpu via `[profile.dev.package.taffy]` etc. This is the well-known
Bevy recipe [memory]; heavy deps compile once and stay cached.
- **Type-erased views and no generics tower** (already tenet 7); generics → `-Zshare-generics` helps incremental
[memory].
- **`cargo check`-speed inner loop for agents** is likelier to be dominated by rust-analyzer-like analysis than linking;
run `cargo check` with `-Zthreads` only on a spike machine.
- The numbers above come from a 12-core Apple-silicon Mac, so
larger machines should do better. **Do a one-hour measurement of the real Rune workspace on a build Mac** before
committing to any of this beyond the two profile lines.
### 11. Hot patching: shrink what's patched — verdict: **spike already in plan; tighten the design**
- **Source.** [subsecond](https://docs.rs/subsecond): detours calls through a jump table; patches are separate objects
built by intercepting the link step and driving `rustc` manually; "works across macOS, Windows, Linux, iOS, Android"
per the author ([HN](https://news.ycombinator.com/item?id=44369642), [search snippet]); requires an ASLR reference
address from the running process.
- **How Rune uses it.** The plan's state design (typed models outside views, keyed by stable ids) is what makes patching
safe, since struct layout changes break old state. Add: (1) models are the only state that crosses a patch, and a
**layout hash of each model type** is stored with it; a mismatch triggers a reset of that model only, with an
inspector message, rather than UB; (2) keep the render thread's code out of the patch set (it's in `rune-render`
and not hot), so animation continues during a patch; (3) patch granularity = view functions, handlers.
- **Cost/risk.** Layout-hash gating is the difference between "usually works" and "agents trust it". Known from subsecond
docs: changing struct layouts requires a rebuild.
- **Verdict.** Already planned; add the layout-hash guard and render-thread isolation as requirements.
### 12. PGO from replayed command streams; BOLT later — verdict: **later (post-M3)**
- **Sources.** [cargo-pgo](https://github.com/Kobzol/cargo-pgo) and [Kobzol's write-up](https://kobzol.github.io/rust/cargo/2023/07/28/rust-cargo-pgo.html)
(PGO + BOLT; the tool's README claims up to ~15% speedups [search snippet]; Rust's own compiler ships PGO/BOLT-optimised
builds). Mach-O BOLT support was not mature when I last looked [memory, unverified]; PGO works with LLVM on macOS.
- **The agent-specific trick.** Rune records the command channel for deterministic replay (PLAN §6). A set of replayed
sessions (scroll a long list, spring storms, typing, window resize) is a **reproducible, repo-checked PGO training
corpus**, which most apps lack. CI can produce a profile and rebuild with `-Cprofile-use` automatically, and perf
counters (instructions) gate regressions precisely.
- **Cost/risk.** Profile staleness and build time (two-stage builds); PGO varies in effect on already-branch-light
SoA code. Estimate 3-10% on scene-build/layout paths; I would not expect it to change a 120 Hz verdict.
- **Verdict.** Later. Do it for shipped release builds once the scene catalog stabilises.
### 13. Text: cache before you SIMD — verdict: **skip SIMD; adopt cache design**
- **Sources.** [simdutf](https://github.com/simdutf/simdutf) (GB/s UTF-8↔UTF-16 validation/transcoding; used by Node,
Bun, ghostty) [search page]; Ash Vardanian's [UTF-8 SIMD search](https://ashvardanian.com/posts/search-utf8/) [search
page]. Both target bulk text.
- **Assessment.** UI strings are short; the cost is shaping and rasterizing, not validation or transcoding. The one place
bulk text matters is the editor (rope + sum tree, PLAN §4.6), where Zed's tree already gives O(log n) offsets. An ASCII
fast-path (all bytes < 0x80 → skip bidi/script itemization, use cached advance table) is worth more than SIMD and is
~20 lines.
- **Do instead.** Glyph-run cache keyed by `(font id, size, features, text hash)`; wrap-interval caching (idea 4);
shape off the main thread for paragraphs above N glyphs (already in plan).
- **Verdict.** Skip SIMD text; adopt ASCII fast path + caches.
---
## Steal
- Slate's four dirty classes and the **Volatile** escape hatch; avoid time-phased retainers.
- Chromium property trees: instances reference tree nodes, so animation touches nodes not geometry.
- Salsa/Incremental **early cutoff**; React Compiler's memoize-by-input-versions idea; comemo's recorded-constraint hits.
- Clay's flat arena + contiguous subtrees; ImGui's single shared vertex/index buffer per frame.
- Triple buffer for latest-wins, byte-encoded SPSC ring for ordered commands (the ring is also the replay log).
- Counting allocator as a unit test; "frame arena in the `El` lifetime".
- `debug = false` for dependencies; `unpacked` split-debuginfo on macOS.
## Avoid
- A general reactive dependency graph (Salsa/Adapton/AttributeGraph): conflicts with hot-patch state survival; use
version stamps.
- Retainer/offscreen caching by timer ("render on phase"): the one measured foot-gun (50.9 ms, worse than uncached).
- Cranelift on Apple until macOS unwinding and arm64 ABI land.
- `split-debuginfo = "packed"` in dev profiles (+16 s per edit).
- SIMD for text validation/transcoding; SIMD hit-testing before a counter justifies it.
- Hand-written lock-free structures when published crates work; BOLT on Mach-O.
## Recommendation for Rune (ranked)
1. **Property-tree scene + GPU-evaluated spring tracks** (idea 1): the one idea that can make "animation costs the CPU
nothing" literally true; spike early, with a CPU reference evaluator.
2. **Dirty classes + early cutoff + exact counters** (ideas 2, 3): gates "zero work at rest" with numbers.
3. **Frame arena in `El`'s type + counting allocator** (idea 7): a signature decision that is expensive to change later;
decide before the view API ships.
4. **Command channel = byte SPSC ring + triple buffer, loom-tested** (idea 5), doubling as the replay log.
5. **Two-line Cargo profile + measured compile baseline** (idea 10), then hot-patch hardening (idea 11).
**Rejected alternatives:** Salsa/SwiftUI-style graph (state vs patches); Slate retainers by phase (measured regression);
Cranelift on Apple (unwinding, ABI); SIMD text (wrong bottleneck); damage-history tracking now (power only, unmeasured).
## Open questions
- Does wgpu's Metal backend expose a path to write instance data in place without a staging copy? (read wgpu-hal.)
- Can edge-animated rounded rects and their text be expressed as property-tree nodes, or does idea 1 need per-instance
edge tracks only? (Prototype in the spring scene catalog.)
- Is mold's Mach-O linker production-ready on macOS 27 (the README lists `macho/`)? Only matters if link time shows up
in the real Rune workspace, where the nushell data says it won't.
- Real Rune compile numbers: baseline `cargo check`, dev build, and patch time with the crate split.
- Is a layout-hash guard on models enough for agent-trusted hot patching, or do we need a full state-migration hook?
- Measure energy (not frame time) of full-pass-at-rest-with-small-change to decide whether idea 9 is worth building.
+134
View File
@@ -0,0 +1,134 @@
# 18. Desktop timeline motion: what the DOM branch learned
Scope: the OpenCode Desktop session timeline on branch `timeline-motion` (PR #57224, head `39eb86d`), for the Rune
rebuild of the session page. Written 2026-10-22. Constants come from source unless marked *measured* (the
branch's `.jank` harness) or *not in code*. Bare file names are under `packages/app/src/session/timeline/`.
## Summary
- One spring, `timeline.growth` at 0.32 s and bounce 0 (`row-growth.ts:6-14 @ 39eb86d`), drives row growth, gap
closing, Working's glide and the send flight. Springs are analytic and keep velocity when retuned
(`packages/ui/src/motion/spring.ts:59-91 @ 39eb86d`), but per-frame pixel caps make growth frame-rate dependent.
- The streaming edge is still an open decision, and "coming back lands at the bottom" is *not in code*.
## 1. Streaming edge and word reveal
The four edges are one table (`row-growth.ts:31-40 @ 39eb86d`):
| Edge | mask max | floor | shrink/frame | catch-up | duration × | clip |
|---|---|---|---|---|---|---|
| Feather | 28 px | 18 px | 1.8 px | 1 | 1 | yes |
| Fast Feather | 12 px | 6 px | 4 px | 2.4 | 0.55 | yes |
| No Mask, Word Fade | 0 | 0 | 28 px | 1 | 1 | no |
The mask aims for `min(max, max(floor, 1.5 × leftToGrow))`, growing at most 5 px per frame (`row-growth.ts:311-317
@ 39eb86d`). Its gradient has 72% opacity at 0.62 of its height and 28% at 0.28, rounded to whole pixels so
unchanged masks aren't rewritten (`row-growth.ts:586-597 @ 39eb86d`).
The "15 px mask, 40 px trail" figures are *measured* means: Feather showed 15.3 px of mask with content 39.5 px
ahead of the shown height, Fast Feather 5.7 and 19.8, No Mask 0 and 37.2, Word Fade 0 and 34.7.
Words fade in over 180 ms ease-out (`packages/session-ui/src/components/markdown.css:54-56 @ 39eb86d`); No Mask
disables the fade and Word Fade makes it 360 ms (`markdown.css:470-480 @ 39eb86d`). The stagger between words is
20 ms, shrinking to 5.5 ms as the backlog grows (`packages/session-ui/src/components/markdown-solid.tsx:22-33 @
39eb86d`).
Paced text shows backlogs under 512 characters at once and reveals larger ones in chunks every 24 ms, snapped to
word or punctuation boundaries (`packages/session-ui/src/message/message-content.tsx:118-222 @ 39eb86d`). A live
row also holds back a trailing partial word of up to 24 characters
(`packages/session-ui/src/timeline/session-timeline-row.tsx:80-95 @ 39eb86d`).
## 2. Row growth
Growing rows share one spring whose step is a budget split between them (`row-growth.ts:163-339 @ 39eb86d`). Each
frame's take is capped (`row-growth.ts:222-239 @ 39eb86d`): it starts at 1.875 px, ramps up by at most 2.2× per
frame, and is capped at 11.5 px, rising to 16 px for long distances, or 7.5 px while carrying Working. Streaming
rows slow further near their target (`(0.085 × rem + 0.65) × catchUp` within 36 px).
Only the ramps scale with `dt`, and `dt` is clamped to 1/30 s (`row-growth.ts:356 @ 39eb86d`), so the 16 px cap is
per frame. A 457 px bubble took about 1.5 s at 30 fps headless and about 0.5 s at 60 fps (*measured*). A growth
bent toward a nearer target lands there instead of overshooting (`row-growth.ts:177-178 @ 39eb86d`).
Growth joins follow in `settle`: rows resize without TanStack's per-row scroll correction, then one `pinEnd` write
holds the end (`virtualizer.tsx:483-540 @ 39eb86d`). Space freed by the composer or a removed row is held under the
last row and closes on the same spring after 120 ms without growth (`row-growth.ts:359-366 @ 39eb86d`). A
streaming row never shrinks below what it shows (`virtualizer.tsx:709-719 @ 39eb86d`).
## 3. Send flight
In `send-flight.ts @ 39eb86d`, only the composer's visible lines are cloned, clipped with `clip-path` (lines
38-58). When the bubble mounts, a clone flies on `growthSpring` with `dt` capped at 1/60 (line 189). The measure
phase re-reads the live bubble rect every frame, so flights retarget as earlier bubbles land (lines 175-180). The
clone scales uniformly by width and reveals its height through a `clip-path` inset from where the composer had
scrolled (lines 200-209). If the wraps differ by over 2 px (line 166), composer text is gone by p = 0.25 and the
clone fades in over p = 0.1-0.4; otherwise they finish at 0.4 and 0.5 (lines 210-213).
## 4. Working tail row
Working is its own 36 px `Activity` row at the end of the active turn (`message-timeline.tsx:229-250 @ 39eb86d`),
inside an 82 px reserved tail (`virtualizer.tsx:50-52 @ 39eb86d`). At turn end it hands off over 0.34 s, blurring
to 6 px and scaling to 0.5 while the copy button sharpens from scale 0.6 (`row-growth.ts:53-102 @ 39eb86d`,
`virtualizer.tsx:937-995 @ 39eb86d`).
## 5. Steer promotion
Admission used to add a 24 px "Steering" label and move Working. Now the client predicts the status a steer sent
now will get (`packages/client/src/solid/data.ts:294-305,1491-1494 @ 39eb86d`), and the just-sent bubble sits where
admission will put it (`controller.tsx:89-114 @ 39eb86d`). On promotion, Working glides on the growth spring while
the gaps it leaves shrink in proportion (`virtualizer.tsx:775-847 @ 39eb86d`). A row shrinking mid-glide joins the
glide unless it is past 75% (`virtualizer.tsx:736-752 @ 39eb86d`).
## 6. Width-change easing
`holdLandingWidth` gives rows their landing width when a side panel starts moving, so text wraps once
(`packages/app/src/shell/panel-motion.ts:151-200 @ 39eb86d`). Heights wait for 120 ms of stable width, then growing
rows ease to their new heights; for 400 ms a streaming row may shrink (`virtualizer.tsx:672-693 @ 39eb86d`).
## 7. Pretext sub-line measurement
Rows are measured with `@chenglou/pretext` where possible. While streaming, the last line's fill is measured
(`packages/session-ui/src/timeline/text-layout.ts:156-170 @ 39eb86d`) and the target height lags by up to 0.52
(one line) or 0.82 line heights, less as the line fills, rounded to 1/64
(`packages/session-ui/src/timeline/markdown-layout.ts:168-180 @ 39eb86d`). A new line's height arrives as it
fills. The followed row uses this `streamHeight` (`virtualizer.tsx:466 @ 39eb86d`).
## 8. The 1/64 px grid
Heights and offsets are rounded to 1/64 px (`row-growth.ts:16 @ 39eb86d`, `virtualizer.tsx:46-48 @ 39eb86d`).
Chromium rounds `scrollTop` to whole pixels, so `writeScroll` writes the floor, draws the remainder as a
`translate`, and defers the commit until growth settles (`virtualizer.tsx:569-636 @ 39eb86d`). Sub-pixel reversals
went from 3163 to 0 (PR body).
## 9. Follow and coming back
Following needs pinned, a finished cold mount, no touch and no reduced motion (`virtualizer.tsx:769-771 @
39eb86d`). Losing it lands every growth (`virtualizer.tsx:1137-1145 @ 39eb86d`). Cold opens stay hidden until
fonts load and the bottom is pinned (`virtualizer.tsx:1421-1445 @ 39eb86d`).
A newer requirement is *not in code*: returning to a session, tab or window paints the bottom in the first
frame, with no animated scroll, nothing that arrived while away streaming or growing, and no remembered position.
While visible and following, a target more than about a viewport away should cut instead of gliding. Today a hidden tab pauses rAF, the first frame back clamps `dt` to 0.1 s (`packages/ui/src/motion/loop.ts:61 @
39eb86d`), growth clamps it to 1/30, and the backlog animates at the per-frame cap. Paced text doesn't flush.
## What was hardest in the DOM
- **Reads vs writes.** Per-frame work goes through `frameLoop.addMeasured`, which runs all reads before any writes
(`loop.ts:68-99,136 @ 39eb86d`). One stray rect read after a write forces layout.
- **Caps per frame.** Headless 30 fps looks about 2× slower than 60 fps.
- **Reflow mid-animation**, handled by landing widths and the width hold.
- **Unknown heights.** TanStack doesn't cache a measurement equal to its estimate, which looped
(`virtualizer.tsx:1069-1070 @ 39eb86d`); pretext avoids DOM measurement.
- **Main-thread stalls.** SSE now flushes on rAF (commit `31c63cef78`); a ~170 ms render task on session open
remains.
- **Masks and clip-path.** Writes are rounded and deduplicated; paint cost was never measured.
## What Rune should guarantee
1. Springs evaluated in time, with speed limits per second, so 30 fps and 120 Hz give the same curves.
2. Retargeting that keeps position and velocity (`spring.ts:85-86 @ 39eb86d`).
3. Synchronous text measurement, including last-line fill.
4. A measure phase before a mutate phase, enforced by the API.
5. Fractional scroll offsets and wrap-once width animation.
6. No one-frame disappearance; leaving nodes fade where they stand.
7. A global reduced-motion mode that keeps 0.11-0.2 s opacity fades.
8. A settle-all for resume that lands every track and flushes paced text before the first frame.
+254
View File
@@ -0,0 +1,254 @@
# 23. Text raster quality and motion
S5 from PLAN.md. Headless bitmaps only; no window or display capture. Results
below are filled from outputs, not from the hypothesis.
## Oracle and metrics
`crates/rune/examples/text_quality.rs` renders Inter Regular and system SF at 11, 12, 13, 15
and 24 pt, 1×/2×, #181818 on #eeeeee and its inverse. Five strings per size
cover prose, UI labels, digits, ambiguous letters, ligatures and a stem probe.
It exports the exact Parley glyph IDs, quarter-pixel x positions and snapped
baselines. `scripts/coretext-quality.swift` draws those same glyphs with the
same font bytes into an sRGB CoreGraphics bitmap, with grayscale antialiasing,
font smoothing and fractional positioning enabled. This isolates **raster and
blend quality**. It does not claim parity with CoreText's shaping, optical-size
selection, SF tracking or line breaking. SF is supplied from the local system
font, never redistributed.
Measured on an Apple M5 Max, macOS 27.0.1 (26A434). Font SHA-256:
- Inter: `40d692fce188e4471e2b3cba937be967878f631ad3ebbbdcd587687c7ebe0c82`.
- `/System/Library/Fonts/SFNS.ttf`: `44890958f3e0b997028121ed7c7a789f3f5cce227c7a93ce8f86ec0db26da571`.
SF's registered family is `System Font`. The CoreText oracle explicitly sets
`opsz` to point size × scale, matching Parley's current variation selection.
Without this, the 2× reference uses a different SF outline. This calibration
covers regular Latin UI text, not CJK, emoji, bold/italic, arbitrary backgrounds,
or native SF tracking. The CoreText bitmap is a reference, not an AppKit capture.
`scripts/text-quality.py` reports Gaussian SSIM (sigma 1.5, population covariance,
data range 1) on each row's ink-bounded horizontal crop. Each row gets equal
weight; full-page blank backgrounds do not inflate the score. It also reports
signed and absolute relative ink-weight error, normalized ink MAE, and per-glyph
advance-cell coverage/weight. Overlapping side bearings belong to the adjacent
cell; these are attributed cells, not independently rasterized isolated glyphs.
No image alignment search, rescaling or blur is used to improve scores.
The phase sweep moves `lHEximno` through two device pixels, 64 timestamps per
pixel. Each frame is a separate 40 px strip rendered through the real GPU path.
Inverse-sRGB decoding recovers linear coverage; coefficient of variation,
peak-to-peak range and adjacent-frame RMS quantify brightness shimmer. This
coverage metric is separate from perceived brightness after nonlinear blending.
## Baseline policy and constraints
- `text.rs` already uses four x phases and whole-pixel baselines, including
negative coordinates and carry into the next pixel. Hinting is on at 1× and
off at 2×. Atlas is **2048² R8** (the older README said 1024²).
- `shader.wgsl` uses exact texel loads for ordinary text. Bilinear filtering is
reserved for scaled flight snapshots. Changing filtering for ordinary text
would add blur to already phase-rasterized glyphs.
- The baseline `runtime.rs::glyph_gamma` uses `0.78 + 0.22 * sRGB(luminance)`.
- `rune-motion/src/layer.rs::settle_after` already computes a conservative
analytic settle time; the store lands at `(target, 0)` and removes the track.
Do not replace this with frame-by-frame epsilon tests or a second text spring.
- Preserve the shaped-layout cache, retained Taffy cache, virtual rows,
reusable cluster scratch and zero-allocation presentation gate.
## Sources inspected
1. [Wang et al., Image quality assessment: From error visibility to structural
similarity, IEEE TIP 2004](https://ece.uwaterloo.ca/~z70wang/research/ssim/).
SSIM is a spatial image metric, not proof of native subjective equivalence.
2. [Skia, The Raster Tragedy](https://skia.org/docs/dev/design/raster_tragedy/).
Distinguishes linear blending, the guessed-background gamma hack, optical
sizing and contrast enhancement. Full-pixel grayscale gamma adjustment is
not the same as LCD subpixel correction. CoreText's optical emboldening can
depend on nominal size, unlike hinting at final pixel size.
3. Kit's Apache-2.0 GPUI fork (`kitlangton/gpui`), commit
`2e52b98886063ddfa828312c83415a14208dfe87`,
`src/platform/mac/text_system.rs:194–201, 444–458`. Five luminance buckets
(0, .25, .5, .75, 1) select CoreText smoothing through the **fill color of an
alpha-only CGContext**. This is not a five-radius morphological max filter;
blindly copying bucket numbers into swash dilation would not reproduce it.
4. [Research 15 §7](15-research-motion-perception.md): pixel-y, quarter-phase x,
analytic settling, shared container tracks, a phase-sweep brightness oracle.
5. [WebRender macOS rasterizer](https://searchfox.org/mozilla-central/source/gfx/wr/wr_glyph_rasterizer/src/platform/macos/font.rs)
probes actual OS smoothing behavior, distinguishes dilation from LCD AA,
quantizes color for its smoothing masks and preblends grayscale. Its native
CoreGraphics masks cannot be copied into a deterministic swash path. Historical
[issue 1767](https://github.com/servo/webrender/issues/1767) documents separate
light/dark weightings, not a universal gamma constant.
## Experiments
| Experiment | Decision | Evidence |
|---|---|---|
| Independent swash oracle, default hinting, zero emboldening | Control | All four Inter GPU images and phase metrics equal production baseline. |
| No hinting at 1× | Keep with calibrated weight | Inter 1× dark SSIM .971615 → .981808; light .958593 → .964075. Alone it makes light-mode weight slightly worse. |
| 3×3 max-filter coverage dilation plus gamma sweep | Reject | A diagnostic approximation, not CoreText's outline smoothing. Broadens outside pixels and needs extra work; centered outline emboldening wins. |
| Centered swash outline emboldening, .1 device px | Partial | Improves 2× weight but overweights 1× light-on-dark with the old exponent. |
| Centered emboldening, .1 point (.1/.2 device px), scale-aware exponent | Keep | Weight error improves in all eight font/polarity/density groups; SSIM improves in seven. SF dark 1× is the exception below. |
| Fixed exponent `.375 + .875 * sRGB(luminance)` | Reject | Good static Inter fit, but SF dark 2× brightness variation regresses. The final density-aware expression improves all eight brightness probes. |
| Five luminance-keyed atlas copies | Reject for this pass | kitlangton/gpui's buckets invoke CoreText, not five interchangeable swash radii. A single shape plus continuous blend correction avoids up to 5× cache cardinality and bucket jumps during theme animation. |
| Bilinear filtering of ordinary glyphs | Reject | Quads already land on device pixels with rasterized x phases. Resampling them again softens text; flight filtering remains separate. |
Calibration used the first two strings at each size; the remaining three were
held out. With .1/.2 device-pixel centered emboldening, the best gamma-only
training fits were .45/.45 for dark-on-light and 1.15/1.20 for light-on-dark.
The retained candidate uses one continuous expression,
`0.35 + (1.15 + 0.2 * clamp(scale - 1, 0, 1)) * sRGB(foreground_luminance)`.
This balances static weight with phase-dependent brightness, rather than
minimizing the training error alone. Outline expansion is recentered in both axes:
swash's `embolden(d)` adds
`d` translation as well as expansion. The cache key includes `d`: 12 pt at 2×
and 24 pt at 1× have the same pixel size but different nominal-size smoothing.
An early build emitted empty quads for spaces because emboldening gives empty
outlines nonzero bounds. Rejecting all-zero masks restores the original instance
count; the phase/cache test includes whitespace to prevent recurrence.
The offline `coverage-*.png` diagnostic overwrites overlapping glyph masks; it
is only a parameter-search approximation. All static results below come from
actual GPU source-over output, not that approximation.
### GPU results, Inter
All SSIM values are row-crop means. Weight is mean absolute row ink-weight error.
| Mode | SSIM before → after | Weight error before → after |
|---|---:|---:|
| Dark, 1× | .971615 → .980707 | 7.46% → 6.46% |
| Dark, 2× | .982463 → .985549 | 11.93% → 6.32% |
| Light, 1× | .958593 → .982740 | 30.14% → 4.04% |
| Light, 2× | .968310 → .990795 | 22.84% → 3.46% |
### GPU results, SF
| Mode | SSIM before → after | Weight error before → after |
|---|---:|---:|
| Dark, 1× | .949609 → .948209 | 8.10% → 6.20% |
| Dark, 2× | .977342 → .979416 | 12.42% → 7.13% |
| Light, 1× | .923434 → .950077 | 30.69% → 2.68% |
| Light, 2× | .963039 → .986747 | 23.87% → 2.80% |
The SF dark 1× SSIM loss is .001400 (held-out strings: .950056 → .949516),
despite better average weight. This is a deliberate tradeoff for better light
text weight and lower phase brightness variation, not universal CoreText parity.
The other seven held-out groups improve. Per-font/stage aggregates are in
`demo/text/metrics.json`. `scripts/text-quality.py` regenerates full row and
attributed-glyph results, including 11/12/13/15/24 pt separately, in the ignored
run directory. The public report deliberately omits that large diagnostic data.
Group means hide size-specific losses: dark 1× SF at 24 pt loses .017929 SSIM,
and dark 1× Inter at 13 pt loses .010482. The retained policy favors the combined
weight/motion result; it is not a per-size static optimum.
### Motion
The production quarter-phase/pixel-baseline policy and conservative analytic
settle were already implemented. Keep them rather than introducing a second
text spring or switching hinting during motion. Two focused tests exercise
negative origins, phase carry, four cached phases per glyph, different nominal
sizes at equal pixel size, exact analytic landing, 120 identical resting samples
and no atlas writes after phase warmup. The warmed streaming allocation gate
still passes (zero allocations).
| Probe | Before | After |
|---|---:|---:|
| Raw coverage CV, 1× | .03688% | .02164% |
| Raw coverage CV, 2× | .01896% | .01165% |
| Inter display ink CV, light 1× | 1.54294% | .99005% |
| Inter display ink CV, dark 1× | .71390% | .20733% |
| Inter display ink CV, light 2× | .43394% | .27093% |
| Inter display ink CV, dark 2× | .46632% | .14171% |
| SF display ink CV, light 1× | 2.15455% | 1.65172% |
| SF display ink CV, dark 1× | .50179% | .23311% |
| SF display ink CV, light 2× | 1.20865% | .75191% |
| SF display ink CV, dark 2× | .22162% | .13237% |
Display ink is the polarity-normalized sRGB pixel difference from the background,
computed with the shader's exponent and linear source-over equation from the GPU
coverage sweep. It is not a psychophysical flicker threshold. Residual variation
is nonzero; the result supports **less shimmer**, not an unqualified “no shimmer”.
SF raw-coverage CV improves too, but its 1× peak-to-peak coverage rises from
.08582% to .10970%, and adjacent-frame coverage RMS from .01386% to .01444%.
Thus not every raw metric improves. This is a 13 pt horizontal stem probe at
virtual timestamps, not physical display cadence or a whole-font motion audit.
## Performance
Headless release on the same M5 Max, 120 Hz virtual time, one warmup and seven measured runs
per workload. Each pair alternates the saved original binary and the final one;
pair order reverses on successive runs. Synthetic fixtures only.
CPU includes update/build/encode/submit, excludes readback and is not GPU latency.
Both binaries end with **1,126 instances**. The atlas remains 2048² R8, four x
phases, no color-keyed copies, and warmed presentation still allocates nothing.
| Workload | CPU p50 before → after | CPU p95 before → after | First CPU frame before → after |
|---|---:|---:|---:|
| Stream | .313 → .295 ms | .665 → .604 ms | 4.98 → 5.39 ms |
| 2,000-message stream | .327 → .311 ms | 3.891 → 3.695 ms | 9.70 → 10.40 ms |
The machine was contended. p95 MADs were .171/.115 ms for stream and .203/.241 ms
for long-stream; first-frame MADs .55/.88 and .15/1.05 ms. Do not claim a speedup.
No warmed-frame regression is evident; a small first-raster cost remains possible.
Earlier unpaired baseline/final medians (.259/.334 ms stream p50) drifted with
load, so the paired comparison is authoritative. All paired runs and MADs are
retained in `demo/text/performance.json`. Research/19's structural caches,
virtualization and cluster scratch were not changed.
Saved executable SHA-256:
before `c2bb31da0a331b0fc68e9edbd228ac7df1e42ff3058851d32655d49f4f0cdb44`,
after `e4c7d51a1ef2b8b05fdc6ec1d9e66944d7cc39c5fc5ce1a312a28c5f86d8b368`.
## Images and goldens
`demo/text/{inter,sf}-{light,dark}-{1,2}x.png` shows before / after / CoreText,
one representative line at each of the five sizes. `*-diff-*.png` shows absolute
pixel error amplified 4×. `*-phases-*.png` shows nine raw-coverage positions.
`ui-crops.png` contains actual settings/OpenCode/kit before/after crops.
Inspected light/dark crops: dark-on-light stems gain the missing weight, rounded
edges remain antialiased, and 2× light-on-dark edges lose some bloom. Advance
positions and baselines stay fixed. SF 1× still has visible raster differences
from CoreText. The kit's Linux Chromium reference is a different oracle; its
scores need not improve when moving toward macOS weight.
`scripts/text-goldens.py` refreshes seven settings/OpenCode stills, two kit index
images and twelve kit side-by-sides. It keeps the committed web columns and
recomputes Rune plus the diff, without another browser capture. Updated scores
live in `demo/text/kit-metrics.json`.
The streaming still is standardized to `--at 4`; its former capture time was
not recorded, so its change includes that state adjustment. Historical motion
strips/videos retain their recorded states and are not current text goldens.
## Reproduction
```sh
mkdir -p .lab-output/text/target/perf
cargo test -p rune quality_tests
cargo test -p rune --test alloc
cargo build --profile perf -p settings -p kit-gallery # (the OpenCode fixture example has since moved out of this repository)
cargo build --release -p rune --example text_quality
swiftc -O scripts/coretext-quality.swift -o .lab-output/text/coretext-quality
cp target/perf/{opencode,settings,kit-gallery} .lab-output/text/target/perf/
cp target/release/examples/text_quality .lab-output/text/
# Headless bitmaps on the measurement host. Repeat for SFNS.ttf / "System Font".
FONT=crates/rune/assets/Inter-Regular.ttf
.lab-output/text/text_quality perf/autoresearch/text/before/inter "$FONT" Inter auto 0 legacy
.lab-output/text/text_quality perf/autoresearch/text/after/inter "$FONT" Inter
.lab-output/text/coretext-quality perf/autoresearch/text/before/inter
.lab-output/text/coretext-quality perf/autoresearch/text/after/inter
uv run --with numpy --with pillow --with scikit-image scripts/text-quality.py perf/autoresearch/text/before/inter
uv run --with numpy --with pillow --with scikit-image scripts/text-quality.py perf/autoresearch/text/after/inter
# After both fonts:
uv run --with numpy --with pillow scripts/text-report.py perf/autoresearch/text demo/text
mkdir -p target/perf target/release
cp .lab-output/text/target/perf/{opencode,settings,kit-gallery} target/perf/
cp .lab-output/text/target/perf/{opencode,settings,kit-gallery} target/release/ # for text-goldens.py
python3 scripts/bench-ui.py --only stream,long-stream --out perf/autoresearch/text/perf-after
python3 scripts/text-bench.py --before .lab-output/text-before/target/perf/opencode \
--after target/perf/opencode --out perf/autoresearch/text/perf-paired-new
uv run --with numpy --with pillow scripts/text-goldens.py
```
+192
View File
@@ -0,0 +1,192 @@
# 24. Reference renderer and differential testing
Reader: the next agent changing Rune's renderer. Run the commands
below before changing a tolerance or a shader formula.
`crates/rune-ref` evaluates Rune's current instance stream on the CPU and checks
the production wgpu renderer against it. The first corpus found a glyph sampling
bug: interpolated screen coordinates selected an adjacent atlas column. Its
single-primitive regression differed by up to 83 channel levels before the fix.
After the fix, measured single-primitive errors are at most 1 level; composited
scenes reach 2. The gate allows 2 per channel and **zero outlier pixels**.
## The oracle evaluates the formulas Rune actually ships
The scalar evaluator implements the five instance kinds present when this work began:
| Kind | Reference behavior |
|---|---|
| 0 | Per-corner rounded-rect SDF, clamped capsule radii, softness, and an inset border (uniform or per-side) over the fill, hiding it by its alpha before opacity (`params[3]`) |
| 1 | Evan Wallace shadow formula, the shader's erf approximation and four y samples |
| 2 | R8 glyph texel loads, scaled bilinear footprints, coverage exponent; `params[0]` turns the quad about its centre and samples bilinearly in the glyph's own frame |
| 3 | Inset shadows with spread, offset and the sharp/blurred branch at sigma .3; square corners take exact pixel areas |
| 4 | Vertical premultiplied-linear gradient with rounded-rect coverage |
Every kind uses the shader's four independent soft clip ramps. Expanded quad
bounds are included, since the GPU cannot shade outside its triangles. Outlines
and capsules already lower to rounded-rect instances. Positions are device pixels.
Translation, positive glyph scale and glyph rotation are the transforms the current
instance ABI supports for these five kinds. The generator keeps glyph rotation at zero:
at arbitrary angles a turned edge can pass within the rasterizer's sub-pixel precision of
a pixel centre. `rotated_glyphs` covers quarter turns, whose edges stay half a pixel away. Arbitrary affine transforms, path rendering, group
opacity and backdrop blur are not covered by this oracle.
During the publication rebase, main added vector segment/triangle kinds 5 and 6
(`d666064`). Those new kinds are rejected by this oracle's validator and are not
generated yet; extending the independent formulas and corpus is follow-up work.
`vello_cpu` was considered, as PLAN §6c requests. Its path-area coverage would
introduce a second antialiasing definition, and its rounded-box blur need not
match Rune's four-sample approximation. A direct evaluator is a closer oracle
for our WGSL. Vello remains a good candidate for the future path renderer.
The CPU implementation is independent code, not generated from the shader.
That catches implementation drift; it cannot prove a shared mathematical model
is visually correct or that the four-sample shadow approximates a true Gaussian.
The CPU lane uses strict scalar Rust f32 operations, fixed loop order, no
`mul_add`, and pinned `libm = 0.2.16` with `force-soft-floats` for
sqrt/exp/pow/round/floor. That feature disables libm's architecture shortcuts even
when another workspace dependency enables its default `arch` feature. Gate scripts
also pass `-C llvm-args=-fp-contract=off`; do not enable fast-math. Each blend
decodes the previous sRGB RGBA8 pixel, applies premultiplied source-over, and
quantizes back to sRGB RGBA8. Alpha stays linear. Clear is quantized too.
Sixteen BLAKE3 hashes in `goldens.json` pin the canonical corpus. Cross-architecture
byte equality still needs the Linux run; it is a design goal, not measured evidence.
The sixteen hashes agree in debug and optimized release builds on arm64; the
release check explicitly disabled FMA contraction. CPU-target Clippy passed with
warnings denied. The CLI regression replay reports node 4, `generated/3`, at
13,34 and a maximum GPU delta of 1 with no outliers.
The CPU-only build has no Rune/wgpu/window/font dependency. `--features gpu`
adds a field-by-field adapter to **Rune's real Renderer**, including its shader,
blend state, atlas upload and sRGB Offscreen readback. `Primitive::from_instance`
accepts real emitted instances with a node/source sidecar. Frozen atlas bytes in
a JSON scene make replay independent of subsequent font/shaper changes.
## One generator drives the checks
`generate::scene` decodes a vector of bounded 32-byte records. Each record controls
kind, geometry, per-corner radii, colours/alpha, border, softness/sigma, clip/fades,
inset offsets and glyph scale. Text cases add real Parley/embedded-Inter runs and
freeze their atlas; those cases check sampling, not shaping correctness. Synthetic
atlas texels have guard space so the tests do not rely on undefined out-of-bounds
GPU texture loads. `generate::seeded` provides a stable SplitMix64 corpus.
The shape follows Vello's `cpu_gpu_differential` target [1]: structured bounded
inputs, two persistent renderer implementations, a per-channel comparison,
and saved replay cases. Rune uses proptest rather than cargo-fuzz. Proptest
shrinks both the vector and its fields, persists failure seeds, and writes the
final minimized GPU failure as `crates/rune-ref/failures/minimized.json`.
`RUNE_REF_FAILURES` overrides that output directory for worker artifact collection.
Move understood cases into `regressions/`; the test replays every JSON there.
CPU metamorphic tests require exact bytes for integer translation, opacity-zero
identity, full-viewport clip identity, and reorder of disjoint clipped groups.
The GPU runs the same four relations. Translation/full clip allow 2 levels;
transparent additions and disjoint order require exact equality. Comparison never
uses an image average that could hide an incorrect edge.
### Measured budget on Apple M4 Pro / Metal
Rust 1.99.0 on an Apple M4 Pro build worker; no windows or screen captures. One successful corpus run contains 128 generated scenes × 8 isolated
primitives, 128 composites, and 16 pinned-font text scenes.
| Primitive | Measured maximum channel delta | Gate |
|---|---:|---:|
| Rounded rect / border / capsule | 1 | 2 |
| Outer shadow | 1 | 2 |
| Glyph, including scaled synthetic atlas | 1 | 2 |
| Inset shadow | 1 | 2 |
| Vertical gradient | 1 | 2 |
| Eight-primitive composite | 2 | 2 |
There are no permitted outliers. One LSB covers rounding around an RGBA8 encoding
boundary; the second covers accumulated blend/encode rounding. This is an
empirical bounded-corpus budget, not a theorem or a cross-vendor certification.
WGSL allows FMA fusion and reassociation [2], and sRGB conversion accuracy adds
another backend-dependent rounding step. Measure Vulkan/D3D12 before claiming
their budget. Never increase the cap to hide a large geometric/texel mismatch.
Also passed: 128 GPU proptest scenes, 128 CPU metamorphic cases, 32 GPU
metamorphic scenes, and the saved glyph regression. The allocation gates passed
for 30 warmed CPU-reference frames and Rune's existing 30-frame streaming runtime
test. These exclude scene construction, shaping/commit and GPU/driver allocations.
## The glyph regression fixes a discontinuity
`regressions/glyph-texel-boundary.json` came from seed 15, primitive 4. Its glyph
starts at x=10.5. At a pixel center x=13.5 the intended local coordinate is 3,
but triangle interpolation can produce a value just below 3. `floor` then loads
column 2. Before the fix, 231 pixels exceeded the 2-level cap, maximum delta 83.
The glyph branch now uses fragment `@builtin(position).xy` for its texel lookup,
which is the rasterizer's pixel center. Both nearest and bilinear glyph sampling
use it. Other primitive formulas and clip interpolation are unchanged. The saved
case and full corpus pass. No existing PNG golden was rewritten. Fractionally
positioned glyphs can intentionally change where the old lookup selected the wrong
texel; existing app-wide snapshot equivalence has not been measured in this pass.
Harness corrections during bring-up: avoid translating the sentinel NO_CLIP
bounds beyond the replay validator's coordinate limit; permit Rune's actual
2048² atlas rather than the README's historical 1024² size. Neither was a
production shader failure. The first compile also caught a mutable-array borrow
in generator setup. All were corrected before the successful runs above.
## A differing pixel names its last contributor
`Frame::new(width, height, true)` enables a primitive-index buffer. A positive
source alpha records the last contributing primitive, so transparent draws do
not erase provenance. `Frame::blame` resolves it to the node ID and source key
(which can be a file:line string supplied by an app). Diff JSON includes the first
outlier's x/y, expected/actual RGBA, node and source. This is top-contributor blame,
not a claim that the top node caused every error under translucent overlays.
```sh
cargo run -p rune-ref --features gpu -- \
--scene crates/rune-ref/regressions/glyph-texel-boundary.json --diff --blame 13,34
```
`--seed N --save scene.json` creates a replay file. Without `--diff`, the CLI
needs no GPU and prints the exact BLAKE3 hash. Invalid scene geometry/atlas data
is rejected before upload. The optional provenance buffer is allocated once;
repeated rendering allocates nothing.
## Exact gates are scripts, with Linux instruction measurement pending
```sh
sh scripts/check-reference.sh --gpu
```
That runs exact CPU hashes/metamorphic properties, both allocation gates, GPU
differential fuzzing and saved regressions. The normal command without `--gpu`
still runs the production runtime allocator test, but does not initialize wgpu.
`benches/instructions.rs` uses gungraun 0.20.0 [3,4] to count one fixed warmed
reference frame. Scene/frame allocation and destruction sit outside the measured
function. `scripts/check-reference-instructions.sh save` records a named base;
`check` compares the candidate, failing above **+0.5% instructions**. It checks
the Rust/Valgrind/runner version manifest and refuses a missing baseline marker.
Run both revisions on the same Linux worker with the same Cargo target directory.
Install the matching `gungraun-runner --version 0.20.0` and Valgrind first.
No Linux worker was available when this was written, so instruction counts and
the Linux-only benchmark have not been executed. No instruction
number or performance improvement is claimed. These scripts are ready for any Linux runner. The first Linux run must validate the benchmark and save its baseline.
## Sources and remaining verification
1. [Vello fuzz README](https://github.com/linebender/vello/blob/main/fuzz/README.md). Its default permits 2 per channel and 4 outlier pixels;
Rune intentionally permits zero outliers.
2. [WGSL floating-point evaluation](https://www.w3.org/TR/WGSL/#floating-point-evaluation)
and research/14 §3 for FMA/reassociation and tolerance policy.
3. [Gungraun regression guide](https://github.com/gungraun/gungraun/blob/main/docs/src/regressions.md). Version 0.20 uses `Callgrind::soft_limits`.
4. [Gungraun baselines](https://github.com/gungraun/gungraun/blob/main/docs/src/cli_and_env/baselines.md).
5. Rune `shader.wgsl` and `render.rs`; research/12 and /14; PLAN tenet 7 and §6c.
Every Renderer caller supplies target dimensions as the viewport, so fragment
position has the required coordinates. Static glyphs are pixel-snapped, which
keeps their texel choices unchanged. Non-Linux workspace benches skip cleanly; the
instruction-gate script still rejects non-Linux execution.
Remaining: Linux instruction execution, x86/arm CPU hash comparison, Vulkan/D3D12
budget measurement, broader app snapshot comparison, and the new vector kinds.
+86
View File
@@ -0,0 +1,86 @@
# Syntax highlighting in Markdown code fences
How rune-kit colours fenced code, and why it uses hand-written scanners instead of a grammar
engine.
## What it has to do
- Colour the languages chat answers use most: TypeScript/TSX/JavaScript, JSON, Rust, Swift,
CSS, HTML, shell, SQL and YAML. Anything else stays plain.
- Treat the input as untrusted: model output can be huge or adversarial, so time must be linear
in the source with no backtracking, and work per block must be capped.
- Stream without layout shift: a fence grows a line at a time, and colouring must not move a
glyph.
- Build everywhere Rune builds, including wasm and iOS, without adding much to binaries.
## Options
**syntect** (Sublime Text grammars). The most accurate of the three for many languages, but
it ships a serialized grammar set (hundreds of KB to a few MB, depending on the languages kept),
loads it lazily at a noticeable startup cost, and its grammars rely on regexes with lookaround,
run by `onig` (C) or `fancy-regex`. Both backtrack, so a crafted line can take super-linear
time. Highlighting is per line with carried state, which fits streaming, but the cost and the
backtracking risk don't fit untrusted chat text.
**tree-sitter**. Real incremental parsing and the best structure, but each language is a
generated C parser (the TypeScript and TSX grammars alone are large), the runtime is C, and
highlighting needs a query file per language. Every target, wasm and iOS included, then needs a
C toolchain, and the size cost is several hundred KB per language. It is the right tool for an
editor, more than a chat transcript needs.
**Hand-written scanners** (chosen). One small byte scanner per language family (C-like, shell,
markup, CSS, SQL, YAML), in the same spirit as the native mermaid renderer. Each only moves
forward; lookaheads are bounded (a regex literal at most 512 bytes) or skip bytes the scanner
would otherwise visit; embedded code (template `${}`, JSX `{}`, `<script>`, `$()`) nests at most
three deep. Pure Rust, no dependencies, no data files, wasm-friendly. The cost is semantic
precision: it recognises tokens, not grammar, so an unusual construct can colour slightly
wrong. For reading an answer that is an acceptable trade, and the scanners err toward leaving
text plain.
## Decisions
- **Colour only.** Spans set a brush and nothing else: no weight, italic or size, so shaping
sees the same runs and glyph positions are identical with and without colour. A unit test
lays out the same code plain, coloured and part-coloured and compares every glyph quad.
- **Streaming.** An unclosed fence colours its complete lines only; the line still arriving
draws plain and takes its colour when its newline arrives.
- **Caps.** The first 32 KiB of a block (cut at a line end) and at most 8192 coloured runs;
the rest draws plain. Results are cached per (language, source) for the last 32 blocks on
the thread, the same bound as the parse cache.
- **Colours.** Eight token kinds from `MarkdownStyle`. Defaults use fixed familiar hues (violet
keywords, green strings, orange numbers, teal types, blue functions, rose properties) at one
lightness and chroma derived from the theme's text colour, and the theme's muted and faint
text for punctuation and comments. Theme status colours were tried as the hue source, but
they vary too much between themes (one theme's "info" is magenta) to keep kinds apart.
- **No new feature flag.** The scanners are about a thousand lines of plain Rust with no
dependencies, so they live under `markdown`.
- **`Block` keeps its shape.** Each code block's language travels beside the parsed blocks
rather than in a new `Block` variant, so apps that match on `Block::Code` keep working.
## 2026-11: Desktop's own lexers, translated
OpenCode Desktop doesn't highlight with a TextMate engine. Its diffs, file views and Markdown use
Pierre's Highlights (`@pierre/highlights`, Apache-2.0): 80 hand-written lexers, written in
WebAssembly Text and shipped as one 183 KB module, whose tokens are Zed capture names that
Desktop's theme maps to its `syntax-*` colours. The scanners above covered 20 of those
languages and coloured 82.9% of their samples' bytes as Desktop does.
Options, measured on a Windows x64 desktop shared with other builds, with one sample per language, repeated to 1,000+ lines,
optimised builds; sizes are the growth of a minimal binary:
| Option | Languages | Native size | Web (wasm32, gzip) | ms per 1,000 lines | Same colours as Desktop |
|---|---:|---:|---:|---:|---:|
| Hand-written scanners (before) | 20 | +81 KB | +25 KB | 0.1-0.4 | 82.9% |
| Highlights, translated to Rust (chosen) | 80 | +429 KB | +175 KB | 0.16-0.37 quiet, 0.56-0.70 loaded (V8 runs the module at 0.24 and 0.58-0.72) | 100% (tokens identical) |
| Highlights in an interpreter (wasmi) | 80 | about +2.9 MB | the browser's own WebAssembly | 8.4 | 100% |
| syntect, 75 Sublime grammars | 75 | +2.46 MB | - | 147 (warm) | TextMate scopes; see Shiki |
| Shiki's grammars (TextMate, JS or Oniguruma) | 80 | 3.9 MB of grammar JSON (487 KB gzip) + engine | - | 41-49 | 81.0% |
| tree-sitter, 8 grammars (parse only) | 8 | +16.2 MB | needs a C toolchain | 2.4-15.4 | different grammar and queries |
The choice: `crates/rune-highlights` translates `highlights.wasm` to Rust in `build.rs`
(`codegen/translate.rs`, about 550 lines over `wasmparser`), so the same lexers run natively on
every target with no runtime and no compiling on users' machines. Its tokens are identical to
the module's in V8 on all 80 samples and 3,360 fuzzed sources (mutations, deep nesting, random
text); 200,000-deep nesting runs on a 1 MiB main-thread stack. A block streaming in uses
Highlights' stream mode: 0.044 ms per new line at 5,000 lines, against 1.5 ms to lex the whole
block again. A trap (a bug in the lexers) draws the code plain instead of panicking.
+81
View File
@@ -0,0 +1,81 @@
# 26. Native materials in step with Metal frames
Reader: the next agent changing `system_material/macos.rs`, frame pacing on macOS, or the
present path. Re-run the lab below before changing either.
`El::system_material` puts an `NSGlassEffectView` (macOS 26+) or an `NSVisualEffectView`
popover behind a transparent window's CAMetalLayer and sets its frame, corner radius and
alpha in the same `CATransaction` as the frame's drawable (`presentsWithTransaction`). This
note records what that buys, what it costs, and the one thing still limiting it.
## How it was measured
`examples/glass-card` with `GLASS_CARD_PATTERN=black` flies a card over a black window and
draws a 2 px magenta border on the card's edge. Over black the glass shows as a flat dark
grey, so each frame gives two edges: Rune's (magenta) and the native view's (grey). The
screen was captured at 120 fps (ScreenCaptureKit, 1x) on a MacBook Pro with a 120 Hz display
running macOS 27. For each frame with the card moving at least 2 px, a script measured how far
grey extends past the magenta edge, or black shows inside it, on rows and columns through the
card. The left and top edges are clear of the fading text and button, so they are the ones
counted. Cadence comes from `GLASS_CARD_TRACE` traces of the card window, as gaps between
submissions in display periods.
## Results
| Path | Moving frames with the glass edge off by more than 4 px | Frames one period after the last |
|---|---|---|
| Glass, synced (default) | 26 of 1421 (1.8%) | 70% |
| Glass, synced, main thread busy 8 ms a frame | 0 of 325 | about 60 Hz (the busy loop alone takes 8 ms) |
| Popover (`legacy`), synced | 2 of 538 (0.4%) | 98% |
| Glass, `unsynced` (views committed before the present) | 178 of 605 (29%) | 78% |
| Fallback fill (`off`) | n/a | 99% |
Seven synced Glass runs ranged from 0 to 4% of moving frames, clustered in a few flights.
- **The synced glass never lags.** Every miss is the glass one frame ahead: Rune's content
shows frame N while the glass is already at N+1. At the card's speed that is 10 to 14 px.
Unsynced shows the same one-frame gap on about a third of moving frames.
- **A busy main thread doesn't break the sync.** It delays the views and the drawable
equally, because both wait for the same transaction.
- **Glass is expensive to move.** `NSGlassEffectView` runs a SwiftUI graph on every frame or
radius change: `layoutSubtreeIfNeeded` takes 0.8 to 2 ms a frame (the radius makes no
difference). Skipping that call only moves the cost into the transaction commit. The popover
view costs about 0.2 ms.
- **That cost, not the transaction, drops Glass below 120 Hz.** With the fallback fill a
frame takes about 0.5 ms of CPU, and with Glass about 3.2 ms (median). The display link
refuses a tick that comes less than half a period after the last present (`permits` in
`display_link.rs`), so any frame over 4.2 ms skips the next one. In one trace, 192 of the
219 frames over that line were followed by a skip. Skipped frames let the CPU clock down,
which makes the next glass layout slower.
## Getting Glass to 120 Hz (not landed)
Two experiments, env-gated and since removed, show what it would take:
| Pacing change | Frames one period after the last | Glass edge off by more than 4 px |
|---|---|---|
| Drop the half-period check | 97% | 11 of 313 (3.5%) |
| Measure the half period from the last frame's start, not its present | 98.5% | 97 of 555 (17%) |
| Frame start, and wait for the GPU before presenting | 99% | 11 of 703 (1.6%) |
Running at full rate without the GPU wait makes the misses much more common. wgpu's
`presentsWithTransaction` path only waits until the command buffer is scheduled
(`waitUntilScheduled`), so a drawable can join the transaction before it has rendered. The
WindowServer then applies the views and keeps showing the previous drawable for a frame.
Waiting for the GPU before the present (`device.poll(Wait)`) closes most of that gap. With the
stock pacer, Glass runs near 80 fps; there the wait made no clear difference to the misses
(0 and 21 frames in two runs) and lowered cadence to 62%.
The pacing change affects every app's frame timing, so it belongs in its own change. The
existing pacer test (`late_frames_and_idle_restarts_cannot_catch_up_in_a_burst`) expects a
present-based check in one case, where a callback arrives 2 ms after an early present.
## Notes for the implementation
- `presentsWithTransaction` is read when wgpu acquires a drawable, so the first frame that
finds a material is dropped and redrawn once the flag is set.
- AppKit builds a glass view's backdrop layers on its first visible frame, so views are made
and parked at zero alpha, never hidden. A hidden one shows unrefracted for a frame when shown.
- The host view is flipped and returns nil from `hitTest:`, so winit's view gets every event.
AppKit can reorder sublayers, so each frame checks that the Metal layer is still above the
host's layer.
+138
View File
@@ -0,0 +1,138 @@
# 27. Editing a long Markdown note
Reader: someone deciding how a notes app should hold a note in Rune, or changing text layout,
text paint or `TextEdit` history. Re-run the bench below before and after changing any of them.
The question: can one multi-line `text_input` hold a whole ~50 KB Markdown note and stay
smooth at 120 Hz (8.3 ms a frame)? It can scroll, move the caret and follow it at any size
measured. It can't type at 50 KB: every keystroke reshapes the whole note, at 12 ms.
## How it was measured
`crates/rune/examples/long_note.rs`, headless, no window:
```
cargo run --profile perf -p rune --example long_note --features frame-profile -- \
--sizes 5,50,200 --samples 60 --gpu [--blocks]
```
The note is generated from fictional words: headings, wrapping paragraphs, lists, task lists,
quotes and fenced code, at 8.9 KB (142 lines), 54 KB (861 lines) and 207 KB (3,289 lines). It
sits in a 760 × 900 pt scroll viewport at 2x, in 15 pt type. Each case times an input and the
frame it commits, in thread CPU. `--gpu` adds the renderer's encode and submit time on a
headless GPU, which stayed under 0.5 ms (p95) in every case. `--blocks` splits the note at blank
lines into one keyed field per block (about 1,600 fields at 200 KB). Numbers below are medians
(p95 in brackets) in ms, from an M4 Pro Mac mini.
## Results: one field for the whole note
| Case | 5 KB | 50 KB | 200 KB |
|---|---|---|---|
| Type a character (start, middle or end) | 2.2 (2.5) | 12.0 (12.2) | 45.7 (46.6) |
| Return | 2.0 (2.1) | 12.0 (12.3) | 46.2 (49.2) |
| Backspace | 2.0 (2.1) | 12.0 (12.4) | 46.4 (48.9) |
| Paste 2 KB | 2.4 (2.5) | 12.5 (12.8) | 47.7 (50.0) |
| Cmd+Z right after the paste | 0.12 (0.14) | 0.32 (0.35) | 0.74 (0.81) |
| Scroll frame | 0.10 (0.13) | 0.10 (0.12) | 0.09 (0.12) |
| Down arrow | 0.12 (0.15) | 0.19 (0.23) | 0.41 (0.46) |
| Cmd+Down to the end | 0.17 (0.22) | 0.23 (0.26) | 0.51 (0.56) |
| Click to place the caret | 0.11 (0.18) | 0.16 (0.18) | 0.39 (0.42) |
Caret-follow held at every size: across 120 Down presses the caret never left the viewport,
which moved at most one line (22 pt) per press; Cmd+Down landed at the end with the caret in
view; 30 of 30 clicks placed the caret where clicked without moving the viewport.
Memory (heap growth over the process before the note opened, MB):
| | 5 KB | 50 KB | 200 KB |
|---|---|---|---|
| Opened | 5.5 | 9.8 | 24.8 |
| After 50 typed characters | 10.3 | 18.8 | 45.6 |
| After 200 | 10.5 | 18.8 | 45.6 |
| Undo steps kept of 100 small pastes | 53 | 9 | 2 |
## Why typing costs what it does
`TextSystem::layout_blocks` caches a layout under a hash of the field's whole text, so an edit
anywhere misses and Parley lays out the whole string again: font selection, text analysis,
HarfRust shaping and line breaking, about 0.22 ms per KB. A profile of 200 KB typing puts all
of the frame there. Cmd+Z right after an edit is cheap because the previous text's layout is
still in the cache (stale layouts stay for two commits, and longer within a 64 KB budget).
Memory follows from the same thing: a whole-note layout is roughly 90 bytes of heap per byte
of text, and while typing two are alive, the current one and the previous one.
Undo depth comes from `TextEdit`'s history: up to 128 steps within 1 MB, where each step holds
a full copy of the text before and after it. A long note fits only a few steps: about
1 MB ÷ (2 × note size). Typing coalesces a run of keystrokes into one step, so a step is a burst
of typing or one paste, but a 200 KB note still forgets everything before the last two.
## What was fixed: paint walked every line
Before this change, painting a text walked every glyph of its layout, looking each up in the
atlas, and only then dropped the glyphs outside the clip. A 200 KB note in a scroll view spent
5.4 ms of every frame on that, scrolling included. Paint now binary-searches the layout's lines
for the clip's band (with two ems of slack for ink past a line box) and walks only those. The
per-glyph clip test still decides what draws, so the output is unchanged: the glyph counts
match before and after in every case.
| Case, median ms | 5 KB | 50 KB | 200 KB |
|---|---|---|---|
| Scroll frame | 0.27 → 0.10 | 1.46 → 0.10 | 5.45 → 0.09 |
| Down arrow | 0.30 → 0.12 | 1.58 → 0.19 | 5.81 → 0.41 |
| Click | 0.31 → 0.11 | 1.57 → 0.16 | 5.78 → 0.39 |
| Type a character | 2.44 → 2.19 | 13.68 → 11.96 | 51.46 → 45.72 |
The test `a_long_scrolled_text_paints_only_its_visible_lines` checks that a glyph on a text's
last line isn't rasterized until it's scrolled into view.
## Results: one field per block (`--blocks`)
| Case | 5 KB | 50 KB | 200 KB |
|---|---|---|---|
| Type a character (middle) | 0.31 (0.36) | 0.82 (0.96) | 2.6 (3.2) |
| Type at the start | 0.22 (0.28) | 0.69 (0.87) | 3.0 (4.4) |
| Return | 0.27 (0.34) | 0.77 (0.96) | 2.5 (2.8) |
| Backspace | 0.28 (0.29) | 0.66 (0.82) | 2.4 (3.0) |
| Paste 2 KB | 0.70 (0.75) | 1.38 (1.58) | 3.4 (4.5) |
| Scroll frame | 0.10 (0.12) | 0.12 (0.17) | 0.18 (0.22) |
| Heap after 200 typed characters, MB | 7.2 | 11.7 | 27.1 |
| Undo steps kept of 100 | 100 | 100 | 100 |
An edit reshapes one block (0.03 to 0.6 ms). What's left grows with the number of blocks:
building, diffing and laying out every field each commit, about 2.2 ms at 1,600 fields.
## What's left, and a plan
- **Typing in one field: whole-note reshape (12 ms at 50 KB).** Lay out each hard paragraph
(text between `\n`s) as its own Parley layout, cached under that paragraph's text, spans and
style, and stack them under a composite layout with a line index. An edit then reshapes one
paragraph. It's a large change: caret geometry, hit-testing, selection boxes, decorations,
pills, block indents, elision and the glyph walk all take one `parley::Layout` today, and all
would go through the composite.
- **Undo depth.** Store each step as its changed byte range (the removed and inserted text)
plus the small mark, block and soft-break lists, so a step costs its edit, not the note;
check an undo still applies by length and a hash rather than comparing full copies.
- **Per-commit work proportional to the note** (about 0.3 ms at 200 KB, outside text shaping):
the whole text is hashed for the layout cache and copied into the view on each rebuild.
Small; it goes away with paragraph layouts.
- **Many blocks.** `El::virtualize` would make a block-per-field note's commits independent of
its length, but in a first try a focused field inside a virtualized stack reported its caret
(`ElementInfo::caret`, which caret-follow also uses) away from its row, and a field revealed
with `Tx::scroll_into_view` didn't take typing headlessly. That needs its own look before a
notes app relies on it.
## Advice for a notes app
- Up to about 10 KB, one field per note is fine: 2 ms a keystroke.
- Beyond that, use one keyed field per Markdown block (paragraph, list, quote, code fence). That
stays under 1 ms a keystroke at 50 KB and under 4 ms at 200 KB, keeps a full undo history per
block, and holds a few MB instead of two whole-note layouts.
- Moving between blocks becomes the app's job: Up and Down at a block's first or last line move
focus to the neighbouring block; Backspace at a block's start merges it into the one above;
Return splits it; a selection across blocks and an undo spanning blocks need an app-level
model.
- Handle Return. In a multi-line `text_input`, plain Return in a paragraph submits (to
`on_submit`, or the default button when there is none), while Shift+Return and Option+Return
type a newline (as does plain Return inside a rich list, quote or code block). An editor
gives each field an `on_submit` that splits the block or inserts `"\n"`.
+113
View File
@@ -0,0 +1,113 @@
# 28. Resizing a window with a long Markdown note
Reader: someone changing text layout or its cache, or deciding how a notes app shows a long
note. Re-run the bench below before and after changing either.
The question: can a window showing a long Markdown note (`rune_kit::Markdown` in a scroll
view) be resized at 120 Hz (8.3 ms a frame)? Before this change it couldn't at 50 KB: every
frame of a live resize shaped every wrapped text of the note again, 16 ms a frame. Now a width
change only re-breaks lines, and a frame costs 4.6 ms.
## How it was measured
`crates/rune-kit/examples/markdown_resize.rs`, headless, no window:
```
cargo run --profile perf -p rune-kit --example markdown_resize --features markdown,frame-profile -- \
--sizes 5,50,200 [--memo]
```
The note is generated from fictional words: headings, wrapping paragraphs with bold, italic,
inline code and links, bullet, numbered and task lists, quotes and fenced code, at 5.4 KB
(71 texts), 52 KB (645 texts, 1,364 layout nodes) and 202 KB (2,501 texts, 5,381 nodes). Only
32 texts are on screen at a time. The window is 900 pt tall at 2x; `resize` steps its width
from 900 to 600 pt and back in 1 pt steps, one frame per step (600 frames), as a live resize
does. Each frame is timed in thread CPU, split into the runtime's phases. Numbers are medians
(p95 in brackets) in ms from an M4 Pro Mac mini, the before and after builds run back to back.
## Results
| Resize frame | 5 KB | 50 KB | 200 KB |
|---|---|---|---|
| CPU, before | 1.57 (1.67) | 16.1 (17.1) | 70.6 (75.4) |
| CPU, after | 0.55 (0.59) | 4.6 (5.1) | 23.2 (24.0) |
| Text (shaping and line breaking), before | 1.08 | 11.9 | 49.2 |
| Text, after | 0.06 | 0.70 | 3.2 |
| Texts shaped per frame, before → after | 42 → 0 | 401 → 0 | 1,565 → 0 |
| Texts re-broken per frame, after | 42 | 401 | 1,565 |
Scrolling (0.24 ms a frame at 50 KB) and opening the note (17 ms at 50 KB, 70 ms at 200 KB,
one shaping per distinct text) are unchanged.
## What was slow
`TextSystem` caches each layout under a hash of its text, spans, style, scale *and wrap width*.
A width it hasn't seen misses, and Parley lays the text out from scratch: font selection,
text analysis, HarfRust shaping, then line breaking. During a live resize every width is new,
so every frame shaped every wrapped text in the note, on screen or not (the column has to know
each block's height for its scroll extent).
Only line breaking depends on the width. Parley's `LayoutBuilder::build` shapes; a built
`Layout` can be broken again with `break_all_lines` (or Rune's block-indent and pill breaker)
and aligned again, which clears its old lines and leaves the shaped runs alone. Alignment and
justification are stored per line, so nothing from an earlier width carries over.
## What changed
The cache key splits in two. A *shape key* hashes what shaping reads: text, spans, style,
scale, `wrap_anywhere` and pills. The *layout key* adds the width, alignment and block indents. Beside the
layout cache, an index maps each shape key to the layout key of the latest layout of that
shaping. A miss on the layout key whose shape key has a cached layout clones that layout
(a flat copy of its glyph and run arrays) and breaks and aligns the copy at the new width,
about 2 µs for a paragraph against about 30 µs to shape it.
- Memory: the index holds no layouts, only keys, and drops an entry when its layout is
evicted. Layouts are kept and evicted exactly as before (one per text and width, two commits
and then the stale-text budget), so a resize holds what it held before.
- Secure text still bypasses the shared cache entirely: it neither reads nor feeds the index.
- Everything that reads a layout (carets, hit testing, selection boxes, decorations and span
rings, visible-line culling, `max_lines` and elision, alignment and justification) gets a
layout with the same lines and glyph positions as one built from scratch at that width. The
test `a_new_width_rebreaks_without_shaping_and_matches_a_fresh_layout` checks this bit for
bit across eight widths (zero and unbounded included) for spans of every kind, all four
alignments, `wrap_anywhere`, right-to-left and justified right-to-left text, CJK, emoji and math fallbacks,
monospace tabs, indented blocks and pills, and that none of it shapes.
- Measuring: Taffy measures a wrapped text at its definite width only (`w_full` texts in a
column are stretched, so min- and max-content aren't asked for), and the final pass asks for
the same width, so each wrapped text costs one re-break per resize frame and nothing else.
A `max_lines` text's trial cuts go through the same cache, so a cut tried at the last width
is re-broken rather than shaped.
## What's left
At 50 KB a resize frame is now 4.6 ms, comfortably inside 120 Hz. What it spends, all of it in
proportion to the note's 1,364 layout nodes, since none of the note is virtualized:
| 50 KB resize frame, after | ms |
|---|---|
| View (building the Markdown tree again) | 0.78 |
| Flattening the tree into layout nodes, and the pass after layout | about 0.85 |
| Taffy layout | about 1.15 |
| Text line breaking | 0.70 |
| Apply (mounting, layout animation targets) | 0.81 |
| Paint | 0.22 |
At 200 KB the same split is 23 ms: view 3.4, Taffy 5.8, line breaking 3.2, apply 4.8, the
rest flattening. A sample of it puts 11% in moving node structs (flatten and apply) and 5% in
hashing whole texts again in Taffy's measure callback, which asks about three times per text
per layout.
A plan, most to least effect:
1. **Virtualize long Markdown.** Build and lay out only the blocks near the viewport, keeping
measured heights per width for the rest (`El::virtualize`). That makes a resize frame
independent of note length. It needs an estimate for blocks never measured at the current
width, which a cheap re-break of their cached shapes can now supply.
2. **Skip the view on a viewport-only commit.** A resize rebuilds the view and flattens it even
when nothing the view read changed. Reusing the last flattened tree when no view read the
viewport or a layout would save view and flatten: about 1.6 ms at 50 KB, 8 ms at 200 KB.
3. **Hash each text once per commit.** Flattening already hashes every text for Taffy's cache;
passing that hash to the measure callback and the final pass saves the repeats, about 5%.
An app can take some of the view cost today by memoizing the note's subtree on its revision
(`rune::memo`, `--memo` in the bench): view drops from 0.78 to 0.54 ms at 50 KB.
+25
View File
@@ -0,0 +1,25 @@
# Scroll-frame CPU
Fixtures: 1,000 plain rows, a long Markdown document, 40 sticky sidebar sections,
and a 1,000-row growth timeline receiving a row every 12 frames. Each drives
480 wheel deltas at virtual 120 Hz, reversing halfway, with the pointer inside.
Metric: median thread CPU from wheel dispatch through draw-list construction;
GPU submission is excluded. One warmup and nine alternating before/after pairs.
Build instructions are in `scripts/bench-ui.py`; run with
`python3 scripts/bench-ui.py --frame-cpu --scroll --out target/scroll --runs 9`.
Kept: skip unchanged default hover targets and gate interaction lookups on styles.
Improvement is the median paired ratio; CPU columns are medians in milliseconds.
| Fixture | Before | After | Improvement |
| --- | ---: | ---: | ---: |
| Plain list | 0.401 | 0.306 | 22.1% |
| Markdown | 0.187 | 0.177 | 4.30% |
| Sticky sidebar | 0.333 | 0.276 | 18.9% |
| Growth timeline | 0.473 | 0.416 | 13.2% |
Next proposals:
- Retain scroll-subtree geometry and conservatively cull branches.
- Commit and measure only changed growth rows, retaining keyed row structure.
- Index hover/press candidates instead of scanning every node twice per frame.
+140
View File
@@ -0,0 +1,140 @@
# Overlay GPU cost: Rune vs hand-written Metal
Fixture: `crates/rune/examples/overlay_hud_cost.rs`, a 360×80 overlay whose compositor clears
the drawable in one render pass at 120 Hz with an empty Rune view. The comparison is
`research/overlay-cpu/metal_hud.swift`, the same panel cleared by hand from a CVDisplayLink
callback with one command buffer per frame.
Metric: retired instructions per frame for the whole process (`proc_pid_rusage`), because the
test Mac moves between a fast and a slow CPU mode that changes CPU time by 2× but not
instruction counts. CPU percentages are from paired slow-mode runs. Runs alternate (3 or 4
rounds), 8 to 10 s each after a 2 s warmup, on a real window.
## Per frame
| | Rune | Rune with the wgpu patches | Metal |
| --- | ---: | ---: | ---: |
| Command buffers committed | 6 | 2 | 1 |
| Completion handlers | 2 | 1 | 0 |
| Render encoders, presents | 1, 1 | 1, 1 | 1, 1 |
| Heap allocations | 65.1 | 55.1 | – |
| Kinstructions | ~1,555 | ~1,118 | ~850 |
| Process CPU | ~19.5% | ~16.0% | ~11.2% |
Rune submits once per frame and, with no writes, its staging submits and recycles nothing.
The six command buffers are wgpu's:
1. `(wgpu internal) Transit`: wgpu-core's barrier buffer for the submitted command buffer. Empty on Metal.
2. `(wgpu internal) Pre Pass`: the pass's barriers. Empty on Metal.
3. The render pass.
4. The surface texture's transition to PRESENT at `Queue::submit`, which gets the fence signal and a completion handler. Empty on Metal.
5. `Queue::present` → `prepare_surface_texture_for_present` submits again with a second signal and handler. That's a PRESENT→PRESENT barrier: no backend lists PRESENT among the usages that skip barriers.
6. wgpu-hal's present, which presents the drawable from a command buffer of its own.
wgpu 30.0.1 is the latest release, and wgpu's main branch has the same code, so an upgrade
doesn't help. Two small patches do (`research/overlay-cpu/*.patch`, against 30.0.1):
- `wgpu-core-present-skip.patch`: when the texture needs no clear and every pending transition
is from PRESENT, return without a submission. This affects every backend: Vulkan also leaves
PRESENT out of its ordered usages.
- `wgpu-hal-metal-lazy-command-buffer.patch`: a Metal command encoder makes its MTLCommandBuffer
on first use, so an encoding that records nothing commits nothing. The submit signals on the
last non-empty buffer. This is a prototype. Before sending it upstream, `raw_command_buffer()`
should make the buffer for `as_hal` callers, and the strict-event-sync wait value should be
read at `begin_encoding`.
With the Metal HUD made to do what wgpu does, the gap is driver work per command buffer:
| Metal HUD shape | Kinstructions |
| --- | ---: |
| 1 command buffer, present on it | ~848 |
| Present from its own command buffer, 1 handler (the patched shape) | ~929 |
| 2 extra empty buffers, split present, 1 handler | ~1,105 |
| 4 extra empty buffers, split present, 2 handlers (wgpu's shape) | ~1,213 |
## By thread (8 s, both processes at once, ms)
| | Driver and dispatch threads | Present thread | Main | Display link | Total |
| --- | ---: | ---: | ---: | ---: | ---: |
| Rune, patched | 650 | 205 | 183 | 21 | 1,059 |
| Metal | 468 | – | 3 | 296 | 767 |
- Driver threads: `_submitAvailableCommandBuffers` (271 ms), completion notifications
(~100 ms), drawable presents (~50 ms). This cost scales with command buffers and handlers.
- Present thread: wgpu-hal into Metal 134 ms (commits, present), wgpu-core 43 ms, Rune ~1 ms.
- Main thread, standalone 10 s profile, patched:
- `acquire` 154 ms, of which `nextDrawable` 125 ms. Metal's display link spends the same on
`nextDrawable`.
- Rune's own work is about 105 ms: `frame::step` 46 (`step_motion` 34, the empty view's
`build` 23), `about_to_wait` 22 (pointer observe 7), `render_frame` 18, `submit_and_present`
11 (the hand-off send 9), `PresentWorker::wait` 5, occlusion check 3.
- wgpu's `create_view` on the surface texture is 10 ms.
- The app's own work, which Metal does on its display link, is not in these runs.
## Writes
A frame that writes a buffer costs about 310 kinstructions more, whether it uses `Queue::write_buffer`
or `Frame::write_buffer`. Either way wgpu-core records the copy in a command buffer of its own
(`PendingWrites`, or the encoder's own buffer ahead of the pass), with a blit encoder.
| Writes per frame | Queue | `Frame::write_buffer` |
| --- | ---: | ---: |
| 0 | ~1,558 | – |
| 1 | ~1,863 | ~1,881 |
| 4 | ~1,966 | ~1,918 |
Staging maps its chunk once per frame however many writes share it, so each extra write costs
~12 kinstructions against ~35 for a queue write.
## Rune's own frame
Each change stacks on the one before. The fixture also prints the main thread's instructions
(`thread_selfcounts`), which isolate Rune's share from the driver threads. Medians of 6
alternating rounds, 10 s each, no writes, unpatched wgpu:
| Build | Main kinstructions | Main µs | Process kinstructions | Present thread ms/s |
| --- | ---: | ---: | ---: | ---: |
| Before | 161.9 | 149 | 1,395 | 17.0 |
| Claim the display link's frame before waiting on the present thread | 153.3 | 134 | 1,398 | 16.4 |
| Skip the pointer sample when nothing reads it | 148.3 | 127 | 1,388 | 15.5 |
| Read occlusion once a turn | 144.2 | 118 | 1,384 | 15.3 |
| Leave a still runtime alone while only the compositor animates | 139.2 | 102 | 1,371 | 14.9 |
| Skip the staging when nothing is staged | 140.8 | 109 | 1,375 | 13.7 |
- The main thread does 13% fewer instructions. The process total moves by about as much as the
run-to-run spread (±50 kinstructions), because driver threads dominate it.
- A Time Profiler run on the main thread finds `frame_step` and `step_motion` (14 of 117 samples
before) gone once the runtime rests. What's left is `acquire`, mostly `nextDrawable`.
- Allocations stay at 65.1 a frame: they are wgpu's and Metal's, not Rune's.
## Writes with immediates
A compositor that asks for `Features::IMMEDIATES` gets the adapter's immediate size (4 KB on
Metal), so it can hand a frame's uniforms to `RenderPass::set_immediates` instead of writing a
buffer. Three writes a frame, same rounds:
| Path | Process kinstructions | Main kinstructions | Allocations | Command buffers, blit encoders |
| --- | ---: | ---: | ---: | ---: |
| `Queue::write_buffer`, before | 1,708 | 277 | 82.1 | 7, 1 |
| `Queue::write_buffer`, after | 1,696 | 258 | 82.1 | 7, 1 |
| `Frame::write_buffer`, before | 1,679 | 166 | 85.1 | 7, 1 |
| `Frame::write_buffer`, after | 1,650 | 144 | 85.2 | 7, 1 |
| Immediates | 1,405 | 148 | 71.1 | 6, 0 |
Immediates cost what a frame with no writes costs: no copy, so no command buffer and blit
encoder for it. A uniform ring in `MAPPABLE_PRIMARY_BUFFERS` memory was not tried. It would also
skip the copy, but it needs its own fencing per frame in flight, and it isn't available on every
backend.
## What's left
- Ship the wgpu fix. A `[patch]` in Rune's workspace doesn't reach apps that pin Rune. A git
dependency on a wgpu fork would, but every app that names `wgpu` itself would have to follow
it. Upstreaming both patches is the clean route.
- Without wgpu changes, Rune could acquire drawables from the CAMetalLayer itself, wrap each
texture with `create_texture_from_hal`, and present on its own command buffer after the frame's.
That would remove buffers 4 to 6 and one handler, about 110 kinstructions of driver work by the
Metal HUD's measure plus wgpu-core's present path. In exchange, Rune would bypass wgpu's
surface on macOS.
- Rune's main thread is now about 10% of the process's instructions, most of it `acquire`. The
rest of the cost is wgpu's command buffers and Metal's driver threads.
+264
View File
@@ -0,0 +1,264 @@
# 31. Where a frame goes: Taffy, Parley and Rune
Reader: someone deciding whether to replace Taffy or Parley with engines built for Rune, or
looking for the next big CPU or memory win in a frame. Re-run the bench below before and after
a change to layout, text or the commit path.
The question: how much of a real frame's CPU time, allocations and heap belong to Taffy, to
Parley and its font stack (Fontique, HarfRust, Swash, ICU), and to Rune's own code?
The short answer: outside of shaping, Rune's own code is most of every frame. Taffy is 5% to
16% of a frame and Parley 0.4% to 20%, so the most either replacement could save there is
under 0.9 ms a frame. Shaping is the one place Parley dominates: 73% of opening a long note and 98% of
typing in one. Both cases come from shaping text whose shape is already known, and a cache
above Parley could avoid that without replacing it.
## How it was measured
`crates/rune-kit/examples/layout_text_cost`, headless, no window:
```
CARGO_PROFILE_PERF_DEBUG=limited cargo build --profile perf -p rune-kit \
--example layout_text_cost --features markdown,frame-profile
target/perf/examples/layout_text_cost # timing
target/perf/examples/layout_text_cost --mode sample --repeat 3 --out s.txt # CPU profile
target/perf/examples/layout_text_cost --mode heap --out h.txt # allocation stacks
python3 scripts/cost-attribution.py symbolize s.txt --exe target/perf/examples/layout_text_cost > s.syms
python3 scripts/cost-attribution.py report s.txt s.syms --top 12
```
Each case starts on a fresh runtime, lets it settle, then times its frames:
| Case | What each frame does |
|---|---|
| `stack` | A settings-like column of 60 cards of switches, badges and buttons, not virtualized (5,283 layout nodes, 2,040 texts). Each frame flips one switch. |
| `stack-same` | The same column. Each frame re-runs the view with nothing changed. |
| `list` | 10,000 rows of three texts under `virtual_rows` (278 nodes mounted). Each frame scrolls two rows. |
| `edit` | One multi-line `text_input` holding a 50 KB note. Each frame types a character. |
| `md-resize` | A 50 KB Markdown note in a scroll view (1,268 nodes, 614 texts). Each frame steps the width 1 pt, 900 → 600 → 900, as a live resize does. |
| `md-same` | The same note. Each frame re-runs the view with nothing changed. |
| `md-open` | The first frame of a fresh runtime showing the note, so every text is shaped. |
The note is generated from fictional words, like the one in [28](28-resize-rewrap.md).
Three probes ran inside the example, since no system profiler was available on the build
machine:
- **Timing.** Each frame's thread CPU time comes from `rune/frame-profile`, split into its
phases. Five runs alternated case order (forward, reverse, forward, …). The tables give the
median of the five runs' medians and p95s. Most runs landed within 5% of that median. One
run each of `stack-same` and `md-resize` was 19% and 24% slower, likely because of the other
jobs on the machine.
- **CPU sampling.** A thread suspends the main thread every 200 µs, walks its frame pointers
and resumes it. 208,000 samples over three repeats of every case. A sample belongs to the
innermost frame that isn't std, `alloc`, `core`, hashbrown and the like. Time in `malloc`
or `free` goes to *Allocator*, which also records who called it. In the tables, allocator
time counts toward its caller's bucket. Symbols come from `atos -i`, so inlined frames
count too.
- **Heap.** A counting global allocator records the stack of every allocation during the
measured frames, plus what is still live once the case settles.
Machine: an M4 Pro Mac mini, `--profile perf`. It was running other build jobs at the time,
with a load average around 15.
Buckets:
- **Taffy:** `taffy::*`, including `Style` comparisons and drops in flatten. It doesn't
include the text measure callbacks Taffy calls.
- **Parley:** `parley`, `parley_engine`, HarfRust, read-fonts and skrifa (shaping), ICU and
bidi (text analysis), Fontique (font queries and fallback) and Swash (glyph raster). It also
includes Rune's clone of a shaped `Layout` before re-breaking it (see below), which exists
only because Parley breaks a layout in place.
- **Rune:** the `rune` crate and `rune_motion`.
- **View:** `rune_kit`, Markdown and the bench's own view code.
- **Instr.:** the frame-profile clock. Only builds with that feature pay for it.
## Results
### CPU time per frame
The ms columns are thread CPU, median (p95). The bucket shares come from the samples. The
last three columns are the frame with that bucket's share removed: the most a free Taffy, a
free Parley, or both could save.
| Case | ms | Rune | View | Taffy | Parley | Instr. | Taffy = 0 | Parley = 0 | Both = 0 |
|---|---|---|---|---|---|---|---|---|---|
| stack | 10.2 (13.6) | 86.8% | 7.2% | 5.6% | 0.4% | 0.0% | 9.6 | 10.2 | 9.6 |
| stack-same | 9.9 (11.7) | 86.6% | 7.8% | 5.1% | 0.5% | 0.1% | 9.4 | 9.9 | 9.4 |
| list (mean) | 0.44 | 72.7% | 2.9% | 5.3% | 18.2% | 0.5% | 0.41 | 0.36 | 0.33 |
| edit | 15.5 (17.1) | 1.6% | – | 0.1% | 97.8% | 0.1% | 15.5 | 0.34 | 0.33 |
| md-resize | 4.56 (5.87) | 53.7% | 6.4% | 15.6% | 19.6% | 4.5% | 3.85 | 3.67 | 2.96 |
| md-same | 1.98 (2.49) | 80.1% | 12.9% | 4.8% | 2.2% | 0.1% | 1.88 | 1.94 | 1.84 |
| md-open (one frame) | 18.3 (21.3) | 19.1% | 1.5% | 5.0% | 72.8% | 1.2% | 17.4 | 5.0 | 4.1 |
`list` frames come in two kinds. Most mount nothing new (median 0.15 ms). Every few frames,
new rows mount and get shaped (p95 1.16 ms). The samples cover all frames, so the shares are
for the mean.
The allocator takes 11% of `stack`, 12% of `md-resize`, 10% of `md-same` and under 6%
elsewhere. Most of that is Rune's: 9.4 of the 11 points in `stack`. In `md-resize` it splits
4.9 points Rune, 5.2 Parley and the layout clone, 1.6 Taffy.
The Parley column broken down:
| Case | Shaping (HarfRust) | Analysis (ICU, bidi) | Fontique | Line breaking | Layout building and glyph iteration | Clone before re-break | Swash raster |
|---|---|---|---|---|---|---|---|
| edit | 82.8% | 8.6% | 2.5% | 2.5% | 1.3% | – | – |
| md-open | 50.2% | 6.3% | 4.5% | 2.5% | 3.0% | – | 4.4% |
| md-resize | 0.5% | – | – | 7.6% | 2.4% | 3.8% + 2.8% allocator | – |
| list | 7.8% | 0.7% | 1.0% | 0.2% | 8.0% | – | – |
In `list`, "layout building" is mostly paint walking Parley's lines and glyph runs to place
glyphs.
What the time-mode phases say:
| Case, ms | View | Commit | Layout | of which Text | Apply | Paint |
|---|---|---|---|---|---|---|
| stack | 2.41 | 8.54 | 0.058 | 0 | 2.92 | 1.09 |
| stack-same | 2.42 | 8.37 | 0.012 | 0 | 2.84 | 1.06 |
| edit | 0.01 | 15.36 | 15.25 | 15.21 | 0.06 | 0.12 |
| md-resize | 0.64 | 4.20 | 1.99 | 0.79 | 0.82 | 0.26 |
| md-same | 0.57 | 1.67 | 0.002 | 0 | 0.40 | 0.24 |
| md-open | 0.64 | 16.93 | 14.92 | 13.25 | 0.43 | 1.26 |
Commit includes view, layout and apply. Layout includes text.
### Allocations per frame
Calls to the allocator per frame, by the owner of the allocating code, and bytes allocated
per frame:
| Case | Total | Rune | View | Taffy | Parley | Bytes |
|---|---|---|---|---|---|---|
| stack | 45,657 | 39,293 (86%) | 6,290 | 74 | 0 | 30 MB |
| stack-same | 45,586 | 39,293 (86%) | 6,290 | 3 | 0 | 30 MB |
| list (mean) | 1,350 | 1,153 | 91 | 41 | 65 | 1.4 MB |
| edit | 1,176 | 87 | 1 | 14 | 1,074 (91%) | 3.8 MB |
| md-resize | 21,198 | 8,503 (40%) | 2,641 | 4,956 (23%) | 5,099 (24%) | 12 MB |
| md-same | 10,744 | 8,100 | 2,641 | 3 | 0 | 7 MB |
| md-open | 31,264 | 14,270 | 2,641 | 5,669 | 8,684 | 35 MB |
The biggest single sources:
- `flatten::node_path`: 4 allocations per node per frame. That's 21,130 of the 45,657 in
`stack`, and 5,070 in each Markdown case.
- `El::child` growing children `Vec`s: 4,742 allocations but 16 MB a frame in `stack`. An `El`
is large, so a few children take kilobytes, and each doubling copies them.
- `flatten` itself (one per node), `El::key`, and the label `String`s.
- Taffy's flexbox: `generate_anonymous_flex_items` and the `FlexLine` vectors allocate on every
layout of a flex container. That's 4,170 allocations per frame in `md-resize`.
- Parley's line breaker clones `BreakerState`, which owns a vector, once per line: 1,030 of
`edit`'s 1,176 allocations.
- The layout clone before re-breaking copies seven vectors per text: 3,540 allocations and
2.2 MB per frame in `md-resize`.
### Heap
What is live once a case settles, by owner (MB = 10⁶ bytes):
| Case | Live | Rune | Taffy | Parley | Other |
|---|---|---|---|---|---|
| stack (5,283 nodes, 2,040 texts) | 57.9 MB | 41.3 | 11.0 | 5.4 | 0.2 |
| list (278 nodes, 165 texts, 10,000 rows) | 11.4 MB | 8.0 | 0.7 | 0.8 | 1.9 (row data) |
| edit (1 field, 50 KB) | 19.2 MB | 5.3 | 0.02 | 13.8 | 0.1 |
| md-resize (1,268 nodes, 614 texts) | 20.8 MB | 13.3 | 2.8 | 3.9 | 0.9 (Markdown) |
Per node and per text:
| Owner | stack | md-resize |
|---|---|---|
| Taffy's node (`Style`, layout cache) | 2.1 KB / node | 2.2 KB / node |
| Rune's flattened node | 2.4 KB / node | 2.5 KB / node |
| `rune_motion` store and scene | 3.5 KB / node | 3.3 KB / node |
| Parley layout | 2.6 KB / text (short labels) | 6.3 KB / text, 76 bytes per byte of text |
One 50 KB field holds 13.8 MB of Parley, about 270 bytes per byte of text. 7.8 MB of that is
`ShapedText`'s reserved runs, clusters and glyphs, and 4.3 MB is HarfRust's buffer. That buffer
grew to fit the whole text and stays that size. The glyph atlas's CPU copy is a fixed 4.2 MB
per runtime and counts toward Rune in every row.
## Text: how much is re-shaping text that was shaped before
- **Resize (`md-resize`): none.** Since [28](28-resize-rewrap.md), a width change re-breaks
395 texts a frame and shapes none. The rewrap costs 0.8 ms of text time, which is Parley's
line breaking, cloning the shaped layout before breaking it (7.1% with its allocations), and
hashing (below). A word-shape cache would save nothing here.
- **Typing (`edit`): almost all of it.** Each keystroke shapes the whole 50 KB note as one
text: 15.2 ms, 83% of it in HarfRust. The note has 7,201 words and 772 distinct ones, and
one word changed. Splitting the field into paragraphs ([27](27-long-note-editing.md))
removes nearly all of it, with no word cache needed.
- **Opening (`md-open`): most of it, if the cache is per word.** The 404 texts shaped hold the
same 7,201 words, of which 772 are distinct. A cache keyed by (word, style, font) would
shape 11% of them and could cut the 9.2 ms of HarfRust in this frame by up to about 8 ms.
That is an upper bound. The note's generator draws from a small vocabulary, so real prose
repeats words less. Shaping a word alone also loses context across word boundaries, which
some scripts and fonts need, so a cache like this needs a fallback for them. The list's
10,000 rows have 149,438 words and 10,050 distinct ones (6.7%).
## Layout: how much is re-solving unchanged subtrees
- **When one switch flips (`stack`), almost none.** Taffy spends 0.058 ms laying out 5,283
nodes, and 0.012 ms when nothing changed. Its cache already skips the clean subtrees. In
`stack`, Taffy's 5.6% is spent in flatten, not in layout: comparing and dropping `Style`
values to decide whether a node's style changed. Most of that goes to the grid fields Rune
never sets (`Style::eq` 1.0%, the grid track and placement comparisons 1.6%).
- **During a resize (`md-resize`), there are no unchanged subtrees to skip in Taffy's
terms.** Every node's available width changes, so every cache entry misses. Taffy's own
work is 15.6% of the frame (0.71 ms, about 0.56 µs per node), including about 4,170
allocations for flex items and lines. Some subtrees end up the same size anyway (code blocks
and short lines that fit at both widths). Counting those would need instrumentation inside
the runtime, which this pass didn't add. Skipping all of Taffy's work is still at most 0.71
ms.
- **Measure calls.** `text_hash` runs once per text in flatten, once in `measure_view`, and on
each Taffy measure call. Its time in each place puts Taffy's measure calls at about four per
text per frame during a resize. Each call hashes the whole text with SipHash before it
checks the cache.
## The biggest costs
Rune's own code:
1. **Re-running and re-committing a view that didn't change.** `stack-same` costs 9.9 ms a
frame for 5,283 nodes: 1.9 µs, 8.6 allocations and 5.7 KB allocated per node. The time
splits into apply (27%), flatten (15%), paint (11%) and view building (10%, plus 6% in kit
components and 7% in the allocator). The allocations are `node_path` (4 per node) and
children `Vec`s of large `El`s. In `stack`, `rune_motion`'s `AnimationStore::set_raw` and
its OKLab conversion take 8%.
2. **Hashing whole texts on every measure.** `text_hash` (SipHash over the full text, its
spans and style) is 11.2% of `md-resize`, about 0.5 ms, and 4.4% of `stack`. Flatten
already computes the same hash. Passing it into measure would remove most of the cost.
3. **Cloning a shaped layout to re-break it:** 7.1% of `md-resize`, with 3,540 allocations a
frame.
4. **Heap per node:** about 2.5 KB in the flattened node and 3.3 to 3.5 KB in the motion store
and scene, against Taffy's 2.1 KB.
5. Instrumentation: frame-profile's clock costs 4.5% of `md-resize`, because a timing scope
opens on every re-break. Builds without the feature don't pay it, so a production
`md-resize` frame is closer to 4.35 ms than 4.56 ms.
Dependencies:
1. **HarfRust shaping** when a text is shaped: 50% of `md-open` and 83% of `edit`. A new
engine would still have to shape. What would make this cheaper is shaping less (paragraphs
for editing, maybe words for opening), and that works on top of Parley.
2. **Taffy during a resize:** 15.6%, 0.71 ms, and a quarter of the frame's allocations.
Elsewhere it's 5% or less, mostly `Style` comparison in flatten.
3. **Parley memory:** about 270 bytes of heap per byte of text in one large field, and 76 in
a Markdown note.
4. **Parley's per-line `BreakerState` clone:** 1,030 allocations per keystroke at 50 KB.
## What headless leaves out
- The GPU side: encoding, glyph and image uploads, submit, and waiting for presentation. Glyph
rasterizing on the CPU (Swash) is included. [30](30-overlay-gpu-cost.md) and
[29](29-scroll-frame-cpu.md) cover the GPU side.
- Delivery of real window events: winit, IME and the OS text input services, and the resize
handshake with the window server.
- Other threads. Rune does all of this work on the main thread, so a single-thread profile is
complete for these phases, but it says nothing about contention with other threads.
- Cache warmth in a real app. Each case runs on a fresh runtime in a process that has already
run the earlier cases. A real app's caches may be colder (after other windows) or warmer.
- Startup. The system font list is built once per process, before any timed frame.
`md-open` does include font matching and fallback queries (Fontique, 4.5%).
- The probes' own cost. The sampler stops the main thread for a few microseconds per sample,
and heap mode makes every allocation slower. Timing runs used neither probe.
+459
View File
@@ -0,0 +1,459 @@
# 32. Layout and text engines: verdicts and frame-cost plan
Reader: someone deciding whether Rune should build its own layout engine (replacing Taffy) or
text engine (replacing Parley), or choosing the next frame-time and memory wins in `rune`,
`rune-motion` and `rune-kit`. Re-run `layout_text_cost` ([31](31-layout-text-cost.md)) and
`scripts/motion-audit` before and after each phase below.
The question: from first principles, should Rune replace Taffy and Parley with purpose-built
engines, and how should it cut frame CPU, per-frame allocations and retained heap from here?
The short answer: **keep both Taffy and Parley.** Outside text shaping, Taffy is 5% to 16% of
a frame and Parley is 0.4% to 20% ([31](31-layout-text-cost.md)); replacing both with free,
zero-byte engines would leave a 5,283-node settings commit at 9.6 ms (still over the 8.3 ms
120 Hz budget) and a 50 KB Markdown resize at 2.96 ms. Where Parley dominates (98% of typing
in a 50 KB `text_input` at 15.5 ms, and 73% of cold-opening a 50 KB note at 18.3 ms), it is
spending 83% and 50% of the frame inside HarfRust OpenType shaping, which an own engine would
still run unless it shapes less text. Fixes inside Rune's own commit, motion, style and
caching layers can bring typing to ~1 ms, live resize to ~1.4 ms, and steady 5,283-node
commits to ~3.5 ms (< 0.8 ms with `memo`), while cutting per-node heap roughly in half. Two
focused layers *are* worth building from scratch now: a compact `BoxStyle` on `El` (replacing
inline `taffy::Style`) and a multi-paragraph composite `TextLayout` above `parley::Layout`.
---
## 1. Verdict on an own layout engine: keep Taffy, delete the mirror's waste
### Evidence
- **Solver CPU is tiny.** In `layout_text_cost` ([31](31-layout-text-cost.md)), Taffy's layout
pass (`Phase::Layout`) takes **0.058 ms** for 5,283 nodes when one switch flips (`stack`)
and **0.012 ms** when nothing changed (`stack-same`). Taffy's 5.6% sample share in `stack`
(0.57 ms) is spent in `flatten`, comparing and dropping `taffy::Style` values whose CSS Grid
`Vec` fields Rune never populates (2.6% alone in `Style::eq` and grid track comparisons).
- **Even a full cache-miss resize has a 0.71 ms ceiling.** Stepping a 50 KB Markdown window's
width by 1 pt (`md-resize`, 1,268 nodes) invalidates every width constraint in Taffy. Taffy
takes 15.6% of the frame (**0.71 ms**, 0.56 µs/node, 4,170 flex-line allocations). A magic
zero-cost solver would take `md-resize` from 4.56 ms to 3.85 ms; skipping Rune's redundant
view/flatten rebuild on resize saves twice as much (~1.5 ms) in ~120 lines.
- **Taffy is the smallest of the three per-node heap owners.** Live heap per node in `stack`
is **2.1 KB** in Taffy, **2.4 KB** in Rune's flattened `Node`, and **3.5 KB** in
`rune_motion`. An earlier branch (`t710-taffy-adapter`) replaced `TaffyTree` with a dense
364 B/node store (−71% layout-tree heap on 500 rows) and left commit time flat, confirming
that commit CPU sits in Rune's tree walk, string paths, style comparisons and `Scene`
retargeting rather than Taffy's slot maps.
- **Clean seam, real CSS parity risk.** `El.style` is `pub(crate)` (`crates/rune/src/el.rs:782`)
and `taffy` is never re-exported, touching 12 files in `crates/rune`. Rune uses flex
(`row`/`col`, grow/shrink/basis, wrap, gap, min/max, padding/border/margin, `aspect_ratio`),
`Position::Absolute` (under `Position::Relative` by default), and one grid helper,
`equal_columns(n)` (`repeat(n, 1fr)` on row 1). Even on that subset, views and `rune-kit`'s
components depend on CSS flexbox specifics: automatic minimum size (`min_h(0.0)` on flexing
scroll views), `flex_shrink: 0.0` defaults, `max-content` horizontal scroll rewrites
(`runtime/flatten.rs:312-334`), shrink negotiation under min/max bounds, and `flex_wrap`
with gaps. Re-owning those (~2.5 to 3.5 kLOC plus differential fuzzing) carries real
layout-regression risk for ≤ 0.71 ms of upside.
### Measurable trigger to revisit an own layout solver
Build a Rune-native single-pass layout solver over `Vec<Node>` only if, **after Phases 1 and 3
land**, one of these holds on `layout_text_cost` (`--profile perf`, paired medians):
1. `taffy::*` exceeds **30% of frame CPU and ≥ 1.0 ms** on a target 120 Hz workload (such as
resizing or mutating a 5,000-node unvirtualized table or canvas).
2. Taffy's rootward dirty propagation (`mark_dirty` walking to the root on any leaf edit)
spends **≥ 0.5 ms** on localized edits inside fixed-size or scrolling containers where
Flutter-style relayout boundaries would stop at the container.
3. Multi-pass layout commits (`aspect_fit`, `fit_anchored`, or `virtual_list` height-bound
retries) still run ≥ 2 full-tree solves on **> 5% of commits** in real traces after PR 4c.
---
## 2. Verdict on an own text engine: keep Parley + HarfRust, cache at paragraph granularity
### Evidence
- **Outside shaping, Parley is ≤ 0.6 ms.** On steady commits (`stack`, `md-same`), the entire
text stack (Parley, `parley_engine`, HarfRust, Fontique, ICU4X, Swash) is 0.4% to 2.2% of
the frame (≤ 0.05 ms). On `md-resize` (4.56 ms), Parley's bucket is 19.6% (0.89 ms), but a
third of that (6.6%, 0.30 ms, 3,540 allocations) is Rune's own `Layout::clone` before
re-breaking; Parley's actual line breaking of 395 wrapped texts takes **0.35 ms** (0.88 µs
per paragraph).
- **Typing is slow because Rune hashes and reshapes the whole 50 KB field per keystroke.**
Typing one character in a 50 KB `text_input` (`edit`) takes **15.5 ms** (97.8% Parley, of
which 82.8% is HarfRust shaping and 8.6% is ICU/bidi analysis) and holds **13.8 MB** of
Parley heap (7.8 MB across two whole-note `ShapedText` buffers plus a 4.3 MB HarfRust
`UnicodeBuffer` high-water mark). Splitting the same 50 KB note into keyed blocks
([27](27-long-note-editing.md) `--blocks`) already drops typing to **0.82 ms** (reshaping
one block takes 0.03 to 0.6 ms). Any custom text engine that shapes a 50 KB buffer as one
unit would still spend ~12 ms in HarfRust and fail 120 Hz.
- **Cold open is bounded by unique-word shaping and unvirtualized offscreen blocks.** `md-open`
shapes 404 texts in **18.3 ms** (9.2 ms HarfRust, 1.15 ms ICU/bidi, 0.82 ms Fontique, 0.81 ms
Swash). Note that `layout_text_cost`'s generator draws from a 50-word list (`main.rs:43-47`:
772 distinct tokens across 7,201 words, an 89% repeat rate), whereas real prose and code
repeat ~40% to 55% of words. Meanwhile, only 32 of the 614 texts in `md-open` are on screen
([28](28-resize-rewrap.md)); virtualizing Markdown blocks avoids shaping ~90% of offscreen
blocks on open without touching the shaper.
- **High parity cost for replacing Parley.** Owning text below `parley` means re-implementing
UAX #9 bidi reordering and visual-order cursor movement (`Cursor`/`Selection`), UAX #14/29
line and grapheme segmentation, fallback itemization across ZWJ emoji and combining marks,
IME preedit caret/underline geometry, and CoreText vertical-metric parity
(`core_text_tests.rs`). Switching to per-OS native shapers (CoreText/DirectWrite) would give
up Rune's cross-platform layout determinism and still leave web/Linux needing a Rust stack.
### Measurable trigger to revisit a lower text seam (`parley_engine` breaker)
Never build an own OpenType shaper, bidi engine or OS-divergent shaper. Revisit replacing
`parley::Layout` with Rune's own line breaker and word/run shape cache directly over
`parley_engine 0.12` (`Analyzer` + `Shaper` + `FontSelector`) only if, **after Phases 1, 2
and 4 land**:
1. Cold open of **unvirtualized** UI or document views (≥ 300 uncached texts on screen at once)
still spends **≥ 6.0 ms in HarfRust**, **and** the Phase 0 spike on real English/code files
shows **≥ 50% word-cache hits and ≥ 2.0× net wall-clock speedup** after per-word overhead
and `unsafe-to-break` fallbacks; **or**
2. Workarounds around `parley::Layout` (inline-box `cursor_from_point`, `cursor_geometry`
`inline_min_coord`, `2n+1` pill re-breaks, space-widened tabs) need > 300 new lines of
wrapper code and upstream fixes in Parley are blocked.
---
## 3. Five root causes verified in the code
Checking the attribution numbers in [31](31-layout-text-cost.md) against `crates/rune` and
`crates/rune-motion` turned up five specific mechanisms that explain the big buckets:
1. **`window_tree` walks every node and expands every `memo` even when no `virtualize` exists
(`crates/rune/src/runtime.rs:3543-3645`, `el.rs:1613-1618`).**
`window_tree` only mutates elements with `virtual_estimate.is_some()`, yet `build_tree`
runs it unconditionally over all 5,283 nodes of `stack` and 1,268 nodes of `md-*`. Worse,
line 3544 calls `el.expand_memo()` while `MemoCache` still holds a second `Rc<Shared>`
reference, forcing `Rc::unwrap_or_clone` to **deep-clone every cached memo subtree's
`Vec<El>`** before `flatten` consumes it. `window_tree` and `flatten` each call
`node_path` (`format!`), and `flatten.rs:229` calls `path.clone()`, accounting for all **4
`node_path` allocations per node** (21,130 of 45,657 allocations in `stack`).
2. **`Scene::record_track` marks every node `dirty = true` on no-op `animate` calls, and
`apply` eagerly allocates 4 to 8 `AnimationStore` tracks on static nodes
(`crates/rune-motion/src/scene.rs:870-940, 1065-1085`, `store.rs:466, 940`,
`crates/rune/src/runtime.rs:3400, 4200-4298`).**
- Each lane in `AnimationStore` takes ~108 B (~160 B with `Vec` capacity; `Layer` is 64 B).
On commit 1, `apply` calls `set_or_anim(P_FILL, Color::TRANSPARENT)` on all 5,283 nodes
and `P_TEXT` on all 2,040 text/icon nodes, even though `Runtime::color` (`runtime.rs:3401`)
ignores `AnimationStore` whenever `!is_animating`. On commit 2, `Scene::animate` calls
`ensure_prop` *before* checking `target == base`, creating 4-lane `RADIUS` and 1-lane
`OPACITY` tracks on every static box (`Scene::insert` also creates `PRESENCE` on
`Mount::Initial`). Together, static nodes carry ~14 unused lanes and ~5 tracks, explaining
`rune_motion`'s **3.4 to 3.5 KB/node** (18.5 MB in `stack`).
- `AnimationStore::animate` runs `Color::write_lanes` (`3 × powf(2.4)` + `3 × cbrt()` for
OKLab) *before* checking whether the target changed (~10,000+ conversions/frame in `stack`).
- For the ~4,750 offscreen nodes in `stack`, `quiet = out_of_sight` calls `Scene::set` →
`set_raw`, which never checks if lanes already sit at `values` and pushes 9,500
`TrackId`s into `set_touched`. For onscreen nodes, `record_track` sets `dirty = true`
even when `animate_raw` was a no-op, forcing `Scene::present_dirty` to recompute all
5,283 `Presented` structs on every commit, including `stack-same` and `md-same`.
3. **`Cx<S>` has no `viewport` getter, and `Runtime` already computes `state_unchanged`
(`crates/rune/src/runtime.rs:270-386, 2299`).**
A view function can only depend on layout geometry through `Cx::caret` (`caret_watch`),
`Cx::layout*` (`layout_seen`), or `virtuals`. During `md-resize`, `state_unchanged` is
already `true`, `scale` is unchanged, and `virtuals` is empty, so re-running `view`
(0.64 ms) and `flatten` (~0.85 ms, 8,503 allocations) rebuilds the exact same `Node` and
Taffy trees every 1 pt step.
4. **`Layout::clone` during resize (7.1% of `md-resize`, 3,540 allocs, 2.2 MB/frame) comes
from `Rc` aliasing with `self.nodes` and stale widths in `self.layouts`
(`crates/rune/src/text.rs:1629-1639`, `runtime.rs:3711-3722`).**
`parley::Layout` stores shaped runs and broken lines in one struct (`LayoutData`). Cloning
happens because `self.nodes` (from the prior commit) and `self.layouts[prev_width]` both
hold `Rc<Layout<Ink>>` (`strong_count == 2`) while `compute_layout` runs. Clearing
`old.text_layout` on surviving (non-exiting) nodes before `compute_layout` and moving an
entry with `used < g` from `prev_key` to `key` drops `Rc::strong_count` to 1, letting
`Rc::make_mut` re-break `&mut Layout<Ink>` in place with zero allocations.
5. **Hidden Parley setup work in `layout_blocks_inner` (`crates/rune/src/text.rs:1602, 1763,
1855-1875`).**
`lcx.ranged_builder` resolves `TextStyle::default()` (triggering an unused Fontique query
for `"sans-serif"`) and splits overlapping style ranges, even though `el.rs:1013`
(`flatten_spans`) already flattens spans into contiguous non-overlapping runs suited to
`lcx.style_run_builder`. And when a fallback font's `trak` table differs from the primary
font's, line 1874 rebuilds and reshapes the entire layout a second time.
---
## 4. Ranked improvements
Baselines from [31](31-layout-text-cost.md) (50 KB, `--profile perf`, M4 Pro): `edit` 15.5 ms
(19.2 MB heap), `md-open` 18.3 ms, `stack` 10.2 ms (45,657 allocs, 57.9 MB heap), `stack-same`
9.9 ms, `md-resize` 4.56 ms / 4.35 ms without `frame-profile` (21,198 allocs, 20.8 MB heap),
`md-same` 1.98 ms, `list` 0.44 ms mean (0.15 ms median). Savings note where items overlap on
the same workload.
| Rank | Change | Expected CPU & alloc/heap impact | Size | Risk |
|---:|---|---|---|---|
| **1** | **Per-paragraph composite `TextLayout` + range-delta undo** (`text/composite.rs`, `edit/history.rs`, ~12 `Layout<Ink>` readers): split multi-paragraph text at `\n` into independently cached `Rc<parley::Layout<Ink>>` slices under a `(byte_start, y_top, line_start)` prefix index; store `TextEdit` undo steps as byte-range diffs. | **`edit`: −14.3 to −14.7 ms** (`15.5 → ~0.8–1.2 ms`); **−9 to −10 MB heap** in `edit` (caps HarfRust buffer to 1 paragraph, drops dual 50 KB `ShapedText` copies); `edit` allocs `1,176 → < 80`; keeps 100/100 undo steps at 200 KB. | ~900 LOC | Medium (UAX #9 bidi is paragraph-scoped so `\n` split is exact; work is routing readers cleanly). |
| **2** | **Lazy `Scene`/`AnimationStore` tracks, no-op `dirty` fix, and sRGB pre-check** (`rune-motion/src/scene.rs`, `store.rs`, `runtime/apply.rs`): leave `dirty = false` on unchanged `animate`; no-op `set_raw` when settled at target; create `PRESENCE`/`RADIUS`/`OPACITY`/`P_FILL`/`P_TEXT` tracks only when values differ from rest; compare `Color` floats before OKLab `powf`/`cbrt`. | **`stack` / `stack-same`: −2.3 to −2.8 ms** (`apply` `2.92 → ~0.4 ms`, removes 8% `set_raw`+OKLab and 5,283-node `present_dirty`). **`md-resize`: −0.55 ms**. **`md-same`: −0.32 ms**. Heap: **−14 to −16 MB in `stack`** (`3.5 → ~0.5 KB/node`), **−3.5 MB in `md-resize`**. | ~260 LOC | Low (`scripts/motion-audit` + retarget velocity tests gate exact behavior). |
| **3** | **`has_virtual` subtree bit + retained `(NodeId, Segment)` `PathTable` (`Rc<str>`)** (`runtime/path_table.rs`, `flatten.rs`, `el.rs`, `memo.rs`): propagate `has_virtual: bool` on `El`/`Shared` to skip `window_tree` (and stop pre-flatten `memo` deep-clones) when no virtual list is under a node; intern `(parent_id, key_or_index) → (NodeId, Rc<str>, LayoutEntry)` across commits. | **`stack` / `stack-same`: −1.8 to −2.4 ms**. **`md-resize` / `md-same`: −0.35 to −0.50 ms**. **`md-open`: −0.5 ms**. Allocs: **−21,130/frame in `stack`**, **−5,070/frame in `md-*`**, while keeping `&str` deref for all ~100 `.path` readers. | ~300 LOC | Low (`--tree` and `key_diagnostics` verify identical paths). |
| **4** | **Viewport-relayout fast path (skip `view` + `flatten` when `state_unchanged`)** (`runtime.rs`): on `relayout` with `state_unchanged && scale_unchanged && virtuals.is_empty()`, update `root_id`'s `style.size` on `self.layout` and run `compute_layout` + `place` + text re-break on `self.nodes`; fall back to `measure_view` only if `layout_reads_moved()` or `caret_moved()` fires. | **`md-resize`: −1.35 to −1.55 ms** (skips 0.64 ms `view` and ~0.85 ms `flatten`; overlaps with #3 on `md-resize`). Allocs: **−11,140/frame** (−5 MB/frame) in `md-resize`. | ~120 LOC | Low (`Cx` exposes no viewport; read/caret fallback preserves reactive views). |
| **5** | **Single `shape_key` hash per `TextSpec` with fast non-SipHash mixer** (`text/hash.rs`, `el.rs`, `flatten.rs`, `text_layout.rs`): compute `shape_key: u64` once on `TextSpec` (invalidated only by `apply_case`/`conceal`) and pass it through Taffy `measure` (~4×/text) and final text layout instead of SipHashing ~6×/frame. | **`md-resize`: −0.38 to −0.50 ms** (11.2% → < 0.5%). **`stack` / `stack-same`: −0.40 to −0.45 ms** (4.4%). **`md-open`: −0.25 ms**. | ~100 LOC | Very low. |
| **6** | **In-place `Layout` re-break via `Rc::make_mut` (remove `Layout::clone`)** (`text.rs`, `runtime.rs`): drop `old.text_layout` on non-exiting nodes before `compute_layout` and move `used < g` cache entries from `prev_key` to `key` so `Rc::make_mut` re-breaks in place with zero copies. | **`md-resize`: −0.28 to −0.33 ms** (7.1% of frame). Allocs: **−3,540/frame and −2.2 MB/frame** in `md-resize`; halves Parley resize cache memory. | ~80 LOC | Low (`rewrap_tests` and `secure_text` `strong_count` tests cover edge cases). |
| **7** | **Compact `BoxStyle` (~88 B `Copy`) + `Cold<T>` split on `El`/`Node` + `subtree_end` paint culling** (`el/style.rs`, `runtime/node.rs`, `runtime/paint.rs`): replace inline `taffy::Style` on `El` with `BoxStyle` (converting to `taffy::Style` only on style change, dropping unused `content_size`/`block_layout` features); box cold handler/scroll/motion/visual groups via `Cold<T>`; store `subtree_end: u32` on `Node` to skip offscreen scroll subtrees in O(1) during `paint`. | **`stack` / `stack-same`: −2.0 to −2.8 ms** (kills Taffy's 0.57 ms `Style` compare/drop in `flatten`, cuts 16 MB/frame `El::child` realloc copies ~5×, drops `paint` `1.09 → ~0.3 ms` on 88% offscreen cards). **`md-same`: −0.4 to −0.6 ms**. Heap: **−9 to −11 MB in `stack`** (`Node` `2.4 → ~0.6 KB/node`). | ~600 LOC | Low–Medium (mechanical layout/cold refactor; `BoxStyle` covers 100% of `El` builders). |
| **8** | **Flattened subtree reuse for `memo`** (`memo.rs`, `flatten.rs`, `runtime.rs`): once #3 stops `window_tree` from expanding memos, reuse the prior commit's flattened `Node` slice (rebasing parent/context indices) and Taffy `NodeId` subtree on a `memo` hit, skipping `flatten` and clean interior `apply`. | **Memoized `stack` / real app views: `9.9 ms → < 0.8 ms`** on 1-card flip; **`md-same --memo`: `1.98 → < 0.25 ms`**. Scales commit cost with changed subtrees instead of mounted nodes. | ~350 LOC | Medium (must replay `Cx` reads and rebase Taffy leaf context indices accurately). |
| **9** | **`ResolvedStyle` cache + `style_run_builder` + single-build `trak`** (`text/resolved.rs`, `text.rs`): cache family stacks, features, variations and `trak` by `(TextStyle, collection_gen)`; switch `ranged_builder` to `style_run_builder`; reuse `LayoutContext` on secure text; pre-resolve fallback `trak` / update run spacing instead of double-shaping on mismatch. | **`md-open`: −1.5 to −2.5 ms** (and −40% to −50% on mixed-script/emoji text that currently double-shapes). **`list` mounting p95: −15%**. Allocs: **−3,500+ in `md-open`**. | ~280 LOC | Low (`core_text_tests.rs` verifies metrics and tracking). |
| **10** | **Fix `El::virtualize` caret/reveal + virtualize `rune_kit::Markdown` blocks** (`virtual_list.rs`, `runtime/caret.rs`, `rune-kit/src/markdown.rs`): fix virtualized `ElementInfo::caret` and `scroll_into_view` headless typing ([27](27-long-note-editing.md)); virtualize top-level Markdown blocks with re-break height estimates while keeping `markdown/find.rs` and `virtual_selection` working. | **`md-open` (50 KB): −11 to −13 ms** (`18.3 → ~4.5–6.0 ms`, and bounds 200 KB open at ~6 ms instead of 70 ms). **200 KB `md-resize`: `23.2 → < 2.0 ms`**. Heap: **−12 MB** on 50 KB Markdown. | ~450 LOC | Medium (offscreen height estimates until lazily broken; selection/find integration). |
| **11** | **Single-pass `aspect_fit` leaf measure & subtree-scoped `fit_anchored`** (`runtime/flatten.rs`, `runtime/anchor.rs`): compute `aspect_fit` inside Taffy's leaf measure closure where childless; run overflowing `anchored_fit` re-layout on `overlay_id` instead of `root_id` (an `above` overlay never moves siblings). | **−30% to −66% of layout CPU** on media grids and overflowing popovers/menus (1 root solve instead of 2 or 3). | ~130 LOC | Low. |
| **12** | **(Conditional, gated on Spike & Trigger) Word/run shape cache over `parley_engine`** (`text/`): cache shaped runs for space-delimited words without cross-space GSUB/GPOS, falling back to full runs for complex scripts. | **`md-open` (only if unvirtualized): −3 to −4.5 ms on real prose** (up to −8 ms on 50-word bench). Unneeded for notes once #10 virtualizes `md-open`. | 3–4.5 kLOC | High (see §5). |
### Projected scorecard after Phases 1 to 4 (keeping Taffy and Parley)
| Case (50 KB) | Today (ms) | Free Taffy + Parley today (ms) | Projected Phases 1–4 (ms) | Live heap today → projected |
|---|---:|---:|---:|---|
| `edit` | 15.5 | 0.33 *(if shaping = 0)* | **~0.9–1.2** | 19.2 MB → **~9.5 MB** |
| `md-open` | 18.3 | 4.1 | **~15.0** *(unvirt.)* / **~4.5–6.0** *(virt.)* | 20.8 MB → **~14 MB** *(~7 MB virt.)* |
| `md-resize` | 4.56 *(4.35 prod)* | 2.96 | **~1.3–1.6** | 20.8 MB → **~14 MB** |
| `md-same` | 1.98 | 1.84 | **~0.6–0.8** *(< 0.25 with `memo`)* | 20.8 MB → **~14 MB** |
| `stack` | 10.2 | 9.6 | **~3.5–4.5** *(< 0.8 with card `memo`)* | 57.9 MB → **~23–26 MB** |
| `stack-same` | 9.9 | 9.4 | **~3.2–4.0** *(< 0.5 with card `memo`)* | 57.9 MB → **~23–26 MB** |
| `list` (mean) | 0.44 *(0.15 med)* | 0.33 | **~0.28–0.33** *(0.10 med)* | 11.4 MB → **~9.5 MB** |
---
## 5. Where a from-scratch layer is the right choice
### Build from scratch now
1. **`BoxStyle` (~88 B, `Copy`) in `crates/rune/src/el/style.rs` (~350 LOC, zero parity risk).**
`El` currently embeds `taffy::Style` (~400+ B with nine CSS Grid `Vec`s Rune leaves empty),
paying to construct, move in `Vec<El>`, compare (`Style::eq`) and drop it on every node of
every commit. A purpose-built `BoxStyle` stores only Rune's actual box/flex/anchor/columns
fields in ~88 B, compares as plain words in `flatten`, and converts to `taffy::Style` only
when a node's style changed. It eliminates Taffy's 5.6% `stack` overhead today and cleanly
decouples `El` from Taffy if a native solver is ever warranted later.
2. **`ParagraphComposite` multi-paragraph layout in `crates/rune/src/text/composite.rs` (~800 LOC,
low-to-medium parity risk).**
`parley::Layout` is a single-block layout buffer by design. Building a thin composite over
`Vec<ParagraphSlice>` (each holding an `Rc<parley::Layout<Ink>>`, cached by paragraph
`shape_key` and width, indexed by binary search on byte, y and line offsets) solves long-note
editing (`15.5 → ~1 ms`) and halves Parley's editor memory while keeping Parley's exact
shaping, bidi and line-breaking behavior within every paragraph.
### Keep gated behind §1 and §2 triggers (do not build before Phase 4)
3. **Native single-pass flex + anchor solver over `Vec<Node>` and `BoxStyle` (~2.5 to 3.5 kLOC
solver + ~1.2 kLOC differential fuzzer against Taffy; medium-to-high parity risk).**
If a real workload ever trips the §1 trigger, a native solver wins by operating directly on
`Vec<Node>` rather than by running faster flex arithmetic: it writes straight into
`Node.local/target/inset` with one reusable scratch arena (zero per-container `FlexLine`
allocations), enforces relayout boundaries at scroll viewports and fixed-size boxes so leaf
edits stay O(subtree), and folds `aspect_fit`, `equal_columns(n)` and `anchored_fit` into
single-pass sizing rules. Parity risk sits in CSS automatic minimum sizes (`min_h(0.0)`),
`max-content` horizontal scroll sizing, shrink negotiation under min/max clamps, and
`flex_wrap` + `gap`; promotion must require `±0.01 pt` agreement with Taffy on generated
`El` trees and every `rune-kit` story.
4. **Custom line breaker + shaped-word/run cache over `parley_engine 0.12` (~3 to 4.5 kLOC +
~1.5 kLOC RTL/CJK/emoji/CoreText suite; high parity risk).**
If unvirtualized cold-open shaping trips the §2 trigger, dropping `parley::Layout` for
`parley_engine::{Analyzer, Shaper, FontSelector}` separates immutable shaped runs from
lightweight `Vec<LineSlice>` line breaking, turns pills, real tab stops, block indents and
optical `trak` into first-class breaker inputs (deleting five wrapper layers), and enables a
Blink-style space-delimited word cache. Parity risk is high: `parley_engine` 0.12 notes that
line-edge reshaping (`unsafe-to-break`) is still in progress, Blink disables word caching
whenever a font has GSUB/GPOS rules touching space, complex scripts still shape per run, and
Rune would take over bidi visual-order `Cursor`/`Selection` movement and CoreText vertical
metrics parity.
---
## 6. Phases, measurable gates, and the first spike
Several target files (`runtime.rs`, `el.rs`, `text.rs`, `edit.rs`, `markdown.rs`) sit in
`scripts/file-size-exceptions.txt`. Per `AGENTS.md`, any phase touching one extracts that area
into a sibling module first and lowers its exception ceiling in `scripts/file-size.sh`.
### First spike (do this first; ~180 LOC, throwaway, half a day)
The two riskiest assumptions in this plan are (a) that stacking per-`\n` `parley::Layout<Ink>`
slices matches a single multi-paragraph `parley::Layout<Ink>` to the pixel across indents,
pills, RTL and Retina quantization (before refactoring ~12 reader call sites), and (b) whether
a word-shape cache still wins on *real* prose and code once `layout_text_cost`'s 50-word
synthetic vocabulary is replaced.
1. **Paragraph-stacking equivalence + `edit` timing (~100 LOC test/bench):** Split `edit`'s
50 KB string at `\n` into cached `(shape_key, width) → Rc<Layout<Ink>>` slices and stack
their line metrics. Check bit-exact `(glyph.id, x, y)` and line `[block_min_coord,
block_max_coord]` parity against `layout_blocks_inner` across `rewrap_tests.rs` (spans, all
4 alignments, RTL, CJK, emoji, math, indented `Block`s, pills, trailing `\n`, scale 1x/2x),
and time `layout_text_cost --case edit`.
- **Gate:** 0 px discrepancy (or exact quantization rule pinned down) **and** `edit` median
`cpu_ms ≤ 1.2 ms`, live Parley heap `≤ 5.0 MB`.
2. **Real-corpus word-cache ceiling (~80 LOC bench):** Run three real ~50 KB inputs (`PLAN.md`,
`CHANGELOG.md`, `crates/rune/src/runtime.rs`) through `WORDS` token counting and a throwaway
per-word `parley_engine::Shaper` cache vs Parley paragraph shaping.
- **Gate:** If net wall-clock speedup on real Markdown/code is `< 2.0×`, **kill Option 5.4**
(`parley_engine` word-cache breaker) outright and rely on Phase 4b Markdown virtualization
for cold open.
### Phase 1: Commit, resize and motion fast paths (4 PRs, ~550 LOC)
- **PR 1a (`text/hash.rs`, `flatten.rs`, `text_layout.rs`):** Precompute `shape_key: u64` once
on `TextSpec` with a fast mixer (`Fx`) and pass it through `measure` and final layout.
- *Gate:* `md-resize` `cpu_ms` drops `≥ 0.35 ms` (`text_hash` sample `< 1%`, down from 11.2%);
`stack` drops `≥ 0.35 ms`.
- **PR 1b (`text.rs`, `runtime.rs`):** Clear `old.text_layout` on surviving nodes before
`compute_layout` and move `used < g` cache entries across widths so `Rc::make_mut` re-breaks
in place without `Layout::clone`.
- *Gate:* `md-resize` `allocs` drops `≥ 3,400/frame` (`21,198 → ≤ 17,700`) and `cpu_ms` drops
`≥ 0.25 ms`; `rewrap_tests` and `secure_text` `Rc::strong_count` tests pass.
- **PR 1c (`rune-motion/src/scene.rs`, `store.rs`, `runtime/apply.rs` extracted from
`runtime.rs`):** Leave `Scene` node `dirty = false` on unchanged `animate`; no-op `set_raw`
when settled at target; allocate `PRESENCE`/`RADIUS`/`OPACITY`/`P_FILL`/`P_TEXT` tracks
lazily on first change/animation; compare `Color` sRGB floats before OKLab conversion.
- *Gate:* `stack` and `stack-same` `apply_ms` `2.92 → ≤ 0.60 ms` (`cpu_ms ≤ 7.6 ms`), `stack`
live heap `57.9 → ≤ 43 MB` (`rune_motion ≤ 0.7 KB/node`), `scripts/motion-audit` clean.
- **PR 1d (`runtime.rs`):** Relayout-only fast path on `set_viewport` when `state_unchanged &&
scale_unchanged && virtuals.is_empty()`, with fallback to `measure_view` if `layout_reads` or
`caret_watch` moved.
- *Gate:* `md-resize` `cpu_ms ≤ 1.7 ms`, `view_ms = 0`, `allocs ≤ 9,500/frame`.
### Phase 2: Multi-paragraph `TextLayout` and delta undo (3 PRs, ~950 LOC)
- **PR 2a (`text/composite.rs` extracted from `text.rs`, `edit.rs`, `links.rs`,
`selectable.rs`):** Route all `Layout<Ink>` readers through a single-layout `TextLayout`
wrapper first and lower `text.rs`/`edit.rs` ceilings.
- *Gate:* Zero `layout_text_cost` regression; full text/IME/selection test suite green;
`scripts/file-size.sh` passes with lowered ceilings.
- **PR 2b (`text/composite.rs`):** Enable per-`\n` paragraph slicing, per-paragraph shape/width
caching, and binary-searched line/byte/y lookup inside `TextLayout`.
- *Gate:* `edit` (50 KB) `cpu_ms` `15.5 → ≤ 1.2 ms` (p95 `≤ 1.6 ms`), `shaped = 1` per
keystroke, `edit` live heap `19.2 → ≤ 10.5 MB`; `long_note` 200 KB typing `45.7 → ≤ 1.8 ms`.
- **PR 2c (`edit/history.rs` extracted from `edit.rs`):** Replace full-string undo snapshots
with `(range, removed, inserted_len)` + mark/block deltas.
- *Gate:* `long_note` retains 100/100 undo steps at 50 KB and 200 KB within the 1 MB cap.
### Phase 3: Path table, compact `BoxStyle`/`Node`, and flattened `memo` (4 PRs, ~1,250 LOC)
- **PR 3a (`runtime/path_table.rs`, `flatten.rs`, `el.rs`, `memo.rs`):** Add `has_virtual: bool`
on `El`/`Shared` to skip `window_tree` when false; replace per-frame `node_path` formatting
with a retained `(NodeId, Segment) → (NodeId, Rc<str>, LayoutEntry)` `PathTable`.
- *Gate:* `stack` `allocs` drops `≥ 20,000/frame` (`≤ 25,000`), `md-same` `allocs ≤ 5,700`,
`stack` `cpu_ms` drops `≥ 1.5 ms`.
- **PR 3b (`el/style.rs` extracted from `el.rs`, `flatten.rs`, `Cargo.toml`):** Replace inline
`taffy::Style` on `El` with 88 B `Copy` `BoxStyle`; materialize `taffy::Style` only on style
change; drop unused `content_size` (and `block_layout` if unused).
- *Gate:* `taffy::*` sample share in `stack` `< 0.5%` (down from 5.6%); `El::child` allocated
bytes/frame drop `≥ 50%`.
- **PR 3c (`el.rs`, `runtime/node.rs`, `runtime/paint.rs`):** Group cold handler/scroll/motion/
visual fields into `Cold<T>` on `El` and `Node`; add `subtree_end: u32` on `Node` and skip
offscreen subtrees inside scroll clips during `paint`.
- *Gate:* `stack` live heap `≤ 30 MB` (`Node ≤ 0.7 KB/node`), `paint_ms` `1.09 → ≤ 0.35 ms`,
un-memoized `stack` `cpu_ms ≤ 4.5 ms`.
- **PR 3d (`memo.rs`, `flatten.rs`, `runtime.rs`):** Reuse flattened `Node` slices and retained
Taffy `NodeId` subtrees on `memo` hits, skipping `flatten` and clean interior `apply`.
- *Gate:* Per-card `memo` on `stack` reaches `cpu_ms ≤ 0.8 ms` on a switch flip; `md-same`
with `memo` reaches `≤ 0.30 ms`.
### Phase 4: Cold-open scaling and single-pass layout cleanups (3 PRs, ~850 LOC)
- **PR 4a (`text/resolved.rs`, `text.rs`):** Add `ResolvedStyle` cache, switch `ranged_builder`
to `style_run_builder`, reuse `LayoutContext` (cleared) on secure text, and eliminate the
`trak` mismatch double build.
- *Gate:* `md-open` `cpu_ms` drops `≥ 1.5 ms` and `allocs` drops `≥ 3,500`; mixed-font `trak`
strings shape once (`shaped = 1`).
- **PR 4b (`virtual_list.rs`, `runtime/caret.rs`, `rune-kit/src/markdown/`):** Fix virtualized
field caret reporting and `scroll_into_view` typing; virtualize `Markdown` top-level blocks
above a block threshold while preserving `markdown/find.rs` and `virtual_selection`.
- *Gate:* `md-open` `cpu_ms` `18.3 → ≤ 6.0 ms` at 50 KB and `≤ 6.5 ms` at 200 KB (down from
70 ms); 200 KB `md-resize` `23.2 → ≤ 2.0 ms`.
- **PR 4c (`runtime/flatten.rs`, `runtime/anchor.rs`):** Move childless `aspect_fit` into
Taffy's measure callback and scope `fit_anchored` re-layout to `overlay_id`.
- *Gate:* `aspect_fit` media-grid and overflowing `anchored_fit` menu scenes run 1 root
`compute_layout` pass instead of 2 or 3 (`Phase::Layout` `−40%+` on those scenes).
### Phase 5: Re-measure and check §1 / §2 triggers
Re-run `layout_text_cost` across `--mode time`, `--mode sample` and `--mode heap`. Start the
native flex solver (§5.3) or `parley_engine` line breaker (§5.4) only if a workload still trips
the §1 or §2 trigger.
## Spike results
Throwaway code on branch `spike/engine`: `research/engine-spike/paragraph_stack.rs`, compiled as
a test module of `rune` (it needs `layout_blocks_inner` and `test_alloc`). Timings use
`--profile perf` with `debug-assertions` on for the `rune` crate only, because its lib tests need
them. Parley and HarfRust build at plain perf settings. Modes alternate order on every keystroke
or round, and the numbers are medians.
### Q1: one cached layout per `\n` paragraph, stacked
**Equivalence.** The matrix is every `rewrap_tests` case plus Arabic followed by digits. Each case
is joined as `[case, plain, empty, case]`, `[plain, case]`, and both of those again with a
trailing `\n`. Every join runs at 1x and 2x, at widths 1200, 433.5, 210 and unbounded: 384 runs
per mode. A run is exact when every line box, run, glyph and pill box matches within 1e-3 px.
| Stacking rule | Exact runs |
| --- | --- |
| Each paragraph laid out alone, tops summed | 264 / 384 |
| + every paragraph forced to the text's base direction | 318 / 384 |
| + line tops rounded from the running total, unbounded width aligned to the widest paragraph | **384 / 384** |
The base rule is that each paragraph keeps its `\n`, and every paragraph but the last drops the
empty line after it. With that rule, trailing newlines, empty lines and their heights never
caused a mismatch. Three things did:
1. **Base direction.** Parley sets one base level per layout, from the first strong character.
A paragraph laid out alone takes its own: a Latin line after Arabic goes LTR instead of RTL,
which moves its alignment and run order. This affected RTL, RTL justified, Arabic then
digits, end and centred. Fix: pass the whole text's direction to each paragraph's builder.
Bidi reordering never crosses a `\n`, so nothing else leaked between paragraphs.
2. **Line-top rounding.** Parley rounds each line's top from the unrounded sum of the line
heights above it. A fractional line height (monospace tabs at 32.5 px, pill lines at 1x)
shifts the lines after it by 0.5 px when a paragraph restarts from a rounded top. Fix: round
each line top from the running unrounded total, not the paragraph's own top.
3. **Unbounded width with centre, end or RTL alignment.** One layout aligns every line in its
widest line; a paragraph alone aligns in its own widest line. Fix: shift each paragraph by
(widest paragraph − its width) × the alignment share. When the widest paragraph changes, the
other paragraphs move but nothing is reshaped.
**Typing.** The `edit` workload is a 50 KB note in 695 paragraphs, with one character typed mid-note
per keystroke at 1392 px width and 2x scale. Each mode ran 480 keystrokes:
| Mode | cpu ms median | p95 | Parley heap after open | after 480 keys |
| --- | --- | --- | --- | --- |
| whole (one layout) | 15.2 | 16.7 | 5.39 MB | 5.46 MB |
| naive (every paragraph through the cache) | 0.23 | 0.31 | 4.03 MB | 7.21 MB |
| incremental (only the edited paragraph) | **0.10** | **0.14** | **4.03 MB** | 7.22 MB |
Across three runs, incremental stayed between 0.10 and 0.18 ms median and between 0.14 and
0.26 ms p95. That is about 150× faster than one layout, and the gate is 1.2 ms. The live paragraph
layouts take 4.03 MB. Heap here means live growth from opening, which is not how research 31
counted its 13.8 MB.
The growth to 7.2 MB comes from the cache's stale copies of the edited paragraph. Clearing the
cache frees 3.18 MB while the live paragraphs stay. The stale budget (`STALE_TEXT`, 64 KB) is
charged in text bytes plus 64 per entry, but a 605-byte paragraph's layout holds about 31 KB.
So about 100 superseded copies fit, and the total settles near 64 KB × ~50.
**Verdict: go.** Stacking matches exactly with the three rules above, and typing is 0.1 ms. The
heap gate holds only if the layout cache charges stale entries by layout heap, or an edited
paragraph's old layout is dropped instead of kept as stale.
### Q2: per-word `parley_engine` shaper cache versus Parley paragraph shaping
The first ~50 KB of each file, cut at a newline. Inter 15 pt for the Markdown files and IBM Plex
Mono 13 pt for `runtime.rs`, at 2x and 1392 px. The cache is a word-keyed map of shaped glyphs;
a miss shapes the word alone. A greedy breaker splits lines at spaces. Each row is the median of
20 rounds, with a cold cache every round.
| File | tokens | distinct | hit rate | Parley ms | cache ms | + analysis | speedup | with analysis | warm cache |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| PLAN.md | 7,480 | 3,136 | 58.1% | 14.36 | 7.68 | 9.21 | 1.87× | **1.56×** | 8.9× |
| CHANGELOG.md | 7,231 | 2,980 | 58.8% | 14.20 | 8.26 | 9.73 | 1.72× | **1.46×** | 9.0× |
| runtime.rs | 6,252 | 2,661 | 57.4% | 6.30 | 2.69 | 4.02 | 2.34× | **1.57×** | 4.1× |
On real text only 57–59% of words repeat within 50 KB, against 89% for the synthetic note's 772
distinct words. "+ analysis" adds the per-paragraph `Analyzer` pass that any real breaker needs
for break opportunities, bidi and script, and with it the cache wins only 1.5×. "Warm cache"
means every word was already shaped, as on a re-wrap. That case is not the cache's to win: Parley
re-breaks an existing layout without reshaping, and per-paragraph caching already makes typing
0.1 ms.
The cache side is also an upper bound. It uses one font with no fallback, a fixed advance for
spaces, no kerning or ligatures across spaces, and breaks only at `' '`, not UAX #14.
**Verdict: kill** the custom breaker. A cold cache wins 1.5×, below the 2× bar, and the case
where it wins big (a warm cache) is already cheap with Parley plus per-paragraph layouts.
+244
View File
@@ -0,0 +1,244 @@
# 33. Real-app bottlenecks, checked against the engine plan
Reader: someone choosing the next frame-time work in `rune`, `rune-kit` or `rune-motion`, or
checking whether [32](32-engine-plan.md)'s ranked plan matches what real apps spend. Re-run the
harness below before and after a change that should move one of these numbers.
The question: in four real Rune apps, during the interactions people actually do, which costs
push frames over the 8.3 ms budget at 120 Hz, and does [32](32-engine-plan.md) cover them?
The short answer: the frames that miss the budget come from rebuilding too much, not from
Taffy or Parley. In every interaction measured here, shaping is 0% to 3.5% of the main
thread's busy time and Taffy 0% to 7.4%. The worst frames re-run a whole view and flatten its
tree after a small change: a keystroke, a step of a live resize, a scroll that mounts new rows,
or opening a card. In two apps the view runs every row's builder, Markdown included, because
the list is built in full and then virtualized. [32](32-engine-plan.md)'s flatten, `memo` and
motion items (#2, #3, #7, #8) hold up on real data, but its two largest projected savings don't
fire here: the resize fast path (#4) excludes any tree with a virtual list, which every measured
app has, and none of the measured interactions types into a long field, where the per-paragraph
layout (#1) would pay off. Three costs the plan doesn't mention: paint re-emits every visible
glyph each frame (21% to 37% of a scroll frame), a virtual window shift re-runs the whole view,
and a blocking read on the main thread looks like a fast frame unless wall time is logged
next to CPU time.
## How it was measured
- Rune `c83aa06b` (`dev`), with each app's `rune` dependencies patched to that tree and built
at `--profile perf` with `rune/frame-profile`. Apps were left unchanged apart from bench-only
seeding switches (a longer seeded conversation, a fixed reply to stream, a card to open).
- Headless and offscreen at scale 2, on a 12-core M2 Max worker that other jobs were also
using (load average 6 to 20 during the runs). Each scenario ran once as warmup and then five
more times, with scenario order alternating between runs. Numbers are medians across runs
with outliers kept.
- `RUNE_FRAME_LOG=FILE` (new here) writes one JSON line per frame: wall and thread-CPU time,
phase CPU (view, commit, layout, text, paint, apply), allocations, commits and texts
shaped. A closing line records memory. `RUNE_HEADLESS_WAIT=SECS` (also new) holds a headless
run before its first frame so a sampling profiler can attach in time to see launch.
- `scripts/real-frames.py` runs the scenarios, summarizes them per interaction window, and
buckets a 1 kHz macOS `sample` of the main thread by self time.
- **What headless leaves out:** GPU execution, presentation, display timing and the window
server. Headless also draws every frame. The tables count only frames a real window would
draw: ones where input arrived, a commit ran or something animated.
Workloads, described generically:
| Workload | Data | Interactions |
|---|---|---|
| Agent client | A real 1,200-message transcript (22 MB), plus a 7.2k-character Markdown reply streamed in | launch, scroll (5 swipes), stream, type in the composer, live resize |
| Task board | A real board snapshot: 895 tasks, some cards with long notes, one with a Mermaid diagram | board scroll, open 12 cards in turn, scroll a long card, open and scroll the diagram card |
| Team chat | A seeded conversation repeated 40 times, one day apart | launch with arrivals, scroll, type, live resize |
| Notes reader | 601 synthetic notes, one of them 200 KB | launch, open a note, step the block cursor, search palette, scroll, live resize |
## Frame CPU per interaction
Thread-CPU ms per drawn frame, from the median run. "Over" is the number of frames above
8.3 ms out of `n`.
| Workload / interaction | n | p50 | p95 | p99 | max | over |
|---|---:|---:|---:|---:|---:|---:|
| Agent client / scroll | 544 | 1.16 | 3.93 | 5.66 | 11.7 | 2 |
| Agent client / stream | 1980 | 1.14 | 5.52 | 7.01 | 9.45 | 2 |
| Agent client / type | 96 | 3.44 | 5.51 | 6.50 | 6.50 | 0 |
| Agent client / resize | 266 | 4.87 | 8.59 | 9.62 | 10.6 | 18 |
| Task board / scroll | 178 | 1.93 | 2.47 | 3.33 | 9.90 | 1 |
| Task board / open cards | 324 | 3.21 | 25.5 | 43.1 | 47.4 | 106 |
| Task board / long card scroll | 361 | 5.47 | 31.1 | 32.9 | 33.9 | 82 |
| Task board / diagram card scroll | 435 | 3.59 | 17.2 | 18.9 | 22.0 | 60 |
| Team chat / scroll | 736 | 0.56 | 1.18 | 1.48 | 15.0 | 3 |
| Team chat / type | 659 | 0.51 | 12.1 | 22.7 | 24.9 | 92 |
| Team chat / resize | 336 | 18.4 | 39.7 | 42.8 | 44.6 | 241 |
| Notes reader / step cursor | 96 | 6.42 | 13.8 | 15.0 | 15.0 | 30 |
| Notes reader / palette search | 22 | 2.88 | 7.64 | 9.62 | 9.62 | 1 |
| Notes reader / scroll | 267 | 1.22 | 1.81 | 2.16 | 2.64 | 0 |
| Notes reader / resize | 242 | 7.71 | 13.7 | 15.3 | 15.5 | 102 |
An earlier chat resize run on the same machine measured p50 13.4 ms with 228 frames over.
Palette search's CPU looks fine, but its wall time doesn't: see #2 below.
Launch, headless (process start to first frame read back) and the first frame's CPU:
| Workload | Process to pixels | First frame CPU | What the first frame spends |
|---|---:|---:|---|
| Agent client | 298 to 347 ms | 28 to 33 ms | before it, 63 to 193 ms loading the transcript; layout 13 to 16, text 12 to 15 (102 texts shaped) |
| Task board | 201 to 293 ms | 86 to 172 ms | shaping 27 to 38, layout 13 to 47, view 20 to 44 |
| Team chat | 68 to 112 ms | 34 to 45 ms | view 26 (every row built), paint 9 |
| Notes reader | 59 to 98 ms | 13 to 26 ms | view 5, layout 3, text 2 |
## Where the main thread goes
Share of busy main-thread samples (waits left out), by the self-time owner. "paint" is the
per-frame draw-list walk (`Runtime::build`, `Phase::Paint`). "glyphs" is Parley's laid-out-glyph
iterators, almost all of it called from that walk. "rtext" is Rune's text code: `push_glyph`,
`text_hash`, Markdown building. "app" and "os" include app code: when an app function's own
frames sit in system calls, they land in "os".
| Interaction | paint | glyphs | rtext | view | flatten | taffy | shape | motion | alloc | app | os |
|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| Agent client / scroll | 13.1 | 25.3 | 10.0 | 8.5 | 1.5 | 1.1 | 2.1 | 1.8 | 4.6 | 2.5 | 18.3 |
| Agent client / stream | 10.4 | 8.9 | 8.7 | 21.6 | 11.0 | 2.9 | 2.1 | 5.0 | 8.6 | 3.3 | 11.3 |
| Agent client / type | 17.2 | 18.7 | 8.7 | 12.6 | 5.2 | 0.9 | 2.8 | 3.3 | 6.1 | 2.8 | 14.3 |
| Agent client / resize | 7.8 | 8.2 | 7.6 | 21.0 | 12.8 | 6.2 | 0.6 | 6.6 | 8.1 | 2.8 | 11.7 |
| Task board / scroll | 13.6 | 2.3 | 1.5 | 10.4 | 1.9 | 0.0 | 0.0 | 12.5 | 6.3 | 22.7 | 22.7 |
| Task board / open cards | 8.2 | 1.9 | 2.8 | 9.5 | 3.6 | 0.4 | 1.0 | 3.6 | 11.6 | 26.8 | 23.3 |
| Task board / long card | 13.3 | 0.9 | 3.2 | 19.2 | 5.5 | 0.6 | 0.7 | 8.8 | 9.6 | 16.3 | 17.4 |
| Team chat / scroll | 19.6 | 16.0 | 8.2 | 14.9 | 0.5 | 0.3 | 0.5 | 3.5 | 6.5 | 2.2 | 17.7 |
| Team chat / type | 8.9 | 5.9 | 11.3 | 19.2 | 2.6 | 0.2 | 0.2 | 2.5 | 11.5 | 12.6 | 21.4 |
| Team chat / resize | 1.6 | 1.0 | 13.3 | 21.3 | 4.0 | 1.6 | 0.0 | 1.2 | 14.6 | 17.8 | 22.6 |
| Notes reader / step cursor | 13.1 | 15.1 | 13.0 | 16.4 | 7.4 | 0.4 | 0.4 | 8.4 | 7.3 | 2.4 | 9.7 |
| Notes reader / scroll | 21.8 | 26.1 | 12.1 | 6.7 | 0.4 | 0.0 | 1.9 | 5.8 | 2.2 | 1.3 | 10.8 |
| Notes reader / resize | 7.5 | 4.6 | 16.8 | 18.5 | 7.5 | 7.4 | 0.4 | 8.5 | 10.2 | 3.8 | 10.7 |
Glyph rasterization and atlas work is at most 0.9% everywhere. Parley line breaking is at
most 3.4%.
## The ten biggest costs
Ranked by how often and how far each one takes frames past 8.3 ms. "Covered" refers to the
numbered items in [32](32-engine-plan.md) §4.
1. **Team chat: a keystroke or a resize step rebuilds every message row.** A keystroke
commit takes 14.8 ms of CPU, 83% of it in view (12.3 ms). A resize step takes 18 to 20 ms
(view 16.8 ms), and 228 to 241 of 336 resize frames miss the budget. The view builds every
message, Markdown included, and then calls `El::virtualize`, which drops the offscreen rows
in `populate_virtual_children`'s non-`RowSource` branch
(`crates/rune/src/runtime/measure.rs:164-189`). The hot code is the app's row builder,
`rune_kit::markdown` (`markdown.rs:1556-1580`) and `el::text` (`el.rs:970-1006`).
*Not covered.* #4 excludes virtual lists, #8 helps only if the app memoizes rows, and
nothing makes `virtualize` build lazily. The `virtual_rows` API already avoids this.
2. **Notes reader: each keystroke in the search palette blocks for 260 to 540 ms.** Mean wall
time per update is 263 ms (p95 538 ms, worst 658 ms) while CPU stays at 3 ms. 90% of
main-thread samples sit in `recvfrom`: the key handler sends a search request to a local
daemon over a Unix socket and waits for the answer. This one cause accounts for the whole
hitch. *Not covered*, since the cost is in the app. Rune has nothing that reports a frame
whose wall time far exceeds its CPU time.
3. **Task board: opening a card or scrolling a long one re-runs the whole view.** Spike frames
cost 18 ms (open) and 28 ms (long card). That is view 9 to 10 ms (36% to 50%),
flatten and bookkeeping 3.6 to 6.5 ms, apply 1.3 to 4.2 ms and the app's poll 2 ms. 106 of
324 and 82 of 361 frames miss. During a scroll, a virtual window or layout-read change sets
off a full commit (`runtime.rs:2285-2303` → `commit` → `measure`). That commit rebuilds the
card's note Markdown along with everything else. *Partly covered:* #2 (apply) and #3, #7
and #8 (flatten). Nothing in the plan limits a window shift to building the newly mounted
rows.
4. **Task board launch: the first frame takes 86 to 172 ms of CPU, and opening the diagram
card 136 ms.** 27 to 38 ms of that is shaping text seen for the first time. Layout takes 13
to 47 ms and view 20 to 44 ms over 1,350 to 4,800 layout nodes. This is a one-time spike,
almost all of it first-use shaping and layout of everything mounted. *Partly covered:* #9
(resolved-style cache, −1.5 to −2.5 ms) and #10 (virtualized Markdown). The real cost is
5 to 9× the plan's 18 ms `md-open` baseline because the whole board mounts.
5. **Live resize of virtualized views re-runs view and flatten on every step.** Notes reader:
7.6 ms per step (view 1.4, layout 2.1, text 0.5, apply 1.3, flatten about 1.2, paint 0.7),
102 of 242 frames over. Agent client: p50 4.9 ms, 18 of 266 over. `text_hash` alone is 8% of
the notes reader's resize (about 0.6 ms) and 4.4% of the agent client's; Taffy is 6% to 7%.
*Covered in idea only.* #4's fast path would skip about 1.4 to 2 ms here, but its gate
(`virtuals.is_empty()`) rejects all four apps. #5's projected saving holds: 0.2 to 0.6 ms.
6. **A small state change commits the whole tree.** Stepping the notes reader's block cursor
costs 6.4 ms with 25k allocations, and 30 of 96 frames miss. An agent client keystroke
costs 3.4 ms, and a streamed chunk 4.2 ms. The costs are in `flatten` (5% to 13%;
`flatten.rs:222` moves each `Node` in, `:340` compares Taffy styles), `El::clone` of `memo`
hits (2% to 7%, `expand_memo`), `apply` (3% to 6%, `runtime.rs:4449`), `Keyed::new` (2% to
3%, `layout_read.rs:585`, a fresh map of every keyed node on each commit) and
`capture_keeps` (2.8%, `sticky.rs:439`). *Mostly covered* by #3, #7 and #8 (flatten,
clones) and #2 (apply). `Keyed::new` and `capture_keeps` are not.
7. **Paint re-emits every visible glyph every frame.** On scroll, paint takes 0.4 to 1.2 ms a
frame. Parley glyph iteration plus `push_glyph` (`runtime.rs:6959-6994`, `text.rs:2153`,
Parley `run.rs:335-359`) is 21% to 37% of a scroll frame, and the per-node walk
(`runtime.rs:5734`) another 13% to 22%. That makes it the floor under every scroll and
animation frame, and it grows with window size. *Not covered*, except #7's culling of
offscreen subtrees. Onscreen text has no cached quads.
8. **Task board: the app's poll costs 1.0 to 1.8 ms every frame, 98% of the time with no
change.** It makes 8k to 13k allocations a frame, half of a board-scroll frame. The cost is
in the app's per-frame status checks. *Not covered* (app code).
9. **Motion upkeep: `Scene::present_dirty` and `Scene::phase`.** These take 2% to 12.5% of
busy time, most on board scroll (about 0.24 ms a frame). Apply takes 4.2 ms on the long
card's spike frames. *Covered* by #2. Its −2.3 ms holds only for the largest tree (the
board's 4,800 nodes). The other apps' trees are smaller and would save 0.1 to 0.5 ms.
10. **First frames in the chat and agent client: 28 to 45 ms of CPU.** In the chat, the view
takes 26 ms because every row is built (as in #1), and paint takes 9 ms rasterizing glyphs
for the first time. In the agent client, layout takes 13 ms and text 12 ms for 102 texts.
*Partly covered* by #9 and #10.
## Checking [32](32-engine-plan.md) against real data
| # | Plan item | Real data |
|---|---|---|
| 1 | Per-paragraph `TextLayout` | None of the measured interactions types into a long field: the agent client's composer is short and the notes reader has no editor. Shaping is ≤ 3.5% everywhere, so −14 ms doesn't show up here. Still worth doing for long-field editing, but it isn't what these apps hit today. |
| 2 | Lazy motion tracks, no-op dirty | Holds. Motion is 2% to 12.5%, and apply is 0.6 to 4.2 ms on commit frames. Saves 0.1 to 0.5 ms on small trees and more on the board. |
| 3 | `has_virtual` bit and path table | Holds. `node_path` 2.2% and memo deep clones 2% to 7% match root cause 1. |
| 4 | Resize fast path | Doesn't fire on any measured app: all four have a virtual list. Its saving (~1.4 to 2 ms a step) is real only if the gate admits virtual lists whose window doesn't change. |
| 5 | One `shape_key` hash | Holds: `text_hash` is 2% to 8%, so 0.2 to 0.6 ms. |
| 6 | In-place re-break | Not visible. `Layout::clone` isn't among the top functions of any profile. |
| 7 | Compact `BoxStyle`, `Cold<T>`, culling | Holds for flatten (`:222` Node moves and `:340` style compares are its top lines). Culling is the plan's only paint change. |
| 8 | Flattened `memo` reuse | The best fit for #3 and #6, but only where apps memoize. The chat app doesn't. |
| 9 | Resolved-style cache | Small next to the board's 27 to 38 ms first-frame shaping. |
| 10 | Virtualize Markdown | Applies to card notes and transcript messages at first mount, not in steady state. |
| 11 | Single-pass `aspect_fit` | Not seen. |
| 12 | Word shape cache | No trigger: shaping is ≤ 3.5% after launch. |
What the plan misses:
- **Lazy virtual lists.** `El::virtualize` accepts a fully built list. Rune could warn when a
virtualized list builds far more rows than it mounts, or make lazy building the default
path.
- **Window shifts that build only the new rows.** When a virtual window or a layout read
moves, Rune re-runs the whole view (#3, and the agent client's roughly 59 commits per scroll run, at 3.9 ms each).
- **A glyph quad cache in paint.** Keep each text node's quads keyed by layout, scale and
colour, and translate them when the node moves (#7).
- **Per-commit bookkeeping:** `layout_read::Keyed::new` and `sticky::capture_keeps` (#6).
- **Stall detection.** The frame log's wall-versus-CPU split is what exposed #2. A debug
warning when an update's wall time is many times its CPU time would catch blocking I/O on
the main thread.
## Memory
App heap, where the app counts it: task board 50 to 100 MB live heap, notes reader 9 to
21 MB. Malloc regions from `footprint`: agent client while streaming 177 MB, chat 86 MB.
Headless footprint numbers can't be compared across runs. The headless loop submits a frame
each time without polling the device, so GPU work and its buffers pile up while the run
renders frames faster than real time. `IOAccelerator (graphics)` reached 155 to 784 MB over
1,800 to 8,300 regions and grew with the number of frames rendered, not with the
interaction. An idle notes launch reached 967 MB after 3 s, with heap at 9 MB. That explains
why the same chat scenario measured 0.25 GB in one run and 1.6 GB in another. A real window
paces itself on the surface, so these numbers say nothing about real windows. Compare heap,
not footprint, until the headless loop polls the device every frame.
## Caveats
- The worker was shared. Wall times include preemption: the agent client's wall p95 is 15 to
43 ms against a CPU p95 of 4 to 9 ms. The CPU numbers are the ones to compare.
- Headless profiling misses GPU and presentation costs. A HUD overlay app was left out
because its costs are in overlay presentation, which headless doesn't model and which is
being changed separately.
- The workloads' data is real, apart from the notes reader's synthetic fixture and the chat's
repeated seed.
## Reproduce
Build an app at `--profile perf` with `rune/frame-profile`, write a scenario config (format in
`scripts/real-frames.py`'s docstring), then:
```
scripts/real-frames.py run app.json --out out/app --runs 5 --sample --sample-secs 90
scripts/real-frames.py summary app.json --out out/app --table
scripts/real-frames.py profile out/app/scroll.sample.txt --top 30
```
+681
View File
@@ -0,0 +1,681 @@
# 34. Should Rune own its GPU layer? Verdict, numbers and plan
Reader: someone deciding whether Rune should replace `wgpu` with its own GPU layer, or choosing
which layer to own on each platform. Re-run `overlay_hud_cost` ([30](30-overlay-gpu-cost.md)),
`upload_bench`, `frame_bench`, `layout_text_cost` ([31](31-layout-text-cost.md)) and
`scripts/motion-audit` at every gate below.
The question: from first principles, should Rune build and own its own GPU backend instead of
paying `wgpu`'s per-frame overhead or waiting on upstream?
**Verdict: yes on Apple (`macOS` and `iOS`), no everywhere else.** Build a ~2,800-line native
Metal backend inside `crates/rune/src/gpu/metal/` on `objc2-metal`, `objc2-quartz-core` and
build-time `naga` (all already in `Cargo.lock`), bridged into `wgpu` 30's `custom` backend
trait (`features = ["custom"]`) plus a direct internal fast path for Rune's own uploads and
present. Keep `wgpu` on Windows (DX12), Linux (Vulkan) and Web (WebGPU), and send three small
bug-fixed patches upstream to `gfx-rs/wgpu` (~120 lines, hand-written descriptions) so Windows
and Linux drop the redundant present submission when upstream ships them.
Why this split wins:
1. **Continuous 120 Hz frames spend 30% to 75% of process CPU in `wgpu` and driver dispatch.**
That covers HUD overlays, `virtual_rows` scrolling, `gpu_springs` ticks and multi-pass blur
or lighting frames. Even with both prototype `wgpu` patches from [30](30-overlay-gpu-cost.md),
any frame that writes a uniform or instance buffer still commits 3 `MTLCommandBuffer`s plus
a `MTLBlitCommandEncoder` and `unmap`/`map_async` round-trip, costing ~1,428
kinstructions/frame against ~850 kinstructions/frame in hand-written Metal.
2. **Heavy window commits spend only 1% to 3.5% (~0.15 ms) in `wgpu`.** On `stack` (10.2 ms),
`edit` (15.5 ms) and `md-resize` (4.35 ms), the commit, motion and paragraph-caching work in
[32](32-engine-plan.md) must carry the win. Once [32](32-engine-plan.md) brings memoized
commits and scrolling under 0.3 to 0.8 ms, `wgpu` becomes a major share of normal windows too.
3. **`wgpu::custom` keeps 100% of the public API compiling.** `Compositor`, `Frame`,
`EffectHook`, `rune-fx`, `rune-light`, `rune-staging`, headless pixel tests and downstream
apps keep their exact `wgpu::*` types on crates.io `wgpu ~30.0.1` without `[patch.crates-io]`
(which Cargo ignores in git dependencies anyway).
4. **Owning Metal is small (~2.8 kLOC); owning Vulkan and DX12 is 5 to 7 times larger (~15 to
20 kLOC) where driver and Wayland/X11 swapchain bugs hurt small teams.** Zed (`zed#46758`)
dropped `blade` on Linux and returned to `wgpu` in January 2026 while keeping raw Metal on
macOS; Warp ships the same native-Metal-plus-`wgpu` split; Flutter Impeller's Vulkan backend
(~21 kLOC) is 3.5 times its Metal backend (~5.9 kLOC).
## Default on macOS
Since 2026-10-31 the native backend is the default on macOS: `metal-backend` is one of Rune's
default features, and an app that doesn't call `App::gpu_backend` draws with it, prewarm
included. `App::gpu_backend(GpuBackend::Wgpu)` or `RUNE_GPU_BACKEND=wgpu` opts out, and an app
built with `default-features = false` keeps wgpu unless it adds the feature. `GpuBackend`'s
`Default` is still `Wgpu`; the backend keeps the app's choice as unset, `Wgpu` or `Metal`
internally, so an explicit `Wgpu` always wins. wgpu's `custom` feature is turned on for macOS
targets only, so Linux, Windows, web and iOS builds compile what they did before. iOS keeps wgpu.
Where the native backend falls short of wgpu, a defaulted app either falls back or fails loudly:
- A compositor whose `Compositor::features` asks for something the backend doesn't offer (it
offers `TIMESTAMP_QUERY` and `IMMEDIATES`) gets a wgpu device for that window or headless run, said once.
- Pipelines made with `layout: None` derive their layout from the shaders, as wgpu-core does.
- Depth and stencil, multisampling, more than four colour targets, indirect draws and
dispatches, render bundles, occlusion and pipeline-statistics queries, timestamps written
inside or between passes, non-WGSL shaders, `clear_texture`, binding arrays and uncommon
texture or vertex formats panic with a message that names the opt-out.
## 1. Where GPU CPU goes: HUD overlays vs normal windows
### Code checks and corrections to earlier notes
Checking `crates/rune`, `crates/rune-fx`, `crates/rune-light` and `wgpu` 30.0.1 source turned up
five facts that change the options:
1. **Normal macOS windows do not use `PresentWorker`.** Only overlays spawn the `rune present`
worker (`crates/rune/src/overlay/frame.rs:57`). `crates/rune/src/window/draw.rs:269-275` runs
`encoder.finish()`, `queue.submit` and `queue.present` synchronously on the AppKit main
thread. Once Metal submit-and-present folds onto one `MTLCommandBuffer` (~35 µs instead of
~214 µs), overlays can drop `PresentWorker` too, saving its thread and two `mpsc` wakeups per
frame (~14 to 25 ms per 10 s).
2. **Both prototype `wgpu` patches still leave +310 kinstructions/frame on any buffer write, and
$P + 1$ command buffers on $P$-pass frames.** In `wgpu-core` 30.0.1
(`command/render.rs:2308-2315`), `encode_render_pass` calls `raw_encoder.close_if_open()`
ahead of every pass so it can splice a barrier buffer before the pass (`close_and_swap` at
`:2765`). Any `copy_buffer_to_buffer` recorded by `Staging::flush` (`Frame::write_buffer` or
`Renderer::prepare`) opens a non-empty blit `MTLCommandBuffer` that `encode_render_pass`
immediately closes. `wgpu-hal-metal-lazy-command-buffer.patch` only skips *empty* command
buffers, so every frame with an upload still commits 3 `MTLCommandBuffer`s (blit, render,
present) plus `unmap`, `map_buffer_on_submit` and channel recycling (+323 kinstructions in
[30](30-overlay-gpu-cost.md)). Multi-pass frames (`backdrop_blur`, `layer_blur`, `rune-fx`,
`rune-light`) commit $2P + 4$ command buffers unpatched and $P + 1$ patched (~2.3 MiB of
transient `IOAccelerator` memory per command buffer, `wgpu#10494`).
3. **`wgpu-hal-metal-lazy-command-buffer.patch` has three bugs.** First, `begin_encoding`
(`metal/command.rs:487`) increments `command_buffer_created_not_submitted`, and `end_encoding`
clears `self.begun = false` while returning `CommandBuffer { raw: None }`; if that buffer is
dropped unsubmitted, `CommandBuffer::drop` (`:1978`) returns early on `None` and leaks a slot
toward the 2,048 `DeviceError::Lost` limit. Second, `Queue::submit` (`metal/mod.rs:755`)
unconditionally sets `"(wgpu internal) Signal"` on the last non-empty command buffer, which
with lazy buffers is the caller's render pass buffer, clobbering its label. Third, moving
`relay.next_release_value.load(Acquire)` out of `begin_encoding` into lazy `cmd_buf()` races
concurrent submissions under strict event sync.
4. **`wgpu` 30.0.1 already exposes `wgpu::custom` (`features = ["custom"]`).** Every `wgpu`
handle dispatches over `Core | WebGPU | Custom` (`wgpu/src/dispatch.rs:728`), with public
`Instance::from_custom`, `Texture::from_custom` and `as_custom::<T>()`. Both `Core` and
`Custom` coexist in one binary (`RUNE_GPU_BACKEND=metal|wgpu`). Meanwhile, Rune's full
surface uses two features a minimal quad renderer would miss: 2-target MRT (`gb0`/`gb1` in
`crates/rune-light/src/render.rs:108`) and dynamic uniform offsets (`has_dynamic_offset: true`
in `crates/rune-fx/src/renderer.rs:342`).
5. **`wgpu-hal` alone neither reaches 1 command buffer on Metal nor stays thin on Vulkan/DX12.**
`hal::metal::Queue::present` (`metal/mod.rs:810`) always commits a separate `Present` command
buffer, and `hal::metal::Queue::submit` (`:739`) always heap-allocates a `block2::RcBlock`
completion handler (+81 kinstructions/frame combined in `metal_hud.swift`). On Vulkan and
DX12, `wgpu-hal` (`lib.rs:48-52`) requires explicit caller-computed `transition_textures` and
`transition_buffers` barriers, which would force Rune to rebuild `wgpu-core`'s state tracker
to keep multi-pass effects and user `Compositor`s sound.
### Attribution: HUD overlay (120 Hz, `overlay_hud_cost`)
From [30](30-overlay-gpu-cost.md) (paired runs at 120 Hz, `proc_pid_rusage` retired instructions
and slow-mode process CPU):
- **0-write HUD:** Rune today runs 1,555 kinstr/frame (19.5% CPU, 6 command buffers, 2
handlers) vs 850 kinstr/frame (11.2% CPU, 1 command buffer, 0 handlers) for
`metal_hud.swift`. The two `wgpu` patches cut 4 empty command buffers and the second present
submit (-437 kinstr, to 1,118 kinstr / 16.0% CPU), leaving 268 kinstr (58% of the 8.3-point
CPU gap). From the 8 s and 10 s thread profiles, that remaining 268 kinstr splits into three
parts:
- **~81 kinstr in `wgpu-hal` Metal:** separate `Present` command buffer plus 1 `RcBlock`
completion handler and driver notification (`929k - 848k` measured on `metal_hud.swift`).
- **~90 kinstr in `wgpu-core` and `wgpu-hal`:** per-frame `Surface` `Texture`/`TextureView`
allocations and registry locks (`10 ms/10 s` in `create_view` alone), `ArcCommand` record
and replay, `Tracker` `set_size`/drop (`43 ms/8 s` on the present thread), 55 heap
allocations/frame, and duplicate `Fence::get_latest` `status()` polls.
- **~97 kinstr in Rune's own overlay loop (being fixed separately):** `frame::step` on an
unchanged empty view (`46 ms/10 s`), `about_to_wait` and pointer polling (`22 ms/10 s`),
`PresentWorker` handoff/wait (`14 ms/10 s`), and duplicate `surface_occluded` layer walks.
- **1-write animating HUD (`OVERLAY_WRITES=1`, live meters/waveforms):** Rune today runs 1,881
kinstr/frame (`Frame::write_buffer`) or 1,863 kinstr (`Queue::write_buffer`). Patched `wgpu`
still lands around ~1,428 kinstr/frame because the blit copy splits out a 3rd command buffer
and unmaps/remaps the staging chunk every frame. A unified-memory `MTLStorageModeShared` ring
in a single `MTLCommandBuffer` writes 256 B with one `memcpy` and
`setVertexBufferOffset`/`setFragmentBufferOffset` (< 2 kinstr).
### Attribution: normal window frames (`upload_bench`, `frame_bench`, [29], [31])
Running `upload_bench` and `frame_bench` (`--profile perf`, headless Metal) gives 54.3 µs CPU
to prepare, encode and submit a 2,000-instance steady frame, 83.0 µs when all 2,000 instances
scroll (256 KiB staged upload), 15.1 µs to record 10 `rune-light` GI passes (before `finish()`
replays them into 20+ command buffers), and 97.9 µs for 16 `rune-fx` layers with 4 backdrop
blurs. Adding main-thread surface acquire (excluding `nextDrawable`'s own wait, which native
Metal shares), `create_view`, `present`'s extra submit and background driver threads puts
avoidable `wgpu` overhead in a 1-pass window at ~0.14 to 0.20 ms/frame (~0.35 to 0.55 ms/frame
with 6 to 10 blur/effect passes):
| Window workload (120 Hz = 8.33 ms) | Rune CPU today ([29], [31]) | Avoidable `wgpu` + driver CPU | `wgpu` share today | Rune CPU after [32] | `wgpu` share after [32] |
|---|---:|---:|---:|---:|---:|
| `edit` (typing in 50 KB note) | 15.50 ms | ~0.16 ms | ~1.0% | ~1.00 ms | ~14% |
| `stack` (5,283 nodes, 1 flip) | 10.20 ms | ~0.16 ms | ~1.5% | ~3.8 ms (< 0.8 `memo`) | ~4% (~17% `memo`) |
| `md-resize` (50 KB width drag) | 4.35 ms | ~0.16 ms | ~3.5% | ~1.40 ms | ~10% |
| `md-same` (unchanged commit) | 1.98 ms | ~0.13 ms | ~6.2% | ~0.7 ms (< 0.25 `memo`) | ~16% (~34% `memo`) |
| `list` scroll (`virtual_rows`) | 0.15–0.31 ms | ~0.17 ms | **35–53%** | ~0.10–0.22 ms | **44–63%** |
| `gpu_springs` (`present_at` tick) | ~0.01 ms | ~0.17 ms | **> 90%** | ~0.01 ms | **> 90%** |
| Window + backdrop blur / `rune-fx` | 0.30–1.50 ms | ~0.35–0.50 ms | **20–60%** | 0.20–0.80 ms | **30–70%** |
## 2. Comparison of options
HUD numbers show the projection after Rune's ~97 kinstr overlay-loop fixes (with pre-fix
numbers in parentheses for 0-write) so GPU layers are compared on equal footing against
`metal_hud.swift` (850 kinstr / 11.2% CPU).
| Option | HUD 0-write / 1-write (kinstr, slow CPU %) | Normal window CPU saved | LOC to write & own | Public API & feature impact | Startup & shaders | Key risks |
|---|---|---|---|---|---|---|
| **Today (`wgpu` 30.0.1)** | `1,458k` (`1,555k` raw) / `1,784k`; ~18.3% / ~22.3% | Baseline (0 ms) | 0 | None; 10 macOS `as_hal` sites depend on `wgpu-core` + `wgpu-hal`. | `uber.metallib` only (85 ms); `fx`/`light`/blur/iOS compile WGSL at runtime; `PipelineCache` no-op. | 6–24 CBs/frame; +310k/write; `get_current_texture` leaks `TextureId` on miss. |
| **(A) Patched `wgpu` fork + upstream PRs** | `~1,021k` (`1,118k` raw) / **`~1,331k`**; ~13.5% / ~17.5% | ~0.06 ms (1-pass); ~0.15 ms (blur, empty CBs only) | ~150 LOC patch + fork rebases | **Cargo ignores `[patch]` in git deps**: every app must copy `[patch.crates-io]` or face split `wgpu` versions. | Unchanged (`Passthrough` still lacks `sized_bindings` & `override`; no `MTLBinaryArchive`). | Upstream Metal review is slow (`#5738` open since 2024); never fixes 1-write (+310k) or $P$-pass CB split. |
| **(B) macOS `CAMetalLayer` bypass + `from_hal`** | `~1,195k` (`~1,292k` raw) / `~1,505k`; ~15.4% / ~19.3% | ~0.04 ms | ~250 LOC in `crates/rune` | Zero breakage, but still links `wgpu-hal` + `wgpu-core`. | Unchanged. | Strictly worse than (A): `Transit` + `Pre Pass` + split `Present` CBs (4–5 CBs/frame) and per-frame `TextureId` churn stay. |
| **(C) `wgpu-hal` directly on Metal, DX12, Vulkan (Web on `wgpu`)** | `~935k` / `~960k` (2 CBs, 1 `RcBlock` handler); ~12.3% / ~12.6% | ~0.11 ms (1-pass); ~0.25 ms (multi-pass) | **~5,500–7,500 LOC** (incl. Vulkan/DX12 barrier tracker & fence ring) | Must wrap in `wgpu::custom` or break `Compositor`/`Frame`/`fx`/`light`. | Still no `MTLBinaryArchive`; `hal` passthrough still lacks `sized_bindings` unless forked. | **High:** `wgpu-hal` is semver-unstable with undocumented `unsafe` contracts; missing Vulkan/DX12 barriers corrupt user `Compositor`s. |
| **(D) Own Metal (`macOS`/`iOS`) via `wgpu::custom` + internal fast path; `wgpu` elsewhere + 3 upstream PRs** *(Recommended)* | **`~855–880k`** (`~955k` pre-overlay-fix) / **`~860–890k`**; **~11.3–11.6%** (1 CB, 0 handlers) | **~0.14–0.19 ms** (1-pass, −35–50% scroll CPU); **~0.35–0.48 ms** (multi-pass) | **~2,800 LOC** (−350 LOC `as_hal` deleted); 0 new Cargo deps | **Zero breakage:** `Compositor`, `Frame`, `fx`, `light`, video `IOSurface`, headless & web compile unchanged; runtime `RUNE_GPU_BACKEND=wgpu` toggle. | Build-time Naga WGSL→MSL→`.metallib` for **all** shaders (`macOS` + `iOS`) + on-disk `MTLBinaryArchive` (< 15 ms warm). | **Low:** scoped to Apple's stable Metal 2.3 API; `wgpu` stays as A/B oracle and Linux/Windows/Web workhorse. |
| **(E) Own backends everywhere (Metal, DX12, Vulkan; Web on `wgpu`)** | Same as (D) on Apple (`~855–880k`) | Same as (D) on Apple; ~0.12–0.20 ms on Win/Linux | **~17,000–23,000 LOC** + DXC/SPIR-V build & allocator stack | Same `wgpu::custom` bridge, but must emulate full WebGPU surface for `Compositor` on 3 APIs. | Offline `.metallib` + DXIL + SPIR-V + `VkPipelineCache`. | **Very high:** Wayland/X11/NVIDIA swapchain hangs (`zed#46758`), D3D12 descriptor heaps/DirectComposition, Lavapipe CI quirks. |
## 3. Internal seam and public API preservation
Rune keeps `wgpu` types at the public boundary (`Gpu`, `Renderer`, `Compositor`, `Frame`,
`EffectHook`) by enabling `wgpu = { version = "~30.0.1", features = ["custom", ...] }` on
`macOS` and `iOS` only (Windows, Linux and Web compile without `custom`, preserving `wgpu`'s
single-variant devirtualization there). Across 60 draws and 10 bind groups, `custom`'s vtable
dispatch adds ~75 calls (~0.1 µs, ~0.4 kinstr). Internally, Rune's window loop, overlay loop,
`Uploads` and `native_surface` downcast once to `MetalQueue` / `MetalDevice` / `MetalSurface`
to bypass staging blits, `PresentWorker`, and `as_hal`:
```rust
// crates/rune/src/gpu/mod.rs: internal fast-path seam alongside wgpu::custom
pub(crate) trait BackendHooks {
fn write_shared_ring(&self, bytes: &[u8], align: u64) -> Option<(wgpu::Buffer, u64)>;
fn submit_and_present(&self, encoder: wgpu::CommandEncoder, frame: wgpu::SurfaceTexture);
fn uses_present_worker(&self) -> bool; // false on Metal (1-CB commit is ~35 us)
}
// crates/rune/src/gpu/metal/command.rs: 1 MTLCommandBuffer across all blit/compute/render passes
enum ActiveEncoder {
None,
Render(Retained<ProtocolObject<dyn MTLRenderCommandEncoder>>, RenderStateCache),
Compute(Retained<ProtocolObject<dyn MTLComputeCommandEncoder>>, ComputeStateCache),
Blit(Retained<ProtocolObject<dyn MTLBlitCommandEncoder>>),
}
pub(crate) struct MetalEncoder {
cmd_buf: Mutex<Option<Retained<ProtocolObject<dyn MTLCommandBuffer>>>>,
active: Mutex<ActiveEncoder>,
}
impl wgpu::custom::CommandEncoderInterface for MetalEncoder {
fn begin_render_pass(&self, desc: &wgpu::RenderPassDescriptor<'_>) -> DispatchRenderPass {
let cb = self.ensure_cmd_buf();
self.end_active_encoder(); // closes Blit/Compute without closing MTLCommandBuffer
DispatchRenderPass::custom(MetalRenderPass::open(&cb, desc))
}
// begin_compute_pass and copy_* switch ActiveEncoder on the same MTLCommandBuffer.
}
impl MetalQueue {
/// Window and overlay path: 1 command buffer, presentDrawable on it, MTLSharedEvent fence,
/// and 0 RcBlock completion handlers unless map_async / on_submitted_work_done registered one.
pub(crate) fn submit_presenting(&self, encoder: wgpu::CommandEncoder, frame: MetalDrawable) -> u64 {
let (cmd_buf, callbacks) = self.finish_custom(encoder);
let ticket = self.next_ticket.fetch_add(1, Ordering::Relaxed) + 1;
cmd_buf.encodeSignalEvent_value(&self.shared_event, ticket); // GPU counter, no ObjC block
if !callbacks.is_empty() { self.arm_event_listener(ticket, callbacks); }
if !frame.presents_with_transaction {
cmd_buf.presentDrawable(&frame.drawable);
cmd_buf.commit();
} else {
cmd_buf.commit();
cmd_buf.waitUntilScheduled();
frame.drawable.present();
}
self.retire_completed(self.shared_event.signaledValue());
ticket
}
}
```
How every existing subsystem keeps working without signature changes:
- **`Compositor` and `Frame` (`crates/rune/src/compose.rs`):** `Frame` still hands callers
`&wgpu::Device`, `&wgpu::Queue`, `&mut wgpu::CommandEncoder` and `&wgpu::TextureView`. App
compositors (`overlay_hud_cost`, `lab`, `cursed-settings`, `rune-fx`, `rune-light`) record
straight into `MetalEncoder`'s single `MTLCommandBuffer` through `wgpu::custom`.
- **Uploads (`Uploads` and `rune-staging`):** On Apple unified memory, `Renderer` and
`Frame::write_buffer` allocate from a triple-buffered `MTLStorageModeShared` ring retired by
`shared_event.signaledValue()`, copying bytes directly into `MTLBuffer.contents()` and binding
offsets with zero `MTLBlitCommandEncoder`s and zero `map_async` callbacks. Glyph and image
atlas row updates record `copyFromBuffer:toTexture:` on the frame's `MTLCommandBuffer` ahead
of the first render pass without closing the command buffer.
- **Video (`native_surface/macos.rs`) and AppKit (`macos.rs`, `present_time.rs`,
`system_material`):** `MetalDevice::import_cv_pixel_buffer` wraps `CVMetalTextureGetTexture`
directly via `wgpu::Texture::from_custom` (retaining `CVMetalTexture` + `PixelBuffer` in the
custom texture's `Drop`), and `MetalSurface::layer()` exposes `&CAMetalLayer` without
`wgpu-hal` or `wgpu-core`.
- **Headless tests & CI:** `Gpu::headless()` uses `MetalInstance` on macOS (1 `MTLCommandBuffer`
+ `MTLBlitCommandEncoder` readback to a shared `MTLBuffer`) and `wgpu` Vulkan/Lavapipe on
Linux CI. Setting `RUNE_GPU_BACKEND=wgpu` switches macOS back to `wgpu-core` for differential
pixel and timing checks in the same binary.
## 4. Phased plan and measurable gates
### Parallel track: upstream three small fixes to `gfx-rs/wgpu` (~120 LOC, non-blocking)
Fix the three bugs in `wgpu-hal-metal-lazy-command-buffer.patch` (decrement the counter when
dropping an unsubmitted `raw: None` `CommandBuffer`, preserve user command buffer labels on
signal, latch `relay.next_release_value` in `begin_encoding`), pair it with
`wgpu-core-present-skip.patch` and a `fid` cleanup on failed `surface_get_current_texture`
(`wgpu-core/src/present.rs:449`), and submit PRs with hand-written descriptions per `wgpu`'s
contribution policy. Do not block Rune on upstream review or carry a `[patch.crates-io]` fork;
once merged into a `wgpu` point release, Windows DX12 and Linux Vulkan gain single-submit
presentation automatically.
### Phase 0: First spike (≤ 450 LOC, ≤ 1 day), single-CB `wgpu::custom` Metal + Naga MSL
The two riskiest assumptions are (1) that `wgpu::custom` over `objc2-metal` + `MTLSharedEvent`
runs `overlay_hud_cost` unchanged with 1 command buffer, 0 completion handlers and 0 blit
encoders (eliminating both the empty-CB tax and the +310 kinstr upload tax), and (2) that
standalone `wgpu::naga` (`wgsl` → `process_overrides` → `msl`) compiles every WGSL shader in
`rune`, `rune-fx` and `rune-light` (`_mslBufferSizes`, `override`s, atomics, MRT) cleanly.
1. **Build `crates/rune/src/gpu/metal_spike.rs` (~380 LOC, gated on `RUNE_GPU_BACKEND=metal`):**
implement minimal `InstanceInterface`, `SurfaceInterface` (`CAMetalLayer::nextDrawable`),
`DeviceInterface`, `BufferInterface` (`MTLStorageModeShared` direct write),
`CommandEncoderInterface`, `RenderPassInterface`, and `MetalQueue::submit_presenting`
(`presentDrawable` + `MTLSharedEvent`, 0 `RcBlock`s).
2. **Add a standalone Naga→MSL compile test (~60 LOC):** translate all 29 WGSL shaders (with
`layer_blur` override specializations and `rune-light`/`gpu_springs` storage-buffer size
slots) and compile each via `MTLDevice::newLibraryWithSource`.
3. **Exact measurement (`--profile perf`, real HUD window on a dedicated test Mac, 4 alternating
10 s rounds after 2 s warmup, `OVERLAY_WRITES=0` and `OVERLAY_WRITES=1`):**
- **Go gate:** `OVERLAY_COUNT_METAL=1` reports `command_buffers=1.00`, `presents=1.00`,
`completed_handlers=0.00`, `blit_encoders=0.00` on both `WRITES=0` and `WRITES=1`;
`WRITES=0` lands within ≤ +40 kinstr/frame (≤ +0.5 CPU percentage points) of
`metal_hud.swift` once paired with the overlay-loop fixes (or ≤ 960 kinstr before them,
≥ 595 kinstr below today's 1,555k); `WRITES=1` adds ≤ 15 kinstr/frame over `WRITES=0`
(down from +310–323 kinstr today); all 29 WGSL shaders compile to `MTLLibrary`.
- **Kill / pivot gate:** if `wgpu::custom` blocks a required `wgpu` handle operation or adds
`> 25 kinstr/frame` of dispatch overhead, keep the Metal backend and swap the `wgpu::custom`
shim for an internal `gpu::Encoder` enum (`Metal | Wgpu`). If single-CB Metal itself fails
to beat patched `wgpu` by `≥ 180 kinstr` on `WRITES=0` and `≥ 400 kinstr` on `WRITES=1`,
abandon owning Metal and ship only the upstream `wgpu` patches.
### Phase 1: Core Metal backend, unified-memory upload ring and window/overlay integration (~1,500 LOC)
- Implement full 2D textures, sRGB/linear views, mip views, samplers, MRT render passes (up to 4
color attachments), dynamic uniform offsets, state deduplication, blit copies (`buf↔tex`,
`tex↔tex`, headless `tex→buf` readback), and `MTLSharedEvent` deferred-free resource
retirement (`Vec<(u64, Vec<Retained<AnyObject>>)>`).
- Wire `Uploads` and `Frame::write_buffer` on Metal to a bounded `MTLStorageModeShared` ring (no
staging copy or `map_async`), encode dirty glyph/image atlas blits onto the frame's single
`MTLCommandBuffer` without closing it, fold `submit + present` in `window/draw.rs` and
`overlay/frame.rs`, and skip spawning `PresentWorker` when running on `MetalQueue`.
- **Gate:** `cargo test -p rune -p rune-kit --features rune-kit/markdown` green on
`RUNE_GPU_BACKEND=metal`; `scripts/check-reference.sh` (`rune-ref`) and CoreText golden tests
match `wgpu` pixel-for-pixel; `scripts/motion-audit` passes with a HUD/scroll scenario added;
`upload_bench --profile perf` drops `steady` `54 µs → ≤ 15 µs` and `scroll` `83 µs → ≤ 22 µs`
with `0` buffer allocations/frame; `bench-ui.py --frame-cpu --scroll` + window present trace
commits `1.00` command buffer/frame and cuts total main+driver scroll CPU by `≥ 120 µs/frame`.
### Phase 2: Compute, timestamps, `rune-fx`/`rune-light`, `IOSurface` video and `as_hal` removal (~900 LOC, −350 LOC deleted)
- Add `MTLComputePipelineState`, `MTLComputeCommandEncoder` (switching cleanly inside the same
`MTLCommandBuffer`), `_mslBufferSizes` sideband `setVertexBytes`/`setFragmentBytes`/`setBytes`,
and `MTLCounterSampleBuffer` timestamp queries (`resolve_query_set`).
- Move `macos.rs`, `present_time.rs`, `system_material/macos.rs` and `native_surface/macos.rs`
(`CVMetalTextureCache` zero-copy BGRA/NV12 import) onto `MetalSurface` / `MetalDevice`
directly; make `RUNE_GPU_BACKEND=metal` the default on `macOS` and `iOS` and gate `wgpu`'s
`metal` feature + `wgpu-hal`/`wgpu-core` behind an optional `wgpu-metal-fallback` dev/debug
feature.
- **Gate:** `rune-fx` and `rune-light` test suites and `video_gui` pass (`live_planes == 0` on
drop); `frame_bench --profile perf` (including `finish + submit`) commits 1.00
`MTLCommandBuffer`/frame across all 10+ GI and glass passes (down from 16–24), cutting
multi-pass submit+driver CPU by `≥ 60%`; `layout_text_cost` shows 0% regression;
`scripts/file-size.sh` passes with every new file under 800 non-test lines.
### Phase 3: Build-time `.metallib` bundle for all shaders + `MTLBinaryArchive` cache (~450 LOC)
- Extend `scripts/precompile-metal-shaders.sh` to run Naga (`wgsl` → `process_overrides` →
`msl`) and `xcrun metal` for `macos`, `ios` and `ios-simulator` across all library shaders
(`uber` + `gpu_springs`, `backdrop_blur`, `layer_blur`'s 5 specializations, `video`,
`rune-fx`'s 13 modules, `rune-light`'s 7 modules), embedding `.metallib` bytecode plus compact
`sized_bindings` tables (falling back to runtime Naga WGSL only for custom app shaders).
- Add a bounded on-disk `MTLBinaryArchive` keyed by `(OS build, GPU name, ABI hash)` so pipeline
creation hits cached GPU ISA after first launch.
- **Gate:** cold pipeline init for `Renderer` + `FxRenderer` + `LightRenderer` drops `≥ 3×`
(`≤ 80 ms` cold AIR, `≤ 15 ms` warm archive); `scripts/bench-startup.py` `first-pixels` median
beats or matches baseline; `.metallib` freshness and pixel-equivalence tests pass across
`rune`, `rune-fx` and `rune-light`.
#### Done: every built-in pipeline precompiled (native backend, macOS and iOS)
`gpu/metal/builtin.rs` looks up each pipeline's function in `builtin_native.metallib` before it
calls naga. The key hashes everything that decides naga's MSL: the WGSL, stage, entry point,
override constants, runtime checks, point size, and the slots *this pipeline's layout* hands out.
So a precompiled function binds exactly what the runtime path would give it, and a table row
carries the sized bindings and the workgroup size. A module whose WGSL is built in isn't parsed
unless a pipeline misses the table. `scripts/precompile-metal-shaders.sh` captures the MSL
(`RUNE_METAL_CAPTURE`) from rune-light's `builtin_shaders` test, which builds every pipeline,
and compiles it for macOS, iOS and the iOS simulator: 60 pipelines, 53 distinct functions, each
in its own namespace. The capture builds the uber shader from WGSL too, since iOS has no
`uber_native.metallib`.
The same test fails on a miss, so a shader edit without a regenerate shows up there. App shaders
miss the table and compile at runtime as before.
Measured with `shader_first_use` (`--profile perf`, fresh processes, 10 alternating rounds,
medians, M-class MacBook Pro). Cold means `com.apple.metal` was cleared before the run:
| First use | Cold, runtime MSL | Cold, precompiled | Warm, runtime | Warm, precompiled |
|---|---|---|---|---|
| `Renderer::new` (uber, already precompiled) | 110 ms | 114 ms | 1.2 ms | 1.3 ms |
| backdrop blur + composite | 394 ms | 29 ms | 2.2 ms | 0.7 ms |
| layer blur (5 specializations) | 727 ms | 45 ms | 1.6 ms | 0.2 ms |
| video | 201 ms | 22 ms | 1.1 ms | 0.2 ms |
| transparent window (straight alpha) | 87 ms | 5 ms | 0.2 ms | 0.1 ms |
| `Renderer::with_springs` | 305 ms | 81 ms | 3.3 ms | 0.2 ms |
| `FxRenderer::new` (before lazy pipelines, below) | 3,627 ms | 1,260 ms | 32.5 ms | 1.2 ms |
| `FxRenderer::add_format` (likewise) | 1,283 ms | 1,263 ms | 15.1 ms | 0.8 ms |
| fire simulation | 1,207 ms | 101 ms | 2.0 ms | 0.2 ms |
| `LightRenderer::new` | 1,389 ms | 127 ms | 5.7 ms | 0.6 ms |
| `GlassRenderer::new` | 392 ms | 126 ms | 6.0 ms | 4.0 ms |
Most of a cold pipeline is Metal's front end (MSL to AIR). Clearing only Metal's library cache
cost a first layer blur 555 ms, and clearing only its function cache cost 45 ms. What remains is
GPU code generation, which the precompiled library can't skip. That's why `add_format`, the same
fx functions for another format, stayed at 1.26 s cold (until rune-fx stopped building pipelines it
hadn't drawn, below). 1,669 readbacks across the rune, rune-fx
and rune-light tests were byte-identical with the library on and off. `settings` first pixels
didn't change (it builds only the uber pipeline).
Cost: 539 KB in the binary (`settings` stripped: 17.37 → 17.90 MB). The library compresses to
235 KB with deflate, which macOS's Compression framework could decode in about a millisecond.
That's left for later. naga stays in every binary: its WGSL front end, validator and MSL back end
are about 1.3 MB of `settings`' 11.2 MB of code, and both wgpu's backend in the same binary and
app shaders need them. The wgpu backend doesn't use the library.
On the iOS 27 simulator (same Mac, 6 alternating rounds for `shader_first_use`, 8 for
`embed_cost`, medians; cold clears the simulator's and the host's `com.apple.metal`), the
precompiled library also covers the uber shader, which compiled at runtime there before:
| First use, iOS simulator | Cold, runtime MSL | Cold, precompiled | Warm, runtime | Warm, precompiled |
|---|---|---|---|---|
| `embed_cost` first frame | 430 ms | 243 ms | 35.0 ms | 31.6 ms |
| `Renderer::new` (uber) | 390 ms | 194 ms | 5.9 ms | 2.6 ms |
| layer blur | 723 ms | 10 ms | 3.4 ms | 1.3 ms |
| `FxRenderer::new` | 2,098 ms | 85 ms | 40.7 ms | 5.2 ms |
| `LightRenderer::new` | 1,254 ms | 27 ms | 9.5 ms | 1.9 ms |
| every built-in pipeline | 6,631 ms | 440 ms | 102 ms | 18 ms |
The device library (`builtin_native_ios.metallib`) compiles from the same MSL but hasn't run on
a phone yet.
#### Done: rune-fx builds a pipeline the first time a frame draws it
`FxRenderer::new` built every effect family (8) in both blends (16 pipelines), plus the mask
pyramid's and the backdrop blur's three, serially on the calling thread, and `add_format` built the
16 again for each extra format, whether or not the app ever drew those effects. After the library,
what's left of a cold pipeline is GPU code generation, and none of it is shared: per pipeline, on a
cold cache, glow 35 ms, pulse 31, electric 38, fire 74, distort 61, motion 21, extras 39 and fill
152, and the screen blend and the `Rgba16Float` format each cost as much again as the first, since
Apple GPUs blend in the fragment shader and each format is its own variant. Serially that's
937 ms per format.
Now each `(format, family, blend)` pipeline sits in a `OnceLock` and is built when a frame first
needs it. `prepare` builds the ones its layers use for the frame's format, in parallel (scoped
threads; Metal compiles concurrently, and wgpu's `Device` is `Send + Sync`), and a draw into
another format builds its own on demand. The mask pyramid and backdrop blur passes wait for
`build_mips` and the first frosted layer. The keys the precompiled library looks up don't change,
so `builtin_shaders` (which now calls `FxRenderer::build_every_pipeline`) still finds all of them.
Measured with `crates/rune-fx/examples/first_glow.rs` (`--profile perf`, fresh processes,
10 alternating rounds, medians, an M4 Pro Mac mini, native Metal backend with the library): new
renderer, `add_format(Rgba16Float)`, then prepare, draw, submit and read back one glow.
| First glow | Cold, before | Cold, after | Warm, before | Warm, after |
|---|---|---|---|---|
| `FxRenderer::new` | 919 ms | 0.14 ms | 1.47 ms | 0.10 ms |
| `FxRenderer::add_format` | 865 ms | 0.00 ms | 0.67 ms | 0.00 ms |
| first frame (prepare, draw, read back) | 5.8 ms | 70.7 ms | 5.6 ms | 6.1 ms |
| **total, `new` to pixels** | **1,799 ms** | **70.9 ms** | **7.9 ms** | **6.2 ms** |
About half of the 70 ms is a fresh process's first pipeline warming Metal's compiler up; after a
`Renderer::new` (as in an app) the same glow pipeline takes 40 to 50 ms cold. All 35 pipelines at
once (`shader_first_use`'s `fx_every_pipeline`, both formats, in parallel) take 410 ms cold against
1,796 ms for `new` plus `add_format` before; 16 pipelines on 16 threads take 217 ms, on 4 threads
332 ms, serially 937 ms.
- **Considered: compile everything in the background at `new` and wait only at first draw.** The
glow is ready just as fast (70 ms, it goes first), but it spends about 930 ms of compiler time
per format on effects an app may never show, competing with its launch.
- **Considered: skip an effect until its pipeline is ready.** No frame would wait, but the first
frame would draw without the effect and then pop it in, and readbacks of a first frame would
change.
- **Not split: the two blend states.** Screen blending (`One, OneMinusSrc`) needs the destination,
which only fixed-function blending gives without a backdrop copy, so it stays its own pipeline,
built only when a `FxBlend::Screen` slot draws.
#### Considered, not done: `MTLBinaryArchive`
Measured on the native backend after step 4, on an M2-class Mac, with fresh processes and medians
of 10 alternating runs. `Renderer::new` builds one uber pipeline per format, and that one pipeline
is the whole cold cost: 89 ms with macOS's per-app shader cache cleared, 0.94 ms warm.
- **Runtime archive, written by the app:** cold drops to 13.7 ms (9.2 ms of that is loading the
archive), but warm rises to 6.1 ms (5.2 ms load), and a first run that writes the archive costs
+38 ms. It only helps when macOS's cache is cold but ours is valid. macOS's cache survives
reboots, and the cases that empty it (first launch, OS or GPU driver update, shader change) also
leave our archive empty or stale. Archive hits don't refill macOS's cache, and
`FailOnBinaryArchiveMiss` doesn't count macOS's cache, so we can't tell when to skip it.
`MTLBinaryArchive.h` also advises against writing archives at runtime in shipping apps.
- **Shipped archive, built offline with `metal-tt`** for its 18 default Apple GPU variants: 1.12 MB
for the windowed format alone, 2.63 MB for Rune's four formats. One-pipeline builds were
byte-identical, but four-pipeline builds came out different on each of five runs. `xz -9`
shrinks the variants to about 56 KB per format (60 KB for all four together), so per-format
compressed archives would add about 225 KB, at the cost of first-launch decompression, a marker
file and a background recompile to fill macOS's cache. That's too much for about 75 ms once per
install or OS update.
- **Revisit if:** cold first launch becomes a measured complaint, `metal-tt` output becomes
deterministic, Apple shrinks offline archives, or many more pipelines move onto the startup path
and make the cold cost much larger.
## 5. Triggers to expand or abandon
- **Abandon / roll back to `wgpu` + upstream patches** if: (a) Phase 0 misses its kill gate,
(b) `crates/rune/src/gpu/metal/` exceeds 3,500 non-test LOC, or (c) Metal backend parity
causes `> 2` pixel or pacing regressions in a quarter once Phase 2 ships (`RUNE_GPU_BACKEND=wgpu`
provides an immediate fallback before `wgpu-metal-fallback` is ever removed).
- **Expand to an owned Windows DX12 backend (~3.5–4.5 kLOC)** only if, after upstream
`present-skip` ships and [32](32-engine-plan.md) Phases 1–3 land: (a) a real Windows 120 Hz
HUD or scrolling app spends ≥ 25% of frame CPU and ≥ 0.35 ms/frame inside
`wgpu_core`/`wgpu_hal::dx12`, and (b) every library shader precompiles offline to signed DXIL
so Rune never ships `dxcompiler.dll` (~20 MB) at runtime.
- **Never own WebGPU** (`wgpu` on `wasm32` already compiles straight to browser WebGPU bindings
without `wgpu-core`), and **do not own Linux Vulkan** unless `wgpu-core` exceeds 0.50 ms/frame
(> 30%) on a 120 Hz Wayland layer-shell workload after `present-skip` and a targeted upstream
`wgpu-hal/vulkan` patch cannot fix it.
## Spike results (Phase 0)
Code: `crates/rune/src/gpu_metal/` behind the `metal-spike` cargo feature and
`RUNE_GPU_BACKEND=metal` at run time; wgpu stays the default, and a build without the feature
compiles none of it. About 600 lines of backend (half of it `wgpu::custom` trait stubs), a
285-line shader test and a 90-line dispatch benchmark (`examples/metal_spike_dispatch.rs`).
A frame through it: `nextDrawable` after waiting on an `MTLSharedEvent` counter if two frames
are in flight; the encoder makes one `MTLCommandBuffer` (`commandBufferWithUnretainedReferences`)
on its first render pass; `Queue::submit` holds a buffer that drew into the drawable;
`Queue::present` calls `presentDrawable` on that buffer, signals the event and commits.
`Queue::write_buffer` copies straight into `MTLStorageModeShared` memory. The overlay's
`submit_and_present` skips `PresentWorker` on this backend. No completion handlers.
### Verdict
| Gate | Result | |
| --- | --- | --- |
| 1 CB, 1 present, 0 handlers, 0 blits at `WRITES=0` and `1` | 1.00, 1.00, 0.00, 0.00 at both | go |
| `WRITES=0` ≤ 960 kinstr/frame | 894 | go |
| `WRITES=1` adds ≤ 15 kinstr/frame | +3 | go |
| 29/29 WGSL shaders compile to `MTLLibrary` | 29/29 (79 libraries) | go |
| `wgpu::custom` adds ≤ 25 kinstr/frame | +3.3 to +3.9 | no pivot |
| Beats patched wgpu by ≥ 180 at `WRITES=0` | by 143 | **miss** |
| Beats patched wgpu by ≥ 400 at `WRITES=1` | by 487 | go |
| `WRITES=0` within +40 of `metal_hud.swift` (after the loop fixes) | +86, without them | not tested |
The kill gate is split. With no buffer writes, owning Metal saves 143 kinstr/frame (14%) over
wgpu with both upstream patches, short of 180. With one write a frame it saves 487 (35%),
because wgpu's write path still costs about +347 kinstr (a staging buffer, a blit encoder and a
command buffer) and the direct write costs 3. Both baselines are lower on this Mac than in
[30](30-overlay-gpu-cost.md) (patched 1,037 here vs 1,118; plain wgpu 1,395 vs 1,555; Swift
808 vs 850), so the absolute margins moved with them.
What decides it: an app that writes any buffer per frame (every real HUD writes at least its
uniforms) sees the 487 saving, and an idle-clear HUD sees 143. Shipping the two wgpu patches
upstream gets the first ~358 kinstr either way.
### Overlay HUD, per frame
`overlay_hud_cost --profile perf`, real 360×80 overlay on an M2 Max MacBook Pro's built-in
120 Hz display (macOS 27.0.1, screen unlocked and awake), 4 alternating rounds of 10 s after a
2 s warmup, medians of the middle two. `queue.write_buffer` for writes (`OVERLAY_STAGED` unset).
Without `perf/overlay-rune-cost`. Patched wgpu is 30.0.1 with both `research/overlay-cpu/`
patches through `--config patch.crates-io`. The Swift HUD has no write option, so it shows once.
| | Metal spike | wgpu | wgpu, patched | `metal_hud.swift` |
| --- | ---: | ---: | ---: | ---: |
| Kinstructions, `WRITES=0` | **894** | 1,395 | 1,037 | 808 |
| Kinstructions, `WRITES=1` | **897** | 1,668 | 1,384 | – |
| Process CPU, `WRITES=0` | 6.7% | 9.4% | 7.5% | 6.3% |
| Process CPU, `WRITES=1` | 6.6% | 10.9% | 10.1% | – |
| Heap allocations, `WRITES=0` / `1` | 7.1 / 7.1 | 65.1 / 73.1 | 55.1 / 64.1 | – |
| Command buffers, `WRITES=0` / `1` | 1 / 1 | 6 / 7 | 2 / 3 | 1 |
| Completion handlers | 0 / 0 | 2 / 2 | 1 / 1 | 0 |
| Blit encoders | 0 / 0 | 0 / 1 | 0 / 1 | 0 |
Rounds, kinstr/frame: Metal 883, 903, 895, 894 and 900, 906, 895, 892; wgpu 1,396, 1,393,
1,397, 1,379 and 1,652, 1,710, 1,665, 1,670; patched 1,038, 1,042, 1,037, 1,037 and 1,383,
1,382, 1,385, 1,388; Swift 814, 806, 802, 811. Counts come from separate 8 s runs with
`OVERLAY_COUNT_METAL=1`, whose swizzles add instructions.
CPU by thread, ms per second, `WRITES=0` (`WRITES=1`):
| | Main | Present thread | Display link | Driver and the rest | Total |
| --- | ---: | ---: | ---: | ---: | ---: |
| Metal spike | 18.3 (17.8) | – | 2.0 (2.0) | 46.6 (46.4) | 66.9 (66.2) |
| wgpu | 14.4 (21.0) | 15.6 (17.2) | 1.9 (2.0) | 61.0 (68.7) | 94.3 (109.1) |
| wgpu, patched | 13.9 (22.2) | 11.9 (15.1) | 1.9 (2.0) | 47.4 (61.3) | 74.7 (101.2) |
| `metal_hud.swift` | 1.8 | – | 11.3 (draws here) | 50.7 | 63.4 |
The main thread does more on Metal (about +4 ms/s) because it now encodes, commits and
presents itself instead of handing the frame to the present thread; the compositor callback
grows from ~4 µs to ~35 µs because the render pass is encoded there rather than replayed at
submit. The remaining 86 kinstr over Swift is Rune's own loop (step, `about_to_wait`, acquire),
which `perf/overlay-rune-cost` targets.
### `wgpu::custom`
`examples/metal_spike_dispatch.rs`, offscreen, the HUD frame through wgpu's API into the
custom backend against the same Metal calls made directly, 3,000 frames × 4 alternating rounds:
| | Through `wgpu::custom` | Direct | Added |
| --- | ---: | ---: | ---: |
| `WRITES=0` | 213.9 | 210.6 | 3.3 |
| `WRITES=1` | 214.9 | 211.1 | 3.8 |
Under the 25-kinstr pivot line, so the spike stays on `wgpu::custom`. What it could express:
the whole overlay frame unchanged, including holding a command buffer from `submit` to
`present` so the drawable presents on it, direct buffer writes, `map_async` that completes at
once, and adapter, surface and capability queries Rune's attach path makes. What it can't, or
what costs:
- `Surface::as_hal` and `Device::as_hal` return `None` for a custom backend, so every macOS
helper that reaches the CAMetalLayer through them silently does nothing: the occlusion check,
`PresumeShown`, `present_with_transaction`, present timing, system materials, and
`NativeSurface` errors. Phase 2's move of these onto the backend is required, not optional.
- The traits are about 150 methods across 30 interfaces; a backend implements them all, and
most of the spike's are stubs (`unimplemented!` for compute, ray tracing, bundles and
external textures; inert shader modules, pipelines, bind groups and samplers).
- `Frame::write_buffer` (`rune-staging`) writes a mapped staging buffer and records a
`copy_buffer_to_buffer`; the spike drops copies, so that path is wrong here. A real backend
should let staging write straight into a shared destination.
- The `custom` feature adds a variant to every wgpu dispatch enum in any build that enables it;
its cost on the wgpu path wasn't measured (the wgpu baselines were built without it).
### Shaders
`gpu_metal/shader_tests.rs` composes each of the 29 WGSL files as its crate does (clip and
common prefixes, gi, glass and reel sections, `layer_blur`'s 5 override pairs), then for each
entry point runs naga `process_overrides` → `msl::write_string` with wgpu-hal's Metal options
(MSL 4.0 on macOS 26+, Restrict bounds checks, loop bounding, zero-initialized workgroup
memory, vertex pulling with a buffer at slot 30, per-entry resource slots with a sizes buffer)
and `newLibraryWithSource` with preserve-invariance. All 29 files compile in every module they
are part of: 31 modules, 79 libraries, 2.3 s in a debug build. No failures.
What the test doesn't prove: resource slots come from the module's own bindings rather than each
pipeline's layout, and vertex inputs are packed into one buffer, so the MSL matches wgpu-hal's
shape but not each pipeline's exact strides.
### Limits of the spike
- It clears and presents; draws, pipelines and bind groups are inert. The HUD and its empty
Rune view need nothing more, so the measured frame is complete, but drawing cost is untested.
- A direct write can race a frame still on the GPU that reads the same buffer. Phase 1's ring
is needed for correctness, and will add a little to `WRITES=1`.
- The layer's scale is set once at creation and doesn't follow a display change.
## Memory: Metal vs wgpu
One app reported, from single unpaired runs, a headless footprint of about 330 MB on the Metal
backend against 1.5 to 1.6 GB on wgpu. Paired and alternating runs of one `--profile perf` binary
(`--features rune/metal-backend`, `RUNE_GPU_BACKEND=metal` or `wgpu`), five pairs each, medians.
Footprint is `phys_footprint` (`footprint`, `time -l` for the peak); RSS from `ps` or `time -l`.
Headless is `long_note --gpu --only scroll --sizes 200 --samples 300` (a 200 KB note scrolled
top to bottom, 785 frames, drawn on a headless GPU). Windows are real, on an M2 Max MacBook Pro
(macOS 27.0.1, unlocked, awake): `hello` idle after 5 s, and `window_scroll_cost` (60 sections of
text rows, scrolling at 600 pt/s) sampled at 7 s, about 400 frames in.
| Case | Backend | Footprint | RSS | Peak footprint |
| --- | --- | ---: | ---: | ---: |
| Headless, Mac mini (M4 Pro) | wgpu | – | 49.1 MB | 278.1 MB |
| | Metal | – | 46.3 MB | 276.7 MB |
| Headless, MacBook Pro (M2 Max) | wgpu | – | 47.6 MB | 58.0 MB |
| | Metal | – | 44.7 MB | 57.8 MB |
| Window idle, 5 s | wgpu | 34 MB | 95.1 MB | 41.5 MB |
| | Metal | 33 MB | 92.5 MB | 39.7 MB |
| Window scrolling, 7 s | wgpu | 68 MB | 104.1 MB | 67.5 MB |
| | Metal | 74 MB | 101.1 MB | 74.2 MB |
**The claim does not hold in these workloads.** The two backends are within a few MB of each
other everywhere, and neither gets near 330 MB, let alone 1.5 GB. Metal has about 3 MB less RSS;
in the scrolling window it has about 6 MB more footprint. I sampled only at 7 s, so growth over a longer run is
not ruled out.
**Where the reported gap most likely came from: an unpaced headless run.** A later headless
scroll benchmark that submits frames as fast as it can (about 1,650 a second, 900 frames)
reproduced it: 325 MB footprint on Metal against 1,956 MB on wgpu. The GPU can't keep up at that
rate, so both runs take the same 0.55 s. Rune's Metal queue keeps Apple's default limit of 64
command buffers in flight and blocks the next one at the start of encode. wgpu allows 2,048, so
it never blocks and gets hundreds of frames ahead, each holding its own buffers. A window paces
frames to the display, so neither queue fills there, which matches the tables above. The same
wait is why such a run reports a higher `encode_ms` on Metal (0.35 ms against 0.19) while its
frame CPU is lower (0.27 to 0.30 ms against 0.38). `encode_ms` is elapsed time, so in an unpaced
run it mostly measures how far behind the GPU is; compare backends there with `thread_cpu_ms` or
`cpu_ms`.
Where the footprint goes (`footprint` by category, one run each):
| Category | wgpu idle | Metal idle | wgpu scrolling | Metal scrolling |
| --- | ---: | ---: | ---: | ---: |
| IOSurface (the layer's drawables) | 5.6 MB | 5.6 MB | 22 MB | 22 MB |
| IOAccelerator (graphics), dirty | 1.1 MB | 1.2 MB | 4.4 MB | 6.6 MB |
| Owned physical footprint (graphics) | 6.2 MB | 5.6 MB | 7.6 MB | 9.6 MB |
| Malloc small | 12 MB | 11 MB | 20 MB | 19 MB |
The wgpu#10494 growth (about 2.3 MiB of IOAccelerator memory per command buffer, held until the
buffers are collected) does not show: wgpu's IOAccelerator is no larger than Metal's after
hundreds of frames. The 6 MB scrolling difference is IOAccelerator and graphics-owned memory,
likely the Metal backend's own pooled buffers and the drawable it keeps in flight, and I did not
chase it further.
So a gap of 1 GB or more is not something the backend alone produces. It must come from what that
app draws or keeps: large images or atlases, offscreen targets, or buffers that wgpu keeps alive
and the Metal backend frees or never makes. To attribute it, run that app's own headless frames
under both backends with `footprint --by-category` and `vmmap --summary`, and compare
IOAccelerator, IOSurface and Malloc. Not measured here: an app with image-heavy views, effects
or many windows, and a long idle run.
+222
View File
@@ -0,0 +1,222 @@
# 35. What wgpu costs a Rune frame on Vulkan and DX12
Reader: someone deciding whether Rune should own its Vulkan and DX12 backends, as
[34](34-own-gpu-plan.md) decided for Metal. Question: per frame, what does `wgpu` 30.0.1 cost on
Linux (Vulkan) and Windows (DX12) compared with the same frame written against the raw API, and how
much of that does the upstream present-skip patch already remove?
**Answer: a native backend would save about 70k instructions and 0.06 to 0.09 ms of CPU per window
frame, under 1.1% of a 120 Hz frame.** The present-skip patch takes about a quarter of the
instructions and, on Vulkan, more than half of the time, because it removes a whole
`vkQueueSubmit`. On a normal window frame, where Rune's own work dominates, `wgpu` and the driver
are about 10% of the renderer's instructions. That backs [34](34-own-gpu-plan.md): keep `wgpu` on
Vulkan and DX12 and land the patch upstream. A 15 to 20 kLOC backend buys less than 0.1 ms a frame.
All numbers come from software drivers (Mesa lavapipe, and vkd3d on top of it under Wine), so
driver instructions and every time below hold only for software drivers. API call counts, and the
instructions spent in `wgpu`, `wgpu-core` and `wgpu-hal`, don't depend on the GPU.
## Setup
- 8-vCPU AMD EPYC 9554P (Zen 4) VM, Ubuntu 24.04, no GPU. Mesa 25.2.8 lavapipe (Vulkan 1.4), Xvfb
with no vsync, so frames run uncapped.
- DX12: the same probe binaries cross-compiled to `x86_64-pc-windows-gnu` and run under Wine 9.0,
whose `d3d12.dll` is vkd3d over lavapipe. Every D3D12 call is translated to Vulkan, so DX12
instructions include the translation.
- `wgpu` 30.0.1 with `vulkan` and `dx12`, as Rune builds it off Apple. "Patched" adds
`research/overlay-cpu/wgpu-core-present-skip.patch`.
- Workloads:
- `overlay_hud_cost` ([30](30-overlay-gpu-cost.md)): Rune's real overlay. Its compositor clears
a 360×80 drawable in one pass, with `OVERLAY_WRITES=0` or `1` queue writes per frame.
- `research/gpu-floor` (built from that directory, outside the workspace):
- `wgpu_frame`: the same frame through bare `wgpu` (acquire, `create_view`, N 256-byte
`Queue::write_buffer`s, one cleared pass, submit, present).
- `vk_floor` (ash) and `dx12_floor` (`windows`): that frame with the fewest calls each API
allows. `UPLOAD=mapped` writes the uniform into a persistently mapped ring with no API call.
`UPLOAD=copy` stages it and records a copy plus one barrier, as a discrete GPU needs.
- `upload_bench` (steady and scroll): a headless window-sized renderer frame
(`Renderer::prepare`, `draw`, `submit`, with no surface), standing in for a normal window.
- Instructions per frame are for the drawing thread only. Lavapipe rasterizes on its own threads,
and on real hardware that work is the GPU's, so those threads are left out.
- Callgrind collects only inside the frame function, Rune's `Compositor::render` or Rune's
renderer calls. `research/gpu-floor/cgsplit.py` then splits the counts by crate and
library, charging `std` and allocator code to its caller.
- `perf_event` instruction counters and `CLOCK_THREAD_CPUTIME_ID` give the user, kernel and CPU
time numbers: medians of 5 alternating rounds of 4,000 frames.
- Barriers were classified with a logging build of `wgpu-hal`
(`research/gpu-floor/wgpu-hal-log-barriers.patch`) on Vulkan and with vkd3d's trace log on
DX12.
## Vulkan, per frame
| HUD frame, 0 writes (1 write) | wgpu today | wgpu patched | Native floor |
| --- | ---: | ---: | ---: |
| `vkQueueSubmit` | 2 (2) | 1 (1) | 1 (1) |
| Command buffers begun and ended | 5 (6) | 4 (5) | 1 (1) |
| `vkResetCommandPool` | 2 (3) | 1 (2) | 1 (1) |
| `vkCmdPipelineBarrier` calls | 4 (5) | 2 (3) | 0 (copy: 1) |
| Barriers, of which no-ops | 4, 2 (6, 3) | 2, 0 (4, 1) | 0 (copy: 1, 0) |
| Image views created and destroyed | 2 (2) | 2 (2) | 0 |
| Framebuffers created and destroyed | 1 (1) | 1 (1) | 0 |
| Buffers created, bound, destroyed | 0 (1) | 0 (1) | 0 |
| Host semaphore or fence calls | 2 (2) | 2 (2) | 2 (2) |
| Heap allocations, `wgpu` crates | 81 (91) | 60 (70) | 0 |
| Heap allocations, driver | 57 (67) | 44 (54) | 29 (29; copy 37) |
| Kinstructions, `wgpu` + `wgpu-core` + `wgpu-hal` | 53.7 (62.3) | 43.0 (50.0) | 0 (probe 0.2) |
| Kinstructions, driver (software) | 34.1 (38.3) | 26.4 (30.6) | 16.9 (17.0; copy 19.2) |
| Kinstructions, thread total (callgrind) | 88.5 (101.3) | 70.0 (81.3) | 17.1 (17.2; copy 19.5) |
| Kinstructions user + kernel (`perf`) | 106.6 (119.0) | 81.3 (92.1) | 30.5 (30.8; copy 33.7) |
| Thread CPU, µs (VM, software driver) | 126 (133) | 89 (92) | 67 (70; copy 74) |
Split of the 53.7 kinstructions on the `wgpu` side: `wgpu-core` 36.8, `wgpu-hal` 14.5, `wgpu`
2.4. Inclusive cost by entry point in Rune's overlay, including driver time: `Queue::submit` 32.4,
`Queue::present` 27.2 (8.2 patched), `CommandEncoder::finish` 16.5, `get_current_texture` 7.3,
`create_view` 3.3, `begin_render_pass` 2.3.
What the floor drops, and why each call is avoidable:
- **The second submit.** `Queue::present` submits a `PendingWrites` command buffer that holds only
PRESENT→PRESENT barriers, because Vulkan's ordered texture usages are `INCLUSIVE` only
(`wgpu-hal/src/vulkan/adapter.rs:3247`). `skip_barrier` therefore keeps the barrier
(`wgpu-core/src/track/mod.rs:341-345`), and `vulkan/command.rs:220,268` skip
`vkCmdPipelineBarrier` only when the list is empty. The patch removes this submit.
- **Two PRESENT→PRESENT image barriers.** Neither changes the layout (`PRESENT_SRC_KHR` both sides)
nor orders anything, so both are no-ops.
- **Three empty command buffers.** `Transit`, `Pre Pass` and `Present` each pay a
`vkBeginCommandBuffer`/`vkEndCommandBuffer` pair. The two barriers that matter,
UNDEFINED→COLOR_ATTACHMENT and COLOR_ATTACHMENT→PRESENT_SRC, ride in two of them. The floor gets
both transitions free from the render pass's `initialLayout` and `finalLayout`, with one external
subpass dependency on the acquire semaphore (`vk_floor.rs`).
- **Two image views and a framebuffer every frame.** `get_current_texture` builds a clear view for
the surface texture (`wgpu-core/src/present.rs:210-223`), and the app's `create_view` builds the
second. The framebuffer cache lives in the command encoder and is drained on every `reset_all`
(`vulkan/command.rs:184-187`), so the framebuffer for that frame's view is rebuilt every frame.
The floor makes views and framebuffers once per swapchain image.
- **With a write:** each `Queue::write_buffer` creates, binds and destroys a staging `VkBuffer`
through `gpu-allocator`, and records a copy into `PendingWrites`, the third command buffer
reset. Its MAP_WRITE→COPY_SRC barrier is a no-op, because `vkQueueSubmit` already makes host
writes visible (Vulkan spec, "Host Write Ordering Guarantees"). COPY_DST→COPY_DST orders the
write after last frame's copy into the same buffer and is needed. The floor writes into a mapped
ring. On a discrete GPU it records one `vkCmdCopyBuffer` and one buffer barrier, which costs
2.3 kinstructions.
Rune's real overlay agrees with the probe: 105.3 kinstructions per frame, of which Rune is 9.9,
the `wgpu` side 51.5, the driver 39.8 and windowing 4.1. With one write it's 116.7 (58.9 `wgpu`,
43.7 driver). Patched, those drop to 84.5 and 97.9.
## DX12, per frame
Traced through vkd3d, counted between two presents. Thread numbers are for the whole Wine stack.
| HUD frame, 0 writes (1 write) | wgpu today | wgpu patched | Native floor |
| --- | ---: | ---: | ---: |
| `ExecuteCommandLists` | 2 (2) | 1 (1) | 1 (1) |
| Command lists reset and closed | 5 (6) | 4 (5) | 1 (1) |
| Command allocator resets | 2 (3) | 1 (2) | 1 (1) |
| `ResourceBarrier` calls, transitions | 2, 2 (3, 3) | 2, 2 (3, 3) | 2, 2 (copy: 2, 3) |
| No-op transitions | 0 (1) | 0 (1) | 0 |
| `Signal` on the frame fence | 2 | 1 | 1 |
| `CreateRenderTargetView` | 2 | 2 | 0 |
| Placed resource, `Map`/`Unmap` per write | 0 (1) | 0 (1) | 0 |
| Kinstructions user + kernel (`perf`) | 160.4 (200.7) | 137.9 (176.1) | 41.4 (41.7; copy 44.4) |
| Thread CPU, µs (Wine + vkd3d + lavapipe) | 130 (146) | 128 (133) | 61 (61; copy 64) |
- DX12 already sits at the barrier floor. `transition_textures` drops a transition whose states
match (`wgpu-hal/src/dx12/command.rs:514-516`), so PRESENT→PRESENT never reaches the API, and
DX12 orders COLOR_TARGET and DEPTH_STENCIL_WRITE (`dx12/adapter.rs:1397-1400`). The two
PRESENT↔RENDER_TARGET transitions are required for a swapchain buffer, so the floor has them too.
- The one no-op is COMMON→COPY_SOURCE on the write's staging buffer: buffers are promoted
implicitly from COMMON, and upload-heap resources stay in GENERIC_READ anyway.
- What's left is the same shape as on Vulkan: a second `ExecuteCommandLists` with its `Signal`
(`dx12/mod.rs:1799-1802`), four extra command list Reset/Close pairs, two RTVs written per frame,
and a placed staging resource per write.
- The per-crate split wasn't measured on DX12, because callgrind can't follow the Windows binary
under Wine. `wgpu-core` is the same code on both backends, so its ~37 kinstructions carry over.
The rest of the 119-kinstruction gap is `wgpu-hal`'s dx12 code plus vkd3d translating its extra
calls, which real Windows doesn't pay. Treat the DX12 gap as an upper bound.
- The probe uses `wgpu`'s default HWND swapchain. Rune uses `DxgiFromVisual`, which differs only
in how the swapchain is created, not in the per-frame calls above.
## Normal window frame
`upload_bench` measures a renderer frame with no surface: `prepare`, one pass with one draw, and
submit.
| Kinstructions per frame (Vulkan, callgrind) | steady | scroll |
| --- | ---: | ---: |
| Rune (`prepare`, `draw`) | 426.1 | 554.1 |
| `wgpu` + `wgpu-core` + `wgpu-hal` | 36.8 | 37.1 |
| Driver (software) | 11.8 | 12.3 |
| Total | 474.7 | 603.5 |
| `cpu_us` without valgrind | 56.9 | 72.1 |
Per frame: 1 `vkQueueSubmit`, 4 command buffers, 3 barriers, 1 copy, 1 draw, and 83 heap
allocations in the `wgpu` crates. A native backend would keep roughly the driver part and add a
few kinstructions of its own, so it saves about 35 kinstructions, 6 to 7% of the frame. A window
also pays the surface costs measured on the HUD (acquire, view, present, and the second submit
today), so a normal window saves about the HUD's figure plus a few µs.
## Projected savings
The 120 Hz frame is 8.33 ms. "Measured" means CPU time on the VM with software drivers.
"Projected" assumes the `wgpu` side and the extra API calls run at 2 to 4 instructions per ns on a
desktop core.
| Backend, HUD frame | Today → native | Patched → native | Today → patched |
| --- | ---: | ---: | ---: |
| Vulkan, kinstructions (callgrind) | −71 (−84 with a write) | −53 (−64) | −18.5 (−20) |
| Vulkan, measured | −0.059 ms, 0.71% (−0.063, 0.76%) | −0.022 ms, 0.27% | −0.037 ms, 0.45% |
| Vulkan, projected on hardware | −0.02 to −0.04 ms, 0.2 to 0.5% | −0.015 to −0.03 ms | −0.005 to −0.01 ms, plus one submit's kernel time |
| DX12, kinstructions (`perf`, includes vkd3d) | −119 (−159) | −96 (−134) | −23 (−25) |
| DX12, measured under Wine | −0.070 ms, 0.83% (−0.085, 1.0%) | −0.067 ms, 0.81% (−0.072) | ~0 (−0.013 with a write) |
| Normal window, kinstructions | ≈ HUD figure + 35 | ≈ HUD figure + 35 | as HUD |
For scale, [30](30-overlay-gpu-cost.md) measured a 705-kinstruction gap per frame between Rune
and hand-written Metal, process-wide. The Vulkan gap here is about 10 times smaller in
instructions. A large part of the Metal gap is driver work per command buffer, which lavapipe
mostly hands to its own threads, so real Vulkan and DX12 drivers may cost more per extra submit
than these numbers show.
## What paid hardware would settle
- The real cost of each extra `vkQueueSubmit`/`ExecuteCommandLists`, empty command buffer,
per-frame view and framebuffer, and staging buffer on NVIDIA, AMD and Intel drivers. A real
submit goes to the kernel, and lavapipe's doesn't. That's the biggest unknown in the projection.
- DX12 with Microsoft's runtime instead of vkd3d, and Rune's `DxgiFromVisual` swapchain under DWM
with real vsync and frame latency waits.
- Cheapest option: one AWS `g4dn.xlarge` (NVIDIA T4) in us-east-1 at $0.526/h on Linux, about
$0.71/h on Windows (license included), or about $0.30/h spot. One hour each, about $1.25 on
demand, runs every probe here.
- A free middle step is a `windows-latest` GitHub Actions job on WARP, which is Microsoft's runtime
over a software rasterizer. Pushing a workflow file needs a token with the `workflow` scope, so it
wasn't tried here.
## Cheaper than a backend
1. Upstream `wgpu-core-present-skip.patch` (one fewer submit, two no-op barriers, a command buffer
and 20 allocations per frame on every backend).
2. In `wgpu-hal` Vulkan, keep the framebuffer cache across `reset_all`, or use imageless
framebuffers, and skip same-layout image barriers as DX12 does.
3. In `wgpu-core`, reuse the surface texture's clear view across frames for the same swapchain
image.
4. In Rune, keep writing through its own staging ring rather than `Queue::write_buffer`, which
creates a staging buffer per call on Vulkan and a placed resource per call on DX12.
## Reproduce
From `research/gpu-floor` on Linux with Mesa lavapipe and an X server (`DISPLAY`):
```sh
cargo build --release
WRITES=0 ./target/release/wgpu_frame # BACKEND=vulkan|dx12
WRITES=0 ./target/release/vk_floor # UPLOAD=mapped|copy
cargo build --release --target x86_64-pc-windows-gnu
BACKEND=dx12 WINE_PERF=1 wine64 target/x86_64-pc-windows-gnu/release/wgpu_frame.exe
WINE_PERF=1 wine64 target/x86_64-pc-windows-gnu/release/dx12_floor.exe
```
For the patched rows, add
`--config 'patch.crates-io.wgpu-core.path="<wgpu-core 30.0.1 with the present-skip patch>"'`.
Callgrind per frame:
`valgrind --tool=callgrind --collect-atstart=no '--toggle-collect=*Draw>::frame' --separate-threads=yes ...`,
then `cgsplit.py <main-thread profile> --frames N`.
+234
View File
@@ -0,0 +1,234 @@
# 37. What to own next
Reader: someone deciding whether Rune should replace another dependency (Taffy, Parley, winit,
an image decoder) or put the next week into its own runtime. This note re-runs
[33](33-real-bottlenecks.md)'s four real-app workloads on current `dev` and ranks the parts
Rune could own by what they cost now.
The short answer: there's nothing left worth owning. The dependencies Rune could replace now
cost little: Taffy is 1–4% of busy time outside a live resize, and 0.06–0.09 ms per committing
frame in an agent client's chat. Shaping is at most 4.7%, and image decode and Markdown parsing
are near zero. What costs now is Rune's own runtime:
1. **Copying `Node`s in commit.** Memo reuse clones every reused node, each about 1.7 KB with
its `Visual`, on every commit, and apply then drops the old copies. That is 15–20% of commit
time in the agent client and most of the commit time that isn't view, layout, text or apply.
2. **Per-frame scans and ancestor walks** in the paint walk and frame step: `subtree_exiting`
walks up to the root for each hit-testable node, and `highlight_target_in`, `Keyed::new` and
`layout_of` scan every node. On the board's long card these cost 15–20% of busy time. A
small spike removed most of it: long-card scroll p50 −17%.
3. **The paint walk itself** (`Runtime::build`). It is 25–62% of a scroll frame. Scroll frames
are already 0.5–0.9 ms at p50, so making it cheaper saves power but doesn't fix missed frames.
The one interaction still missing the frame budget is scrolling the board's long card: 82
frames over 8.3 ms, with p95 15 ms. Item 2 is its first fix.
## How it was measured
- **Builds:** "Then" is the exact tree [33](33-real-bottlenecks.md) measured: Rune `c83aa06b`
with each app's code from that day. "Now" is Rune `dev` at `506f5421`, which matches
`29df6816` apart from three commits that only move files, with each app's current code.
So "now" includes app-side changes as well. The biggest is the team chat's timeline, which
now builds only its mounted rows; that explains much of its type and resize gains.
- **Rune changes in between:**
- glyph quad replay (`f560da33`);
- memo reuse of flattened slices and Taffy subtrees (`049a0b13`, `417da565`);
- the resize fast path that now admits virtual lists (`d7cdefde`).
- **Machine and builds:** `--profile perf` with `rune/frame-profile`, headless at scale 2, on a
12-core M2 Max shared with other jobs (load 5–13). Each side has its own target dir.
- **Runs:** each app ran 6 paired rounds after a warmup. Each round ran every scenario on both
sides, alternating which side went first and the scenario order. Numbers are medians with
outliers kept. A 1 kHz main-thread `sample` ran 3 times per scenario per side, 90 s each.
- **Then figures:** the "then" column is this run's own paired figures. They differ from
[33](33-real-bottlenecks.md)'s because that run's machine was busier (load 6–20).
- **What headless leaves out:** GPU work, presentation, winit and window-server event delivery.
A Metal backend is landing separately, so GPU submission is out of scope here.
## Frame CPU per interaction, then → now
Thread-CPU ms per drawn frame: p50 / p95 / p99 / max, then frames over 8.3 ms.
| Workload / interaction | Then | Now |
|---|---|---|
| Team chat / scroll | 0.55 / 0.96 / 1.15 / 16.5, 3 over | 0.46 / 0.75 / 0.98 / 3.21, 0 over |
| Team chat / type | 0.65 / 13.0 / 16.4 / 22.5, 84.5 over | 0.39 / 2.36 / 3.07 / 3.43, 0 over |
| Team chat / resize | 17.6 / 30.9 / 39.2 / 43.1, 239 over | 2.79 / 5.40 / 5.78 / 6.59, 0 over |
| Notes / open | 4.14 p50, 16.6 max, 2 over | 3.08 p50, 14.5 max, 2 over |
| Notes / cursor | 5.73 / 11.4 / 12.5, 23.5 over | 2.68 / 4.70 / 6.02, 0 over |
| Notes / scroll | 0.83 / 1.18 / 1.29 / 1.62 | 0.63 / 0.84 / 0.91 / 0.99 |
| Notes / resize | 6.67 / 9.81 / 11.5 / 12.8, 21 over | 1.80 / 3.33 / 4.69 / 6.10, 0 over |
| Agent client / scroll | 0.66 / 1.77 / 2.75 / 4.55 | 0.56 / 1.36 / 2.11 / 4.20 |
| Agent client / stream | 0.72 / 2.06 / 2.47 / 3.03 | 0.82 / 1.59 / 1.97 / 2.38 |
| Agent client / type | 1.53 / 1.77 / 2.15 / 2.15 | 0.88 / 1.15 / 1.27 / 1.40 |
| Agent client / resize | 2.01 / 2.68 / 3.08 / 3.73 | 1.23 / 1.72 / 1.91 / 2.10 |
| Board / scroll | 1.29 / 1.70 / 7.91 / 13.0, 2 over | 0.25 / 0.48 / 3.29 / 3.49, 0 over |
| Board / open cards | 1.83 / 11.1 / 17.7 / 30.1, 108 over | 0.39 / 0.71 / 3.66 / 14.7, 1 over |
| Board / long-card scroll | 3.33 / 21.5 / 23.3 / 24.3, 81.5 over | 2.34 / 15.2 / 19.6 / 20.4, 82 over |
| Board / diagram card, scroll | 2.41 / 12.4 / 13.7 / 14.7, 59 over | 0.91 / 4.38 / 5.45 / 6.67, 0 over |
| Board / diagram card, open | 98.3 max | 55.8 max |
The notes palette still blocks on its daemon socket: its mean update wall time went from
231 ms to 188 ms, while its CPU time is small. That one is app-side.
**An agent client's chat** was measured in a separate run on a bigger real transcript: `dev`
`29df6816`, headless release, medians of 3. The figures are CPU ms per active frame, before the
memo work → after.
| Interaction | p50 | p95 | Allocated per frame, p50 |
|---|---|---|---|
| Typing | 3.92 → 2.15 | 4.63 → 2.71 | 5,072 → 2,446 KB |
| New message | 3.91 → 2.79 | 4.57 → 3.53 | 5,811 → 3,744 KB |
## Launch, then → now
Headless, from process start to the first frame read back, and the first frame's CPU.
| Workload | Process to pixels | First frame CPU |
|---|---|---|
| Team chat | 65 → 50 ms | 31.1 → 17.5 ms |
| Notes | 59 → 75 ms | 16.1 → 16.2 ms |
| Agent client | 69 → 75 ms | 17.4 → 19.8 ms |
| Board | 168 → 111 ms | 67.8 → 25.1 ms |
The notes and agent client launches stay within run-to-run spread; the agent client's extra
time is in app state loading (24 → 27 ms).
## Where the main thread goes, then → now
These are inclusive shares of main-thread busy time: self samples whose stack contains the
owner. Owners nest (glyph emission is inside the paint walk), so a row doesn't sum. A share can
rise only because the frame around it got cheaper.
| Workload / interaction | Paint walk | Glyph emit | Flatten | Apply | Taffy | Shaping | Markdown | Alloc |
|---|---:|---:|---:|---:|---:|---:|---:|---:|
| Team chat / scroll | 52 → 48 | 8 → 11 | 1 → 0 | 1 → 1 | 1 → 1 | 1 → 1 | 3 → 0 | 6 → 6 |
| Team chat / type | 20 → 36 | 3 → 7 | 5 → 7 | 3 → 7 | 1 → 2 | 0 → 1 | 16 → 3 | 13 → 6 |
| Team chat / resize | 4 → 14 | 1 → 4 | 6 → 14 | 3 → 9 | 3 → 12 | 0 → 0 | 22 → 7 | 16 → 11 |
| Notes / scroll | 72 → 62 | 16 → 16 | 0 → 0 | 0 → 0 | 2 → 4 | 2 → 2 | 0 → 1 | 1 → 2 |
| Notes / cursor | 44 → 46 | 10 → 10 | 12 → 8 | 6 → 6 | 2 → 2 | 1 → 1 | 0 → 0 | 7 → 3 |
| Notes / resize | 20 → 29 | 4 → 7 | 13 → 0 | 13 → 15 | 26 → 25 | 1 → 1 | 0 → 0 | 8 → 3 |
| Agent client / scroll | 46 → 26 | 12 → 10 | 2 → 2 | 2 → 2 | 4 → 4 | 2 → 2 | 1 → 0 | 4 → 7 |
| Agent client / stream | 27 → 24 | 5 → 6 | 15 → 12 | 12 → 10 | 6 → 9 | 2 → 3 | 3 → 5 | 9 → 7 |
| Agent client / type | 46 → 30 | 10 → 8 | 7 → 4 | 4 → 5 | 4 → 4 | 2 → 3 | 0 → 0 | 5 → 8 |
| Agent client / resize | 20 → 19 | 3 → 7 | 19 → 14 | 9 → 9 | 11 → 14 | 1 → 1 | 0 → 0 | 11 → 7 |
| Board / open cards | 13 → 25 | 1 → 4 | 5 → 3 | 3 → 0 | 1 → 1 | 1 → 2 | 0 → 0 | 9 → 6 |
| Board / long-card scroll | 20 → 29 | 1 → 1 | 9 → 10 | 7 → 7 | 2 → 2 | 1 → 1 | 1 → 0 | 7 → 5 |
| Board / diagram card | 15 → 33 | 1 → 4 | 5 → 4 | 3 → 1 | 1 → 1 | 1 → 2 | 0 → 0 | 7 → 4 |
Parley's glyph iterators, which [33](33-real-bottlenecks.md) found at 15–26% of a scroll frame,
are now 0–1.4%. What glyph emission still costs is Rune's own replay
(`glyphs_in_band_cached`, `glyph_or_image`). Image decode and winit don't appear in any sample:
the workloads load no images, and headless runs bypass winit's event loop.
## The biggest costs now
| Cost | Where | Share |
|---|---|---|
| `Runtime::build`, the paint walk's own lines | every scroll | 13–21% self |
| `highlight_target_in`, a full node scan with a `format!` for each highlight | board long card, diagram card | 6–11% |
| `Scene::phase`, from `subtree_exiting` walking to the root for each hit-testable node | board long card | 5% (+ about 7% inlined into the paint walk) |
| Node copies in flatten: `memmove`, `Node::clone`, `Visual::clone` | agent client stream, type | 6% of busy time, about 60% of flatten |
| `window_tree`: virtual-row builders, `El` moves, a SipHash `HashSet`, linear path finds | agent client stream | 7% |
| `Keyed::new`, a per-frame map of every node's key | board | 3–4.5% |
| `glyphs_in_band_cached` | scroll | 4–9% |
| `Renderer::prepare`, `pack_fade` | scroll | 3–12% (GPU work, out of scope) |
| Taffy `compute_flexbox_layout` | resize | 4.6–5.5% self |
| `__recvfrom` on the daemon socket | notes | 3–7% (app-side) |
In the board runs, 1.7–5.5% goes to the frame log being echoed to stderr as JSON. That is the
harness's own overhead, not the app's.
## What commit spends, besides view, layout, text and apply
In the agent client's chat, about 1.2–1.7 ms of each commit is none of view, layout, text or
apply. Sampling the same workload here (agent client, type and stream) shows which functions
own it. The figures are shares of the samples under `Runtime::commit`:
| Owner | Type | Stream |
|---|---:|---:|
| Flatten: copying reused nodes (`try_reuse_memo` → `Node::clone`, `Vec<Node>::push`) | 14.6 | 14.0 |
| Flatten: the rest (`Style` comparison, path strings) | 7.9 | 9.9 |
| `window_tree`: building virtual rows (app code that the view timer misses), moving `El`s, a SipHash set of mounted keys, a linear search for the scroll node | 7.3 | 17.2 |
| Apply: dropping the previous commit's nodes | 2.4 | 4.2 |
| Layout reads, `measure_virtuals`, `release_kept_layouts`, place | 9.7 | 10.7 |
| *For scale:* view 15.9 / 14.0, Taffy 17.7 / 15.2, the rest of apply 24.4 / 14.9 | | |
Across commit, `memmove` is 17–20% of samples and allocation 7–9%. Most of that `memmove` is
`Node`s being moved or cloned: each is about 1.7 KB, around 100 fields plus a 71-field
`Visual`.
Taffy's share of samples is larger than the frame profile's layout p50 (0.07 ms here,
0.06–0.09 ms in the agent client's chat) because samples weight by time. The commits that
rewrap streamed text pay for layout; the median commit doesn't. Layout's mean is 0.13–0.16 ms.
## Verdicts
Upper bounds are the measured share a change could remove at most, as a percentage of
main-thread busy time unless marked otherwise.
| # | Candidate | Upper bound | Size | Risk | Verdict |
|---|---|---|---|---|---|
| 1 | (b) Smaller `Node`, starting with memo reuse moving nodes instead of cloning them | 15–20% of commit (0.35–0.6 ms per commit in the agent client's chat), plus paint-walk stride | Medium for the clone fix; large for a hot/cold split | Medium: apply's diffing and measure retries read the old nodes | **Own it**, in Rune. Stop cloning reused spans first, then split `Node` and `Visual` into hot and cold parts |
| 2 | (i) Per-frame scans and ancestor walks: `subtree_exiting`, `highlight_target_in`, `layout_of`, `Keyed::new`, `in_scope` | 15–20% on the board's long card, under 2% elsewhere | Small | Low | **Fix in Rune.** Spiked below |
| 3 | (i) `window_tree`: per-commit sets, string paths, linear finds; time row builders as view | 7–17% of commit | Small | Low | **Fix in Rune** |
| 4 | (i) Retained paint per subtree, translating cached spans on scroll | 25–62% of a scroll frame | Large | High: fades, clips, sticky headers, hover | **Later.** Scroll already fits the budget, so the gain is power |
| 5 | (c) Per-frame arena | Allocation is 2–11% of busy time, 7–9% of commit; an arena reaches only frame-lifetime allocations | Medium–large | Medium | **Don't bother.** Items 1 and 3 remove most of the churn |
| 6 | (d) Own flex and stack layout instead of Taffy | 1–4% outside resize; 8–10% self (≤ 25% with measure callbacks) on notes resize | Large | High | **Don't bother.** If resize needs it, skip clean subtrees within Taffy |
| 7 | (e) Own shaper and a shaped-word cache | ≤ 4.7% everywhere | Large | High | **Don't bother** |
| 8 | (f) Markdown parse and build in rune-kit | 0–7% now (was up to 22%) | Medium | Low | **Don't bother.** Memo already covers it |
| 9 | (a) Flat glyph runs for text paint | Landed (`f560da33`); Parley iteration 15–26% → 0–1.4% | Done | — | **Done** |
| 10 | (g) Own the macOS run loop and use CADisplayLink | Not visible headless; a windowed profile is needed | Large | High | **Don't own it for CPU.** Pacing or latency could justify it, but only with a windowed measurement |
| 11 | (h) Image decode | 0% in these workloads | — | — | **Don't bother** |
## Spike: per-frame scans (#2)
The spike made three changes on a scratch tree that won't land:
- One forward pass per frame marks the subtrees that are exiting, and `subtree_exiting` reads
that mark during the frame step.
- A node reads its clock only when it has a loop track.
- `highlight_target_in` checks whether a node has highlights before testing scope, and matches
keys without building a path string.
Both sides were built from the same tree, `dev` with each app's current code, with only the
patch differing. The board ran 6 paired rounds. Other jobs pushed the machine's load to 80–115
during the run, so absolute times are inflated. The spike was faster in every paired round of
every scenario.
| Board interaction | Base p50 | Spike p50 | Frames over 8.3 ms | Median paired ratio |
|---|---:|---:|---:|---:|
| Long-card scroll | 9.81 | 8.17 | 221 → 178 | 0.83 |
| Diagram card scroll | 3.13 | 2.93 | 19 → 20.5 | 0.93 |
| Board scroll | 1.07 | 1.03 | 1 → 2 | 0.96 |
| Open cards | 1.59 | 1.52 | 13 → 12.5 | 0.96 |
In the long-card samples, `highlight_target_in` fell from 11.7% to 4.7%, and from 6.1% to
1.5% on the diagram card. Its remaining cost comes from `layout_of`, which calls it once for
each layout read, so the next step is an index from highlight key to node built once per
commit. `Keyed::new` can be cached per commit the same way. Re-run on a quiet machine before
quoting the size of the gain.
No spike was run for #1, because a safe version has to keep the old nodes readable through
measure retries and apply's diffing, which makes it more than a scratch patch. Its upper bound
comes from the commit samples above.
## Tried, not landed: pooling node path strings
After `154e4d33` (inherited `hover_motion_within` curves kept beside a node's visuals), a
line-level profile of the 2,300-element card workload (`scroll_bench --workload card`) put
commit at 58% of the frame step: flatten 34% of that (moving the 552-byte `Style` into
`sync_taffy_node`, moving 1,152-byte `El` children out of their iterator, a `String`-keyed
`layout_entries` lookup per node), apply 21% with `clear_old_nodes` about 29% of apply,
`place` refilling `node_index` 2.4% of busy time and `release_kept_layouts`' path lookups
3.2%. The patch tried was the cheapest of these: flatten reused the path strings of the
nodes and layout entries the last build dropped (bounded to one per node, 256 bytes each).
On the card, paired over 10 alternating rounds, allocations per commit fell from 9,989 to
7,706 and instructions from 16.68 to 16.25 G (−2.6%). Commit p50 went from 2.10 to 1.83 ms in
one run and 1.86 to 1.81 ms in another. On the board's long card it saved 3.5% of commit
allocations, but instructions moved −0.02% and −0.85% in two runs, and the commit-frame
median was mixed (9.38 → 8.97 ms, then 7.94 → 8.11 ms). That's because memo reuse there moves
nodes instead of dropping them, so `clear_old_nodes` is about 1% of busy time. There, commit
is 32% of busy time: the app's view 42% of it, solve 15%, flatten 13.5%, and every Rune-side
candidate above is under 1% of busy time. Not worth the churn. Numbers come from an M4 Pro
under load 30–40, compared by median with outliers kept, headless, so GPU upload and
presentation are left out.
@@ -0,0 +1,107 @@
# 38. View re-run and commit cost
Follows [37](37-what-to-own-next.md) on `dev` after `43a1a469`, `154e4d33`, `9beba394`, `bdf0507d`,
`8d3d3f72`, `fc9a3d07`, `8a14dda8` and `622890c4` had already landed (`e6371c48`). Those commits
moved `memo`-reused slices on normal rebuilds, split cold fields out of `Node` and `Visual`, and
replaced Taffy's map storage with dense slot tables. Two costs remained for apps that don't wrap
every subtree in `memo`:
1. **Re-running the whole view and rebuilding static subtrees.** Scrolling an `El::virtual_rows`
list (or filling its overscan) re-ran the app's `view` closure and rebuilt every mounted row's
`El` tree even when app state hadn't changed. And `Markdown::render` parsed and built its entire
block/inline `El` tree on every commit unless the caller wrapped it in `memo`, while leaving
`reveal = 0.0` on static paragraphs so `apply` populated `reveals` and rejected `clean_apply_spans`.
2. **Copying and diffing unchanged commit state.** Resize commits (`relayout`) still cloned every
`Node` (`Node::relaid_from`), adjacent clean `memo` spans stayed uncoalesced, truncated and
line-clamped labels ran Parley binary-search shaping probes on every commit, non-memo `Node`
paths allocated fresh `String`s every commit, and `apply` ran ~20 `Scene` / `AnimationStore`
hash lookups on every non-memo node even when its layout, visuals and tracks were at rest.
## What landed
1. **Partial `virtual_rows` remount (`CommitWhy::VIRTUAL`).** When `!relayout && state_unchanged`
and no pending reveal or layout/caret read invalidates the view, `remount_virtuals` moves
non-list subtrees and staying rows straight out of `self.nodes`, calls the row closure only for
newly entering indices, and falls back cleanly to a full `view` pass if a layout read of a
culled or newly mounted row moves. `MemoCache` tags entries with `virtual_row` so view-level and
staying-row memos survive partial commits while culled row memos evict immediately.
2. **Automatic `Markdown::render` subtree caching.** Pure-data `Markdown` renders (not streaming,
no link/task/highlighter closures, no source-copy selection or Mermaid blocks) cache their built
and flattened subtree in `MemoCache` by a 128-bit `(FxHasher, DefaultHasher)` digest and pass
ordinal, preserving `el.key` (`None` when unkeyed, or `.key(..)` attached after `.render(..)`).
Static `Markdown::new` defaults `reveal` to `-1.0` so non-streaming Markdown skips `reveals` and
qualifies for `clean_apply_spans`.
3. **Move nodes on resize commits and coalesce clean apply spans.** `relayout` moves non-input,
non-secure `Node`s out of `self.nodes` via `Node::moved_stub` (restoring them if a virtual
window moves and forces a full `view` pass), and `clean_apply_spans` merges contiguous spans.
4. **Elision cache, in-place node path moves, and resting non-memo `apply` skip.** `TextSystem`
caches `El::truncate` and `El::max_lines` cuts (`CachedElision`) with the same two-commit +
`STALE_BYTES` eviction and `supersede` invalidation as shaped layouts (bypassed for `secure`
text) and reuses probe buffers and the winning binary-search probe. Committing flatten passes
move `old.path` `String`s directly from matching `self.nodes` slots (restored on retry or
`discard_measured`, as opposed to [37](37-what-to-own-next.md)'s dropped string-pool spike, this
also skips the `path_ids` hash lookup when `old_cursor` stays in step). Finally,
`Scene::is_resting_at` checks presence, frame and active tracks in one slot lookup so `apply`
skips unchanged resting non-memo nodes, and `commit_paint` short-circuits `!instant && from == Some(to)`
before querying `AnimationStore`.
## Why arbitrary view helpers still need `memo`
Rust evaluates arguments eagerly: in `parent.child(helper(state, cx))`, `helper` has already run
and built its `El` tree before `parent.child` sees anything, and `&S` is a plain shared reference
with no field-read tracking. Skipping arbitrary `fn(&S, &mut Cx<S>) -> El` helpers without `memo`
would require either reactive state handles or a view macro/compiler rewrite. Automatic skipping in
plain Rust therefore covers the two boundaries Rune already owns: `virtual_rows` closures when `&S`
didn't change, and pure-data component builders (`Markdown::render`).
## Headless numbers, before → after
Built with `--profile perf` and `rune-kit/markdown,frame-profile`, headless at scale 2 on an idle
Apple Silicon worker. Paired over 7 alternating rounds (`A B`, `B A`, …) with outliers kept,
compared by median. Headless figures leave out GPU upload, Metal/wgpu submission, window-server
events and presentation.
### `layout_text_cost` (`e6371c48` → after)
| Case | Commit p50 → after (ms) | Commit p95 → after (ms) | View p50 → after (ms) | Apply p50 → after (ms) | Allocs p50 → after |
|---|---:|---:|---:|---:|---:|
| `md-same` | 0.851 → 0.167 (−80.4%) | 0.952 → 0.186 (−80.5%) | 0.359 → 0.021 (−94.1%) | 0.201 → 0.038 (−81.0%) | 5,687 → 10 (−99.8%) |
| `memo-chat` | 0.549 → 0.340 (−38.0%) | 0.621 → 0.385 (−38.0%) | 0.072 → 0.071 (−1.7%) | 0.241 → 0.086 (−64.3%) | 1,047 → 713 (−31.9%) |
| `md-beside:commit` | 1.218 → 0.818 (−32.9%) | 1.418 → 0.984 (−30.6%) | 0.227 → 0.030 (−86.7%) | 0.223 → 0.111 (−50.3%) | 4,637 → 1,788 (−61.4%) |
| `list:commit` | 0.540 → 0.375 (−30.6%) | 0.599 → 0.419 (−30.1%) | 0.073 → 0.006 (−91.8%) | 0.140 → 0.089 (−36.0%) | 2,048 → 853 (−58.3%) |
| `md-virtual:commit` | 0.855 → 0.620 (−27.5%) | 1.046 → 0.793 (−24.2%) | 0.151 → 0.045 (−70.2%) | 0.136 → 0.069 (−49.4%) | 2,916 → 1,228 (−57.9%) |
| `stack` | 3.962 → 3.254 (−17.9%) | 4.735 → 4.011 (−15.3%) | 1.355 → 1.352 (−0.2%) | 1.278 → 0.788 (−38.4%) | 25,877 → 20,594 (−20.4%) |
| `tree` | 3.216 → 2.700 (−16.0%) | 3.728 → 3.244 (−13.0%) | 0.920 → 0.913 (−0.7%) | 1.163 → 0.733 (−37.0%) | 16,704 → 11,740 (−29.7%) |
| `stack-same` | 3.651 → 3.186 (−12.7%) | 4.365 → 3.861 (−11.5%) | 1.340 → 1.344 (+0.3%) | 1.035 → 0.773 (−25.4%) | 25,806 → 20,523 (−20.5%) |
| `vlist-resize` | 0.452 → 0.432 (−4.5%) | 0.498 → 0.480 (−3.6%) | 0.000 → 0.000 | 0.072 → 0.060 (−16.8%) | 2,236 → 1,747 (−21.9%) |
| `md-resize` | 1.822 → 1.742 (−4.4%) | 1.979 → 1.903 (−3.8%) | 0.000 → 0.000 | 0.265 → 0.230 (−13.2%) | 8,335 → 6,308 (−24.3%) |
| `md-open` | 17.674 → 17.543 (−0.7%) | 18.371 → 18.571 (+1.1%) | 0.456 → 0.481 (+5.5%) | 0.131 → 0.117 (−10.6%) | 47,253 → 48,266 (+2.1%) |
| `edit` | 18.980 → 19.009 (+0.2%) | 19.421 → 19.410 (−0.1%) | 0.007 → 0.007 (0.0%) | 0.053 → 0.052 (−1.7%) | 1,153 → 1,150 (−0.3%) |
### `scroll_bench` (`e6371c48` → after)
| Workload | Frame CPU p50 / p95 (ms) | Commit CPU p50 / p95 (ms) | View p50 / p95 (ms) | Apply p50 / p95 (ms) | Allocs p50 / p95 |
|---|---:|---:|---:|---:|---:|
| `card` | 2.010 → 1.268 (−36.9%) / 2.289 → 1.417 | 1.491 → 0.760 (−49.0%) / 1.700 → 0.853 | 0.513 → 0.301 (−41.3%) / 0.607 → 0.339 | 0.486 → 0.167 (−65.6%) / 0.551 → 0.196 | 9,327 → 3,504 (−62.4%) / 9,380 → 3,557 |
| `growth` (commits every 12th frame) | 0.478 → 0.481 / 2.315 → 2.047 (−11.6%) | 0.000 / 1.846 → 1.585 (−14.1%) | 0.000 / 0.356 → 0.355 | 0.000 / 0.595 → 0.395 (−33.6%) | 6 / 10,272 → 8,239 (−19.8%) |
| `list`, `markdown`, `prose`, `sticky` (non-committing scroll) | within ±1.2% | 0.000 → 0.000 | 0.000 → 0.000 | 0.000 → 0.000 | unchanged |
## Tried and dropped
- **Moving `Node`s on `!same_path` `memo` reuse.** When a reused `memo` subtree shifts to a new
parent path (`!same_path`), `old.id != new_id`. Replacing `old_nodes[flat.start + k]` with
`Node::moved_stub()` causes `apply`'s retirement loop (`if old.is_moved_stub() { forget(old); continue; }`)
to skip `Scene::remove(old.id)` whenever no sibling took `old`'s former path, dropping exit
transitions on the old slot. Kept `Node` moves strictly to `same_path` `memo` reuse, partial
`virtual_rows` remount, and `relayout`, where `old.id == new_id` is in `self.node_index`.
- **Keeping `n.text_layout` attached across `relayout`'s `solve`.** Clearing `n.text_layout = None`
before `solve` drops the node's `Rc<Layout<Ink>>` so `TextSystem`'s cache holds the sole
strong reference (`Rc::strong_count == 1`), letting width changes re-break shaped runs in place.
Fixed-size wrapped text (`w_full().h(..)`) skips Taffy's `measure_leaf`, so keeping `n.text_layout`
across `solve` leaves `strong_count == 2` at `lay_out_text` and forces a clone of the shaped runs
on resize (`resizing_rebreaks_kept_texts_in_place`). Dropped.
- **Two-step `get_key_value` lookup in `MemoCache` to avoid `Rc<str>` construction on nested hits.**
Doing `get_key_value(name)` followed by `get_mut(&existing_id)` added a second hash lookup on
every top-level `memo` hit and regressed `memo-chat` `view_ms` by ~11%. Storing `id: Rc<str>` on
`Entry` itself kept a single `get_mut(name)` lookup while still avoiding `Rc<str>` allocation
when nested.
+464
View File
@@ -0,0 +1,464 @@
//! Throwaway spike for research/32-engine-plan.md ("Spike results"), included from
//! `crates/rune/src/text.rs` under `cfg(test)` on the `spike/engine` branch only.
//!
//! - `paragraphs_stack_like_one_layout`: one Parley layout per `\n` paragraph, stacked, against
//! one layout of the whole text, over the rewrap matrix joined into multi-paragraph texts.
//! - `bench_edit_keystroke` (ignored): typing in the 50 KB `edit` note, whole text vs stacked.
//! - `bench_word_cache` (ignored): a per-word `parley_engine` shaper cache vs Parley paragraph
//! shaping on real files.
//!
//! cargo test --profile perf -p rune --lib engine_spike -- --ignored --nocapture --test-threads=1
use super::*;
use crate::edit::Block;
use std::cell::Cell;
thread_local! {
/// Overrides the base direction Parley otherwise takes from a layout's first strong character.
pub(crate) static FORCE_DIR: Cell<Option<parley::BaseDirection>> = const { Cell::new(None) };
}
#[derive(Clone)]
struct Case { name: String, text: String, spans: Vec<Span>, blocks: Vec<Block>, pills: Vec<PillChip>, style: TextStyle, align: Alignment, wrap_anywhere: bool }
fn case(name: &str, text: &str, style: TextStyle) -> Case {
Case { name: name.into(), text: text.into(), spans: vec![], blocks: vec![], pills: vec![], style, align: Alignment::Start, wrap_anywhere: false }
}
/// `rewrap_tests::cases`, plus an Arabic paragraph ending in digits (bidi weak types across `\n`).
fn cases() -> Vec<Case> {
let body = TextStyle::new(15.0, 400.0).lh(22.0);
let rich = "The quick brown fox jumps over the_lazy_dog and keeps running past \
https://example.com/a/very/long/unbreakable/path/that/overflows/any/line while larger words sit beside it.";
let at = |s: &str| rich.find(s).unwrap() as u32;
let spans = vec![
Span { start: at("jumps"), end: at("jumps") + 5, ..Span::default() }.bold(),
Span { start: at("the_lazy_dog"), end: at("the_lazy_dog") + 12, ..Span::default() }.mono(),
Span { start: at("keeps"), end: at("keeps") + 5, ..Span::default() }.italic(),
Span { start: at("larger"), end: at("larger") + 12, ..Span::default() }.size(22.0),
];
let paragraphs = "First a plain paragraph that wraps over a few lines of text.\nA bullet item long enough to wrap onto a second line at most widths.\nA quoted line that also wraps when the width narrows enough.\nlet code = run(\"a long line of code\");";
let pill_text = "ask @code-reviewer about @src/main.rs and @notes today please, then wrap";
let pills = ["@code-reviewer", "@src/main.rs", "@notes"].iter().map(|label| {
let start = pill_text.find(label).unwrap() as u32;
PillChip { start, end: start + label.len() as u32, icon: None, bg: None, fg: None }
}).collect();
vec![
Case { spans: spans.clone(), ..case("spans", rich, body) },
Case { spans: spans.clone(), wrap_anywhere: true, ..case("wrap anywhere", rich, body) },
Case { spans: spans.clone(), align: Alignment::Center, ..case("centred", rich, body) },
Case { spans: spans.clone(), align: Alignment::End, ..case("end", rich, body) },
Case { spans, align: Alignment::Justify, ..case("justified", rich, body) },
case("right to left", "مرحبا بالعالم هذا نص طويل يلتف عبر عدة أسطر في التخطيط، ثم שלום עולם וטקסט נוסף", body),
Case { align: Alignment::Justify, ..case("right to left justified", "مرحبا بالعالم هذا نص طويل يلتف عبر عدة أسطر في التخطيط والمزيد من الكلمات هنا", body) },
case("arabic then digits", "مرحبا بالعالم 2024", body),
case("mixed fonts", "Mixed 中文字符和日本語のテキスト with emoji 🎉🚀 and math 𝑥² ∑ beside Latin words that wrap", body),
case("mono tabs", "fn main() {\n\tlet x = 1;\t// a comment that runs long enough to wrap\n}", TextStyle::new(13.0, 400.0).family(Family::Mono)),
Case { blocks: vec![Block::Paragraph, Block::Bullet(0), Block::Quote, Block::Code], ..case("blocks", paragraphs, body) },
Case { pills, ..case("pills", pill_text, TextStyle::new(14.0, 400.0)) },
]
}
const PLAIN: &str = "123 then a plain paragraph between the others, long enough to wrap at the narrower widths.";
/// `c` joined with plain and empty paragraphs: `parts` of "case", "plain" and "empty".
fn join(c: &Case, parts: &[&str], trailing: bool) -> Case {
let name = format!("{} [{}{}]", c.name, parts.join(","), if trailing { ",\\n" } else { "" });
let mut out = Case { name, text: String::new(), spans: vec![], blocks: vec![], pills: vec![], ..c.clone() };
for (i, part) in parts.iter().enumerate() {
if i > 0 { out.text.push('\n'); }
let at = out.text.len() as u32;
if *part == "case" {
out.spans.extend(c.spans.iter().map(|s| Span { start: s.start + at, end: s.end + at, ..s.clone() }));
out.pills.extend(c.pills.iter().map(|p| PillChip { start: p.start + at, end: p.end + at, ..p.clone() }));
out.blocks.extend((0..c.text.split('\n').count()).map(|k| c.blocks.get(k).copied().unwrap_or(Block::Paragraph)));
out.text += &c.text;
} else {
out.text += if *part == "plain" { PLAIN } else { "" };
out.blocks.push(Block::Paragraph);
}
}
if trailing { out.text.push('\n'); }
out
}
type Row = (&'static str, Vec<f64>);
/// The first `keep` lines of `l` as rows, moved down `y0` and along `byte0`, pill ids by `pill0`.
/// With `frac`, each line top rounds from `y0` plus the unrounded height above it, as breaking
/// the paragraph with Parley's `line_y` starting at `y0` would. Returns the kept lines' height.
fn rows(l: &Layout<Ink>, byte0: usize, (dx, y0): (f64, f64), pill0: u64, keep: usize, frac: bool, out: &mut Vec<Row>) -> f64 {
let mut h = 0.0;
for line in l.lines().take(keep) {
let (m, r) = (line.metrics(), line.text_range());
let shift = if frac { (y0 + h).round() - m.block_min_coord as f64 } else { y0 };
let y = |v: f32| v as f64 + shift;
h += m.line_height as f64;
out.push(("line", vec![(r.start + byte0) as f64, (r.end + byte0) as f64, m.offset as f64 + dx, y(m.baseline), m.advance as f64,
m.inline_min_coord as f64, y(m.block_min_coord), y(m.block_max_coord), m.line_height as f64]));
for item in line.items() {
match item {
PositionedLayoutItem::GlyphRun(run) => {
let font = run.run().font();
let mut g = vec![font.data.id() as f64, font.index as f64, run.run().font_size() as f64, y(run.baseline()), run.offset() as f64 + dx];
g.extend(run.positioned_glyphs().flat_map(|p| [p.id as f64, p.x as f64 + dx, y(p.y)]));
out.push(("glyphs", g));
}
PositionedLayoutItem::InlineBox(b) => {
let id = if b.id & PILL_BOX != 0 { b.id + (pill0 << 1) } else { b.id };
out.push(("box", vec![id as f64, b.x as f64 + dx, y(b.y)]));
}
}
}
}
h
}
fn whole(ts: &mut TextSystem, c: &Case, scale: f32, width: Option<f32>) -> (Vec<Row>, bool) {
let l = ts.layout_blocks_inner(&c.text, &c.spans, &c.blocks, &c.pills, c.style, scale, width, c.align, c.wrap_anywhere, true);
let mut out = vec![("size", vec![l.full_width() as f64, l.width() as f64, l.height() as f64, l.len() as f64])];
rows(&l, 0, (0.0, 0.0), 0, l.len(), false, &mut out);
(out, l.is_rtl())
}
/// `text` split after each `\n`; a paragraph keeps its `\n`, so its layout ends in an empty line.
fn split(text: &str) -> Vec<(usize, &str)> {
let mut at = 0;
let mut out: Vec<(usize, &str)> = text.split_inclusive('\n').map(|p| { at += p.len(); (at - p.len(), p) }).collect();
if out.is_empty() { out.push((0, "")); }
out
}
/// One layout per paragraph, stacked: each drops the empty line after its `\n` unless it is last.
/// With `fix`, line tops round as one layout's do (see `rows`), and at an unbounded width each
/// paragraph moves over to align in the widest paragraph rather than in its own widest line.
fn stacked(ts: &mut TextSystem, c: &Case, scale: f32, width: Option<f32>, fix: bool) -> Vec<Row> {
let (mut out, mut y, mut size, mut pill0) = (Vec::new(), 0.0f64, [0.0f64; 4], 0u64);
let paras = split(&c.text);
let mut laid = Vec::new();
for (k, &(start, text)) in paras.iter().enumerate() {
let (s, e) = (start as u32, (start + text.len()) as u32);
let spans: Vec<Span> = c.spans.iter().filter(|x| x.start < e && x.end > s)
.map(|x| Span { start: x.start.max(s) - s, end: x.end.min(e) - s, ..x.clone() }).collect();
let pills: Vec<PillChip> = c.pills.iter().filter(|p| p.start >= s && p.end <= e)
.map(|p| PillChip { start: p.start - s, end: p.end - s, ..p.clone() }).collect();
let blocks = [c.blocks.get(k).copied().unwrap_or(Block::Paragraph)];
let l = ts.layout_blocks_inner(text, &spans, &blocks, &pills, c.style, scale, width, c.align, c.wrap_anywhere, true);
laid.push((start, l, pills.len() as u64));
}
let widest = laid.iter().map(|p| p.1.width()).fold(0.0f32, f32::max) as f64;
for (k, (start, l, pills)) in laid.into_iter().enumerate() {
let keep = if k + 1 < paras.len() { l.len() - 1 } else { l.len() };
let share = match (c.align, l.is_rtl()) {
(Alignment::Center, _) => 0.5,
(Alignment::End, false) | (Alignment::Start | Alignment::Justify, true) => 1.0,
_ => 0.0,
};
let dx = if fix && width.is_none() { (widest - l.width() as f64) * share } else { 0.0 };
size[0] = size[0].max(l.full_width() as f64);
size[1] = size[1].max(l.width() as f64);
size[3] += keep as f64;
y += rows(&l, start, (dx, y), pill0, keep, fix, &mut out);
pill0 += pills;
}
size[2] = y;
out.insert(0, ("size", size.to_vec()));
out
}
/// Rows that differ, the largest difference in px, and the first differing pair.
fn diff(a: &[Row], b: &[Row]) -> (usize, f64, String) {
let (mut n, mut max, mut first) = (a.len().abs_diff(b.len()), 0.0f64, String::new());
if n > 0 { max = f64::INFINITY; first = format!("{} rows vs {}", a.len(), b.len()); }
for (x, y) in a.iter().zip(b) {
let d = if x.0 != y.0 || x.1.len() != y.1.len() { f64::INFINITY } else {
x.1.iter().zip(&y.1).map(|(p, q)| (p - q).abs()).fold(0.0, f64::max)
};
if d > 0.0 {
n += 1;
if first.is_empty() {
let short = |r: &Row| format!("{} {:?}", r.0, &r.1[..r.1.len().min(9)]);
first = format!("{} | {}", short(x), short(y));
}
max = max.max(d);
}
}
(n, max, first)
}
#[test]
fn paragraphs_stack_like_one_layout() {
let mut ts = TextSystem::default();
let shapes: [(&[&str], bool); 4] = [(&["case", "plain", "empty", "case"], false), (&["plain", "case"], false),
(&["case", "plain", "empty", "case"], true), (&["case"], true)];
let (mut runs, mut exact, mut ulp) = (0, [0; 3], [0; 3]);
for c in cases() {
for (parts, trailing) in shapes {
let j = join(&c, parts, trailing);
for scale in [1.0, 2.0] {
for width in [Some(1200.0), Some(433.5), Some(210.0), None] {
for (m, mode) in ["auto", "forced", "forced+fix"].iter().enumerate() {
(ts.layouts.clear(), ts.shapes.clear());
let (one, rtl) = whole(&mut ts, &j, scale, width);
let dir = if rtl { parley::BaseDirection::Rtl } else { parley::BaseDirection::Ltr };
FORCE_DIR.set((m >= 1).then_some(dir));
(ts.layouts.clear(), ts.shapes.clear());
let many = stacked(&mut ts, &j, scale, width, m == 2);
FORCE_DIR.set(None);
let (n, max, first) = diff(&one, &many);
runs += usize::from(m == 0);
if n == 0 { exact[m] += 1 } else if max < 1e-3 { ulp[m] += 1 }
if max >= 1e-3 {
println!("MISMATCH {mode} {} @{scale}x w={width:?}: {n}/{} rows, max {max:.3} px\n {first}", j.name, one.len());
}
}
}
}
}
}
println!("SUMMARY runs={runs} auto: exact={} ulp={} | forced: exact={} ulp={} | forced+fix: exact={} ulp={}",
exact[0], ulp[0], exact[1], ulp[1], exact[2], ulp[2]);
}
// The `edit` workload: the 50 KB note of `layout_text_cost` (copied from its generator).
const WORDS: &[&str] = &["amber", "lantern", "orchard", "quiet", "harbor", "copper", "meadow", "signal", "drift",
"pebble", "willow", "ember", "tide", "cinder", "fable", "glacier", "hollow", "juniper", "kestrel", "lumen",
"marrow", "nimbus", "opal", "prism", "quill", "ripple", "sable", "thistle", "umber", "vellum", "wander",
"yarrow", "zephyr", "bramble", "cobalt", "dune", "fern", "grove", "heron", "isle", "the", "a", "of", "and",
"to", "in", "with", "under", "over", "before"];
fn note(bytes: usize) -> String {
let mut s = 0x9e37_79b9_7f4a_7c15u64;
let mut r = |n: usize| { s ^= s << 13; s ^= s >> 7; s ^= s << 17; (s % n as u64) as usize };
let w = |r: &mut dyn FnMut(usize) -> usize, n: usize| (0..n).map(|_| WORDS[r(WORDS.len())]).collect::<Vec<_>>().join(" ");
let rich = |r: &mut dyn FnMut(usize) -> usize, n: usize| (0..n).map(|_| {
let x = WORDS[r(WORDS.len())];
match r(24) {
0 => format!("**{x} {}**", WORDS[r(WORDS.len())]),
1 => format!("*{x}*"),
2 => format!("`{x}_{}`", r(100)),
3 => format!("[{x}](https://example.com/{x})"),
_ => x.to_string(),
}
}).collect::<Vec<_>>().join(" ");
let (mut out, mut section) = (String::new(), 0);
while out.len() < bytes {
section += 1;
out += &format!("# Section {section}: {}\n\n", w(&mut r, 3));
for sub in 0..3 {
out += &format!("## {} {sub}\n\n", w(&mut r, 2));
for _ in 0..2 { let n = 25 + r(60); out += &rich(&mut r, n); out += ".\n\n"; }
for i in 0..4 + r(5) {
let n = 4 + r(10);
let item = rich(&mut r, n);
out += &if sub % 2 == 0 { format!("- {item}\n") } else { format!("{}. {item}\n", i + 1) };
}
out += "\n";
match r(3) {
0 => {
out += "```rust\n";
for i in 0..5 + r(6) {
let (name, call) = (WORDS[r(WORDS.len())], WORDS[r(WORDS.len())]);
out += &format!(" let {name}_{i} = {call}(\"{}\");\n", w(&mut r, 2));
}
out += "```\n\n";
}
1 => { let n = 12 + r(20); out += &format!("> {}\n\n", rich(&mut r, n)); }
_ => { for _ in 0..3 { let n = 3 + r(6); out += &format!("- [ ] {}\n", rich(&mut r, n)); } out += "\n"; }
}
}
}
out
}
/// This thread's CPU clock, ms.
fn cpu_ms() -> f64 {
let mut t = libc::timespec { tv_sec: 0, tv_nsec: 0 };
// SAFETY: `t` is a valid timespec for the call to fill.
unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut t) };
t.tv_sec as f64 * 1e3 + t.tv_nsec as f64 / 1e6
}
fn median(v: &mut [f64]) -> (f64, f64) {
v.sort_by(f64::total_cmp);
(v[v.len() / 2], v[((v.len() - 1) as f64 * 0.95).round() as usize])
}
/// Each keystroke types `w` mid-note, as `layout_text_cost --case edit` does, then lays out:
/// whole (one layout), naive (every paragraph through the layout cache) or incremental (only
/// the edited paragraph; the others keep their `Rc`). Modes alternate order every keystroke.
#[test]
#[ignore]
fn bench_edit_keystroke() {
let src = note(50 * 1024);
let style = TextStyle::new(15.0, 400.0).lh(22.0);
let lay = |ts: &mut TextSystem, t: &str| ts.layout_blocks_inner(t, &[], &[], &[], style, 2.0, Some(696.0 * 2.0), Alignment::Start, false, true);
struct Mode { ts: TextSystem, text: String, caret: usize, paras: Vec<(usize, Rc<Layout<Ink>>)>, cpu: Vec<f64>, peak: Vec<f64>, heap: isize, open: isize }
let mut modes: Vec<Mode> = (0..3).map(|_| {
let mut ts = TextSystem::default();
lay(&mut ts, "Warm fonts and a few words");
for _ in 0..3 { ts.end_commit(); }
Mode { ts, text: src.clone(), caret: src[..src.len() / 2].rfind(' ').unwrap() + 1, paras: vec![], cpu: vec![], peak: vec![], heap: 0, open: 0 }
}).collect();
let step = |k: usize, m: &mut Mode, typed: bool| {
if typed { m.text.insert(m.caret, 'w'); m.caret += 1; }
match k {
0 => { lay(&mut m.ts, &m.text); }
1 => { let ls: Vec<_> = split(&m.text).into_iter().map(|(s, p)| (s, lay(&mut m.ts, p))).collect(); m.paras = ls; }
_ if m.paras.is_empty() => { m.paras = split(&m.text).into_iter().map(|(s, p)| (s, lay(&mut m.ts, p))).collect(); }
_ => {
let i = m.paras.partition_point(|p| p.0 < m.caret) - 1;
for p in &mut m.paras[i + 1..] { p.0 += 1; }
let end = m.paras.get(i + 1).map_or(m.text.len(), |p| p.0);
m.paras[i].1 = lay(&mut m.ts, &m.text[m.paras[i].0..end]);
}
}
// The prefix index a composite keeps: each paragraph's top, from the heights above it.
let mut y = 0.0f64;
let tops: Vec<f64> = m.paras.iter().map(|p| { let t = y; y += p.1.height() as f64; t }).collect();
std::hint::black_box(tops);
m.ts.end_commit();
};
for (k, m) in modes.iter_mut().enumerate() {
let live = crate::test_alloc::live();
step(k, m, false);
m.open = crate::test_alloc::live() - live;
for _ in 0..3 { step(k, m, true); }
}
let mut mid = [0isize; 3];
for i in 0..480 {
if i == 120 { for k in 0..3 { mid[k] = modes[k].open + modes[k].heap; } }
for j in 0..3 {
let k = if i % 2 == 0 { j } else { 2 - j };
let m = &mut modes[k];
let (live, cpu) = (crate::test_alloc::live(), cpu_ms());
let ((), peak) = crate::test_alloc::peak(|| step(k, m, true));
m.cpu.push(cpu_ms() - cpu);
m.heap += crate::test_alloc::live() - live;
m.peak.push(peak as f64 / 1e6);
}
}
let n = split(&modes[0].text).len();
let edited = split(&modes[2].text).into_iter().filter(|p| p.0 < modes[2].caret).last().unwrap().1.len();
println!("EDIT edited_paragraph_bytes={edited}");
for (k, m) in modes.iter_mut().enumerate() {
// Stale entries only: live paragraphs stay alive through `m.paras`.
let live = crate::test_alloc::live();
(m.ts.layouts.clear(), m.ts.shapes.clear());
println!("EDIT mode={} stale_cache_mb={:.2}", ["whole", "naive", "incremental"][k], (live - crate::test_alloc::live()) as f64 / 1e6);
let (cpu, cpu95) = median(&mut m.cpu);
let (peak, _) = median(&mut m.peak);
println!("EDIT mode={} paragraphs={n} cpu_ms median={cpu:.3} p95={cpu95:.3} open_heap_mb={:.2} heap_at_120_mb={:.2} heap_at_480_mb={:.2} keystroke_peak_mb={peak:.2} shaped={} cached_layouts={}",
["whole", "naive", "incremental"][k], m.open as f64 / 1e6, mid[k] as f64 / 1e6, (m.open + m.heap) as f64 / 1e6, m.ts.shaped, m.ts.layouts.len());
}
}
// Word cache: Parley shaping and breaking each `\n` paragraph, against a cache of shaped words
// over `parley_engine` (shaped alone on a miss) with a greedy breaker at spaces.
struct OneFont<'a>(&'a parley_engine::FontInstance);
impl parley_engine::FontSelector for OneFont<'_> {
fn select_font(&mut self, _: &parley_engine::itemize::Segment, _: &parley_engine::ShapeOptions<'_>,
_: &mut parley_engine::shape::CharCluster) -> Option<parley_engine::FontInstanceRef<'_>> {
Some(self.0.as_ref())
}
}
#[derive(Default)]
struct Fx(u64);
impl Hasher for Fx {
fn finish(&self) -> u64 { self.0 }
fn write(&mut self, bytes: &[u8]) { for &b in bytes { self.0 = (self.0.rotate_left(5) ^ b as u64).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95); } }
}
#[derive(Default)]
struct Engine { analyzer: parley_engine::Analyzer, analysis: parley_engine::Analysis, shaper: parley_engine::Shaper, shaped: parley_engine::ShapedText, styles: Vec<u16> }
impl Engine {
fn shape(&mut self, word: &str, font: &parley_engine::FontInstance, px: f32) -> (f32, Vec<parley_engine::Glyph>) {
self.analyzer.analyze(word, &parley_engine::AnalysisOptions::default(), &mut self.analysis);
let n = self.analysis.char_info().len();
(self.styles.clear(), self.styles.resize(n, 0));
let options = parley_engine::ShapeOptions { font_size: px, language: None, features: &[], variations: &[] };
let item = parley_engine::itemize::Item { char_end: n as u32, options };
self.shaper.shape_text(word, &self.analysis, &self.styles, [item], OneFont(font), &mut self.shaped);
let glyphs = self.shaped.glyphs().to_vec();
(glyphs.iter().map(|g| g.advance).sum(), glyphs)
}
}
#[test]
#[ignore]
fn bench_word_cache() {
let mut collection = Collection::new(CollectionOptions { shared: false, system_fonts: false });
for data in [&include_bytes!("../../crates/rune/assets/Inter-Regular.ttf")[..], include_bytes!("../../crates/rune/assets/IBMPlexMono-Regular.ttf")] {
collection.register_fonts(Blob::new(Arc::new(data)), None);
}
let mut fcx = FontContext { collection, source_cache: SourceCache::default() };
let mut lcx = LayoutContext::<Ink>::new();
let (scale, width) = (2.0f32, 696.0f32 * 2.0);
let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../../");
for (file, family, size) in [("PLAN.md", "Inter", 15.0f32), ("CHANGELOG.md", "Inter", 15.0), ("crates/rune/src/runtime.rs", "IBM Plex Mono", 13.0)] {
let all = std::fs::read_to_string(format!("{root}{file}")).unwrap();
let text = &all[..all[..all.len().min(50 * 1024)].rfind('\n').unwrap()];
let paras: Vec<&str> = text.split('\n').collect();
let families = [FontFamilyName::named(family)];
let mut parley = |lcx: &mut LayoutContext<Ink>, p: &str| {
let mut b = lcx.ranged_builder(&mut fcx, p, scale, true);
b.push_default(FontFamily::from(families.as_slice()));
b.push_default(StyleProperty::FontSize(size));
b.push_default(LineHeight::Absolute(size * 1.5));
let mut l: Layout<Ink> = b.build(p);
l.break_all_lines(Some(width));
l
};
let probe = parley(&mut lcx, "x");
let font = probe.lines().next().unwrap().runs().next().unwrap().font().clone();
let font = parley_engine::FontInstance { font, synthesis: Default::default() };
let px = size * scale;
// Tokens and how many a per-word cache shapes: one per distinct word.
let words: Vec<&str> = paras.iter().flat_map(|p| p.split(' ')).filter(|w| !w.is_empty()).collect();
let distinct = words.iter().collect::<std::collections::HashSet<_>>().len();
let mut engine = Engine::default();
type Words = HashMap<Box<str>, (f32, Vec<parley_engine::Glyph>), std::hash::BuildHasherDefault<Fx>>;
let mut warm: Words = HashMap::default();
let cached = |engine: &mut Engine, analyze: bool, cache: &mut Words| {
let space = engine.shape(" ", &font, px).0;
let mut lines: Vec<(u32, f32)> = Vec::new();
for p in &paras {
if analyze { engine.analyzer.analyze(p, &parley_engine::AnalysisOptions::default(), &mut engine.analysis); }
let mut x = 0.0f32;
for (i, w) in p.split(' ').enumerate() {
let adv = if w.is_empty() { 0.0 } else if let Some(e) = cache.get(w) { e.0 } else {
let e = engine.shape(w, &font, px);
let adv = e.0;
cache.insert(w.into(), e);
adv
};
let next = if i == 0 { adv } else { x + space + adv };
if next > width && x > 0.0 { lines.push((i as u32, x)); x = adv } else { x = next }
}
lines.push((u32::MAX, x));
}
std::hint::black_box(&lines);
cache.len()
};
let (mut t, mut parley_lines) = ([vec![], vec![], vec![], vec![]], 0);
for round in 0..21 {
for j in 0..4 {
let k = if round % 2 == 0 { j } else { 3 - j };
let cpu = cpu_ms();
match k {
0 => parley_lines = paras.iter().map(|p| parley(&mut lcx, p).len()).sum(),
1 => { cached(&mut engine, false, &mut HashMap::default()); }
2 => { cached(&mut engine, true, &mut HashMap::default()); }
_ => { cached(&mut engine, true, &mut warm); }
}
if round > 0 { t[k].push(cpu_ms() - cpu); }
}
}
let [a, b, c, d] = t.map(|mut v: Vec<f64>| median(&mut v).0);
println!("WORDCACHE file={file} bytes={} paragraphs={} lines={parley_lines} tokens={} distinct={distinct} hit_rate={:.1}% \
parley_ms={a:.2} cache_ms={b:.2} cache_plus_analysis_ms={c:.2} speedup={:.2}x speedup_with_analysis={:.2}x warm_ms={d:.2} warm_speedup={:.2}x",
text.len(), paras.len(), words.len(), 100.0 * (1.0 - distinct as f64 / words.len() as f64), a / b, a / c, a / d);
}
}
+27
View File
@@ -0,0 +1,27 @@
# Probes behind research/35-wgpu-vulkan-dx12-cost.md. Not a workspace member: build it from this
# directory. `wgpu_frame` draws research/30's HUD frame through wgpu; `vk_floor` and `dx12_floor`
# draw the same frame on the raw API with the fewest calls it allows.
[package]
name = "gpu-floor"
version = "0.0.0"
edition = "2024"
publish = false
[workspace]
[dependencies]
wgpu = { version = "~30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "dx12", "wgsl"] }
winit = { version = "0.30.13", default-features = false, features = ["rwh_06", "x11"] }
pollster = "1"
ash = "0.38"
ash-window = "0.13"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows = { version = "0.58", features = ["Win32_Foundation", "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", "Win32_System_Threading", "Win32_Security"] }
[profile.release]
codegen-units = 16
debug = false
+206
View File
@@ -0,0 +1,206 @@
#!/usr/bin/env python3
"""Split a callgrind profile's instructions into Rune, wgpu, wgpu-core, wgpu-hal, driver and
other, and count the driver entry points that non-driver code calls.
cgsplit.py PROFILE [--frames N | --frame-fn SUBSTRING] [--top N]
A function belongs to a component by its crate (the first path segment of its demangled name)
or, for C code, by its object file. Code that belongs to no component (std, alloc, hashbrown,
libc, ...) is charged to its callers in proportion to the inclusive cost of each call edge, so
a `Vec` growth inside wgpu-core counts as wgpu-core. Per-frame numbers divide by `--frames`
or by the call count of the first function whose name contains `--frame-fn`.
"""
import argparse
import collections
import re
import sys
DRIVER_OBJECTS = ("libvulkan_lvp", "libgallium", "libLLVM", "libvulkan.so", "libvkd3d", "d3d12", "dxgi")
CRATES = {
"wgpu_core": "wgpu-core",
"wgpu_hal": "wgpu-hal",
"ash": "wgpu-hal",
"gpu_alloc": "wgpu-hal",
"gpu_descriptor": "wgpu-hal",
"wgpu": "wgpu",
"wgpu_types": "wgpu",
"naga": "wgpu-core",
"floor": "probe",
"wgpu_frame": "probe",
"vk_floor": "probe",
"dx12_floor": "probe",
}
COMPONENTS = ("rune", "probe", "wgpu", "wgpu-core", "wgpu-hal", "driver", "platform", "other")
def crate_of(name):
s = name.lstrip("<&*")
if s.startswith("mut "):
s = s[4:]
if s.startswith("dyn "):
s = s[4:]
m = re.match(r"([A-Za-z_][A-Za-z0-9_]*)::", s)
return m.group(1) if m else None
def classify(name, obj):
if any(d in obj for d in DRIVER_OBJECTS):
return "driver"
crate = crate_of(name)
if crate is None:
return None
if crate in CRATES:
return CRATES[crate]
if crate.startswith("rune") or crate in ("overlay_hud_cost", "upload_bench", "layout_text_cost"):
return "rune"
if crate in ("winit", "x11rb", "x11_dl", "wayland_client", "wayland_backend", "calloop", "sctk", "smithay_client_toolkit"):
return "platform"
return None
def parse(path):
names = {"fn": {}, "ob": {}}
self_cost = collections.Counter()
edges = collections.defaultdict(lambda: [0, 0]) # (caller, callee) -> [calls, inclusive]
obj_of = {}
ob = fn = cob = cfn = None
pending_call = None
def resolve(kind, rest):
rest = rest.strip()
m = re.match(r"\((\d+)\)(?:\s+(.*))?$", rest)
if not m:
return rest
key, text = m.group(1), m.group(2)
if text is not None:
names[kind][key] = text
return names[kind].get(key, key)
with open(path, errors="replace") as f:
for line in f:
line = line.rstrip("\n")
if not line:
continue
c = line[0]
if c.isdigit() or c in "+-*":
parts = line.split()
cost = int(parts[1]) if len(parts) > 1 else 0
if pending_call is not None:
e = edges[(fn, pending_call[0])]
e[0] += pending_call[1]
e[1] += cost
pending_call = None
cob = None
else:
self_cost[fn] += cost
continue
if line.startswith("ob="):
ob = resolve("ob", line[3:])
elif line.startswith("fn="):
fn = resolve("fn", line[3:])
obj_of[fn] = ob
cob = None
elif line.startswith("cob="):
cob = resolve("ob", line[4:])
elif line.startswith("cfn="):
cfn = resolve("fn", line[4:])
obj_of.setdefault(cfn, cob or ob)
elif line.startswith("calls="):
pending_call = (cfn, int(line[6:].split()[0]))
return self_cost, edges, obj_of
def attribute(self_cost, edges, obj_of):
fns = set(self_cost) | {a for a, _ in edges} | {b for _, b in edges}
cls = {f: classify(f or "", obj_of.get(f) or "") for f in fns}
incoming = collections.defaultdict(list)
for (a, b), (_, inc) in edges.items():
if a != b:
incoming[b].append((a, inc))
dist = {f: ({cls[f]: 1.0} if cls[f] else {"other": 1.0}) for f in fns}
for _ in range(40):
changed = False
for f in fns:
if cls[f]:
continue
acc = collections.Counter()
total = 0
for a, inc in incoming.get(f, ()):
if inc <= 0:
continue
for k, v in dist[a].items():
acc[k] += inc * v
total += inc
if total:
new = {k: v / total for k, v in acc.items()}
if new != dist[f]:
dist[f] = new
changed = True
if not changed:
break
out = collections.Counter()
for f, c in self_cost.items():
for k, v in dist[f].items():
out[k] += c * v
return out, cls, dist
def main():
p = argparse.ArgumentParser()
p.add_argument("profile")
p.add_argument("--frames", type=float)
p.add_argument("--frame-fn")
p.add_argument("--top", type=int, default=40)
p.add_argument("--calls", action="store_true", help="list per-frame calls of every wgpu-core and wgpu-hal entry")
a = p.parse_args()
self_cost, edges, obj_of = parse(a.profile)
frames = a.frames
if a.frame_fn:
calls = collections.Counter()
for (x, y), (n, _) in edges.items():
if y and a.frame_fn in y:
calls[y] += n
if not calls:
sys.exit(f"no function matches {a.frame_fn!r}")
name, frames = calls.most_common(1)[0]
print(f"frames: {frames} calls of {name}")
frames = frames or 1
split, cls, dist = attribute(self_cost, edges, obj_of)
total = sum(split.values())
print(f"total Ir: {total:,.0f} per frame: {total / frames / 1e3:,.1f} k")
for k in COMPONENTS:
if split.get(k):
print(f" {k:10s} {split[k] / frames / 1e3:10.1f} k/frame {100 * split[k] / total:5.1f}%")
api = collections.Counter()
api_cost = collections.Counter()
for (x, y), (n, inc) in edges.items():
if cls.get(y) == "driver" and dist.get(x, {}).get("driver", 0) < 0.5:
api[y] += n
api_cost[y] += inc
print("driver entry points called from outside the driver (per frame, inclusive k):")
for name, n in sorted(api.items(), key=lambda kv: -api_cost[kv[0]])[: a.top]:
print(f" {n / frames:8.2f} {api_cost[name] / frames / 1e3:9.1f}k {name}")
allocs = collections.Counter()
for (x, y), (n, _) in edges.items():
if y in ("malloc", "calloc", "realloc", "aligned_alloc", "posix_memalign", "memalign"):
for k, v in dist.get(x, {"other": 1.0}).items():
allocs[k] += n * v
print("heap allocations per frame by component: " + ", ".join(
f"{k} {allocs[k] / frames:.1f}" for k in COMPONENTS if allocs.get(k, 0) / frames >= 0.05))
wgpu = ("wgpu", "wgpu-core", "wgpu-hal")
entry = collections.Counter()
entry_calls = collections.Counter()
for (x, y), (n, inc) in edges.items():
cy = cls.get(y)
if cy in wgpu and max(dist.get(x, {}), key=dist.get(x, {}).get, default=None) not in wgpu:
entry[y] += inc
entry_calls[y] += n
print("wgpu entry points called from outside wgpu (per frame, inclusive k):")
for name, inc in entry.most_common(a.top):
if inc / frames >= 100:
print(f" {entry_calls[name] / frames:8.2f} {inc / frames / 1e3:9.1f}k {name[:150]}")
if __name__ == "__main__":
main()
+220
View File
@@ -0,0 +1,220 @@
//! research/30's HUD frame on raw D3D12 with the fewest calls the API allows: one command list,
//! two transition barriers (PRESENT -> RENDER_TARGET -> PRESENT, which D3D12 requires for a
//! swapchain buffer), one `ExecuteCommandLists`, one `Present`, one `Signal`. Views are made once.
//!
//! `WRITES=n` writes a 256-byte uniform `n` times a frame. `UPLOAD=mapped` (default) copies into a
//! persistently mapped upload-heap ring with no API call. `UPLOAD=copy` also records a
//! `CopyBufferRegion` per write into a default-heap buffer and one COPY_DEST -> constant-buffer
//! barrier; the buffer decays back to COMMON when the list finishes, so it needs no second one.
#[path = "../count.rs"]
mod count;
#[path = "../harness.rs"]
mod harness;
#[cfg(not(windows))]
fn main() {
eprintln!("dx12_floor runs on Windows (or under Wine with vkd3d)");
}
#[cfg(windows)]
fn main() {
harness::run("dx12_floor", |window| Box::new(unsafe { imp::Floor::new(window) }));
}
#[cfg(windows)]
mod imp {
use std::mem::ManuallyDrop;
use std::sync::Arc;
use windows::Win32::Foundation::{HANDLE, HWND};
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::Win32::Graphics::Dxgi::*;
use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
use windows::core::Interface;
use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle};
use winit::window::Window;
use crate::harness::{Draw, env};
const IN_FLIGHT: usize = 2;
const BUFFERS: usize = 3;
const SLOT: u64 = 256;
pub struct Floor {
_window: Arc<Window>,
queue: ID3D12CommandQueue,
swapchain: IDXGISwapChain3,
targets: Vec<(ID3D12Resource, D3D12_CPU_DESCRIPTOR_HANDLE)>,
_heap: ID3D12DescriptorHeap,
allocators: [ID3D12CommandAllocator; IN_FLIGHT],
list: ID3D12GraphicsCommandList,
fence: ID3D12Fence,
event: HANDLE,
values: [u64; IN_FLIGHT],
next: u64,
mapped: *mut u8,
staging: ID3D12Resource,
uniforms: ID3D12Resource,
writes: usize,
copy: bool,
frame: usize,
}
unsafe fn buffer(device: &ID3D12Device, size: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES) -> ID3D12Resource {
let props = D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() };
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
};
let mut resource = None;
unsafe { device.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut resource).unwrap() };
resource.unwrap()
}
fn transition(resource: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
// Borrowed for the call, not AddRef'd.
pResource: unsafe { std::mem::transmute_copy(resource) },
Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
StateBefore: before,
StateAfter: after,
}),
},
}
}
impl Floor {
pub unsafe fn new(window: Arc<Window>) -> Floor {
unsafe {
let RawWindowHandle::Win32(handle) = window.window_handle().unwrap().as_raw() else { panic!("not Win32") };
let hwnd = HWND(handle.hwnd.get() as *mut _);
let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
let adapter: IDXGIAdapter1 = factory.EnumAdapters1(0).unwrap();
let mut device: Option<ID3D12Device> = None;
D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut device).unwrap();
let device = device.unwrap();
let queue: ID3D12CommandQueue = device
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })
.unwrap();
let desc = DXGI_SWAP_CHAIN_DESC1 {
Width: 360,
Height: 80,
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
BufferCount: BUFFERS as u32,
SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
..Default::default()
};
let swapchain: IDXGISwapChain3 = factory.CreateSwapChainForHwnd(&queue, hwnd, &desc, None, None).unwrap().cast().unwrap();
let heap: ID3D12DescriptorHeap = device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
NumDescriptors: BUFFERS as u32,
..Default::default()
})
.unwrap();
let start = heap.GetCPUDescriptorHandleForHeapStart();
let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize;
let view = D3D12_RENDER_TARGET_VIEW_DESC {
Format: DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D,
..Default::default()
};
let targets = (0..BUFFERS)
.map(|i| {
let resource: ID3D12Resource = swapchain.GetBuffer(i as u32).unwrap();
let handle = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i * step };
device.CreateRenderTargetView(&resource, Some(&view), handle);
(resource, handle)
})
.collect();
let allocators = [(); IN_FLIGHT].map(|_| device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap());
let list: ID3D12GraphicsCommandList =
device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocators[0], None).unwrap();
list.Close().unwrap();
let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
let event = CreateEventW(None, false, false, None).unwrap();
let writes = env("WRITES", 0usize);
let ring = SLOT * writes.max(1) as u64 * IN_FLIGHT as u64;
let staging = buffer(&device, ring, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ);
let mut mapped = std::ptr::null_mut();
staging.Map(0, None, Some(&mut mapped)).unwrap();
let uniforms = buffer(&device, SLOT, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON);
let copy = std::env::var("UPLOAD").as_deref() == Ok("copy");
Floor {
_window: window,
queue,
swapchain,
targets,
_heap: heap,
allocators,
list,
fence,
event,
values: [0; IN_FLIGHT],
next: 0,
mapped: mapped.cast(),
staging,
uniforms,
writes,
copy,
frame: 0,
}
}
}
}
impl Draw for Floor {
fn frame(&mut self) {
let f = self.frame % IN_FLIGHT;
self.frame += 1;
unsafe {
if self.fence.GetCompletedValue() < self.values[f] {
self.fence.SetEventOnCompletion(self.values[f], self.event).unwrap();
WaitForSingleObject(self.event, INFINITE);
}
self.allocators[f].Reset().unwrap();
self.list.Reset(&self.allocators[f], None).unwrap();
let (target, rtv) = &self.targets[self.swapchain.GetCurrentBackBufferIndex() as usize];
let phase = (self.frame % 120) as f32 / 120.0;
let data = [phase.to_bits(); 64];
for w in 0..self.writes {
let offset = (f * self.writes + w) as u64 * SLOT;
std::ptr::copy_nonoverlapping(data.as_ptr().cast::<u8>(), self.mapped.add(offset as usize), SLOT as usize);
if self.copy {
self.list.CopyBufferRegion(&self.uniforms, 0, &self.staging, offset, SLOT);
}
}
let mut barriers = Vec::with_capacity(2);
if self.copy && self.writes > 0 {
barriers.push(transition(&self.uniforms, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER));
}
barriers.push(transition(target, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET));
self.list.ResourceBarrier(&barriers);
self.list.ClearRenderTargetView(*rtv, &[0.0, 0.0, phase * 0.4, 0.4], None);
self.list.ResourceBarrier(&[transition(target, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT)]);
self.list.Close().unwrap();
self.queue.ExecuteCommandLists(&[Some(self.list.cast().unwrap())]);
self.swapchain.Present(1, DXGI_PRESENT(0)).ok().unwrap();
self.next += 1;
self.queue.Signal(&self.fence, self.next).unwrap();
self.values[f] = self.next;
}
}
}
}
+194
View File
@@ -0,0 +1,194 @@
//! research/30's HUD frame on raw Vulkan with the fewest calls the API allows: one command
//! buffer, a render pass whose layouts do the swapchain transitions (no `vkCmdPipelineBarrier`),
//! one `vkQueueSubmit`, one present. Views, framebuffers and the render pass are made once.
//!
//! `WRITES=n` writes a 256-byte uniform `n` times a frame. `UPLOAD=mapped` (default) copies into
//! a persistently mapped host-visible ring, as on a unified-memory or resizable-BAR GPU, with no
//! API call. `UPLOAD=copy` stages the bytes and records a `vkCmdCopyBuffer` per write into a
//! device-local buffer, then one buffer barrier, in the frame's command buffer.
#[path = "../count.rs"]
mod count;
#[path = "../harness.rs"]
mod harness;
use std::sync::Arc;
use ash::vk;
use harness::{Draw, env};
use winit::raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use winit::window::Window;
const IN_FLIGHT: usize = 2;
const SLOT: u64 = 256;
struct Floor {
_window: Arc<Window>,
device: ash::Device,
swapchain_fn: ash::khr::swapchain::Device,
swapchain: vk::SwapchainKHR,
queue: vk::Queue,
render_pass: vk::RenderPass,
framebuffers: Vec<vk::Framebuffer>,
extent: vk::Extent2D,
pools: [vk::CommandPool; IN_FLIGHT],
cmds: [vk::CommandBuffer; IN_FLIGHT],
fences: [vk::Fence; IN_FLIGHT],
acquired: [vk::Semaphore; IN_FLIGHT],
rendered: Vec<vk::Semaphore>,
mapped: *mut u8,
staging: vk::Buffer,
uniforms: vk::Buffer,
writes: usize,
copy: bool,
frame: usize,
}
fn memory_type(instance: &ash::Instance, pd: vk::PhysicalDevice, bits: u32, flags: vk::MemoryPropertyFlags) -> u32 {
let props = unsafe { instance.get_physical_device_memory_properties(pd) };
(0..props.memory_type_count)
.find(|&i| bits & (1 << i) != 0 && props.memory_types[i as usize].property_flags.contains(flags))
.expect("memory type")
}
unsafe fn buffer(instance: &ash::Instance, pd: vk::PhysicalDevice, device: &ash::Device, size: u64, usage: vk::BufferUsageFlags,
flags: vk::MemoryPropertyFlags) -> (vk::Buffer, vk::DeviceMemory) {
unsafe {
let buffer = device.create_buffer(&vk::BufferCreateInfo::default().size(size).usage(usage), None).unwrap();
let req = device.get_buffer_memory_requirements(buffer);
let info = vk::MemoryAllocateInfo::default().allocation_size(req.size).memory_type_index(memory_type(instance, pd, req.memory_type_bits, flags));
let memory = device.allocate_memory(&info, None).unwrap();
device.bind_buffer_memory(buffer, memory, 0).unwrap();
(buffer, memory)
}
}
impl Floor {
unsafe fn new(window: Arc<Window>) -> Floor {
unsafe {
let entry = ash::Entry::load().expect("libvulkan");
let display = window.display_handle().unwrap().as_raw();
let exts = ash_window::enumerate_required_extensions(display).unwrap();
let app = vk::ApplicationInfo::default().api_version(vk::API_VERSION_1_2);
let instance = entry.create_instance(&vk::InstanceCreateInfo::default().application_info(&app).enabled_extension_names(exts), None).unwrap();
let surface = ash_window::create_surface(&entry, &instance, display, window.window_handle().unwrap().as_raw(), None).unwrap();
let surface_fn = ash::khr::surface::Instance::new(&entry, &instance);
let (pd, family) = instance.enumerate_physical_devices().unwrap().into_iter().find_map(|pd| {
instance.get_physical_device_queue_family_properties(pd).iter().enumerate().find_map(|(i, q)| {
let present = surface_fn.get_physical_device_surface_support(pd, i as u32, surface).unwrap_or(false);
(q.queue_flags.contains(vk::QueueFlags::GRAPHICS) && present).then_some((pd, i as u32))
})
}).expect("a device that presents");
let name = instance.get_physical_device_properties(pd).device_name_as_c_str().unwrap().to_owned();
eprintln!("device: {name:?}");
let priorities = [1.0];
let queues = [vk::DeviceQueueCreateInfo::default().queue_family_index(family).queue_priorities(&priorities)];
let dev_exts = [ash::khr::swapchain::NAME.as_ptr()];
let device = instance.create_device(pd, &vk::DeviceCreateInfo::default().queue_create_infos(&queues).enabled_extension_names(&dev_exts), None).unwrap();
let queue = device.get_device_queue(family, 0);
let caps = surface_fn.get_physical_device_surface_capabilities(pd, surface).unwrap();
let format = surface_fn.get_physical_device_surface_formats(pd, surface).unwrap().into_iter()
.find(|f| f.format == vk::Format::B8G8R8A8_SRGB).expect("BGRA8 sRGB");
let extent = vk::Extent2D { width: 360, height: 80 };
let swapchain_fn = ash::khr::swapchain::Device::new(&instance, &device);
let swapchain = swapchain_fn.create_swapchain(&vk::SwapchainCreateInfoKHR::default()
.surface(surface).min_image_count(caps.min_image_count.max(2) + 1).image_format(format.format)
.image_color_space(format.color_space).image_extent(extent).image_array_layers(1)
.image_usage(vk::ImageUsageFlags::COLOR_ATTACHMENT).pre_transform(caps.current_transform)
.composite_alpha(vk::CompositeAlphaFlagsKHR::OPAQUE).present_mode(vk::PresentModeKHR::FIFO).clipped(true), None).unwrap();
let attachment = [vk::AttachmentDescription::default().format(format.format).samples(vk::SampleCountFlags::TYPE_1)
.load_op(vk::AttachmentLoadOp::CLEAR).store_op(vk::AttachmentStoreOp::STORE)
.initial_layout(vk::ImageLayout::UNDEFINED).final_layout(vk::ImageLayout::PRESENT_SRC_KHR)];
let color = [vk::AttachmentReference { attachment: 0, layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL }];
let subpass = [vk::SubpassDescription::default().pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS).color_attachments(&color)];
// Orders the layout transition after the acquire semaphore's wait stage.
let dependency = [vk::SubpassDependency::default().src_subpass(vk::SUBPASS_EXTERNAL).dst_subpass(0)
.src_stage_mask(vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT).dst_stage_mask(vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT)
.dst_access_mask(vk::AccessFlags::COLOR_ATTACHMENT_WRITE)];
let render_pass = device.create_render_pass(&vk::RenderPassCreateInfo::default()
.attachments(&attachment).subpasses(&subpass).dependencies(&dependency), None).unwrap();
let images = swapchain_fn.get_swapchain_images(swapchain).unwrap();
let framebuffers = images.iter().map(|&image| {
let view = device.create_image_view(&vk::ImageViewCreateInfo::default().image(image).view_type(vk::ImageViewType::TYPE_2D)
.format(format.format).subresource_range(vk::ImageSubresourceRange::default()
.aspect_mask(vk::ImageAspectFlags::COLOR).level_count(1).layer_count(1)), None).unwrap();
let views = [view];
device.create_framebuffer(&vk::FramebufferCreateInfo::default().render_pass(render_pass).attachments(&views)
.width(extent.width).height(extent.height).layers(1), None).unwrap()
}).collect();
let rendered = images.iter().map(|_| device.create_semaphore(&Default::default(), None).unwrap()).collect();
let pools = [(); IN_FLIGHT].map(|_| device.create_command_pool(&vk::CommandPoolCreateInfo::default()
.flags(vk::CommandPoolCreateFlags::TRANSIENT).queue_family_index(family), None).unwrap());
let cmds = pools.map(|pool| device.allocate_command_buffers(&vk::CommandBufferAllocateInfo::default()
.command_pool(pool).command_buffer_count(1)).unwrap()[0]);
let fences = [(); IN_FLIGHT].map(|_| device.create_fence(&vk::FenceCreateInfo::default().flags(vk::FenceCreateFlags::SIGNALED), None).unwrap());
let acquired = [(); IN_FLIGHT].map(|_| device.create_semaphore(&Default::default(), None).unwrap());
let writes = env("WRITES", 0usize);
let ring = SLOT * writes.max(1) as u64 * IN_FLIGHT as u64;
let host = vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT;
let (staging, staging_memory) = buffer(&instance, pd, &device, ring,
vk::BufferUsageFlags::UNIFORM_BUFFER | vk::BufferUsageFlags::TRANSFER_SRC, host);
let mapped = device.map_memory(staging_memory, 0, vk::WHOLE_SIZE, vk::MemoryMapFlags::empty()).unwrap().cast();
let (uniforms, _) = buffer(&instance, pd, &device, SLOT,
vk::BufferUsageFlags::UNIFORM_BUFFER | vk::BufferUsageFlags::TRANSFER_DST, vk::MemoryPropertyFlags::DEVICE_LOCAL);
let copy = std::env::var("UPLOAD").as_deref() == Ok("copy");
Floor { _window: window, device, swapchain_fn, swapchain, queue, render_pass, framebuffers, extent, pools, cmds, fences,
acquired, rendered, mapped, staging, uniforms, writes, copy, frame: 0 }
}
}
}
impl Draw for Floor {
fn frame(&mut self) {
let f = self.frame % IN_FLIGHT;
self.frame += 1;
let d = &self.device;
unsafe {
d.wait_for_fences(&[self.fences[f]], true, u64::MAX).unwrap();
d.reset_fences(&[self.fences[f]]).unwrap();
d.reset_command_pool(self.pools[f], vk::CommandPoolResetFlags::empty()).unwrap();
let (image, _) = self.swapchain_fn.acquire_next_image(self.swapchain, u64::MAX, self.acquired[f], vk::Fence::null()).unwrap();
let phase = (self.frame % 120) as f32 / 120.0;
let data = [phase.to_bits(); 64];
let cmd = self.cmds[f];
d.begin_command_buffer(cmd, &vk::CommandBufferBeginInfo::default().flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT)).unwrap();
for w in 0..self.writes {
let offset = (f * self.writes + w) as u64 * SLOT;
std::ptr::copy_nonoverlapping(data.as_ptr().cast::<u8>(), self.mapped.add(offset as usize), SLOT as usize);
if self.copy {
d.cmd_copy_buffer(cmd, self.staging, self.uniforms, &[vk::BufferCopy { src_offset: offset, dst_offset: 0, size: SLOT }]);
}
}
if self.copy && self.writes > 0 {
let barrier = [vk::BufferMemoryBarrier::default().buffer(self.uniforms).size(vk::WHOLE_SIZE)
.src_access_mask(vk::AccessFlags::TRANSFER_WRITE).dst_access_mask(vk::AccessFlags::UNIFORM_READ)];
d.cmd_pipeline_barrier(cmd, vk::PipelineStageFlags::TRANSFER, vk::PipelineStageFlags::VERTEX_SHADER | vk::PipelineStageFlags::FRAGMENT_SHADER,
vk::DependencyFlags::empty(), &[], &barrier, &[]);
}
let clear = [vk::ClearValue { color: vk::ClearColorValue { float32: [0.0, 0.0, phase * 0.4, 0.4] } }];
d.cmd_begin_render_pass(cmd, &vk::RenderPassBeginInfo::default().render_pass(self.render_pass)
.framebuffer(self.framebuffers[image as usize]).render_area(self.extent.into()).clear_values(&clear), vk::SubpassContents::INLINE);
d.cmd_end_render_pass(cmd);
d.end_command_buffer(cmd).unwrap();
let waits = [self.acquired[f]];
let stages = [vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT];
let cmds = [cmd];
let signals = [self.rendered[image as usize]];
let submit = [vk::SubmitInfo::default().wait_semaphores(&waits).wait_dst_stage_mask(&stages).command_buffers(&cmds).signal_semaphores(&signals)];
d.queue_submit(self.queue, &submit, self.fences[f]).unwrap();
let swapchains = [self.swapchain];
let images = [image];
self.swapchain_fn.queue_present(self.queue, &vk::PresentInfoKHR::default()
.wait_semaphores(&signals).swapchains(&swapchains).image_indices(&images)).unwrap();
}
}
}
fn main() {
harness::run("vk_floor", |window| Box::new(unsafe { Floor::new(window) }));
}
@@ -0,0 +1,96 @@
//! research/30's HUD frame through wgpu: acquire, `WRITES` 256-byte `Queue::write_buffer`s, one
//! pass that clears the drawable, submit, present. `BACKEND=vulkan|dx12` (default: the
//! platform's).
#[path = "../count.rs"]
mod count;
#[path = "../harness.rs"]
mod harness;
use std::sync::Arc;
use harness::{Draw, env};
use winit::window::Window;
struct Gpu {
_window: Arc<Window>,
surface: wgpu::Surface<'static>,
device: wgpu::Device,
queue: wgpu::Queue,
buffer: wgpu::Buffer,
writes: usize,
frame: u64,
}
impl Gpu {
fn new(window: Arc<Window>) -> Gpu {
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
desc.backends = match std::env::var("BACKEND").as_deref() {
Ok("dx12") => wgpu::Backends::DX12,
Ok("vulkan") => wgpu::Backends::VULKAN,
_ => wgpu::Backends::PRIMARY,
};
desc.flags.remove(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL);
let instance = wgpu::Instance::new(desc);
let surface = instance.create_surface(window.clone()).expect("surface");
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
compatible_surface: Some(&surface),
..Default::default()
}))
.expect("adapter");
eprintln!("adapter: {:?}", adapter.get_info());
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).expect("device");
let size = window.inner_size();
let mut config = surface.get_default_config(&adapter, size.width.max(1), size.height.max(1)).expect("config");
config.present_mode = wgpu::PresentMode::AutoVsync;
config.desired_maximum_frame_latency = 2;
surface.configure(&device, &config);
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("hud uniforms"),
size: 256,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
Gpu { _window: window, surface, device, queue, buffer, writes: env("WRITES", 0), frame: 0 }
}
}
impl Draw for Gpu {
fn frame(&mut self) {
self.frame += 1;
let frame = match self.surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(t) | wgpu::CurrentSurfaceTexture::Suboptimal(t) => t,
other => panic!("no drawable: {other:?}"),
};
let view = frame.texture.create_view(&Default::default());
let phase = (self.frame % 120) as f32 / 120.0;
let data = [phase.to_bits(); 64];
for _ in 0..self.writes {
// SAFETY: u32 has no padding.
let bytes = unsafe { std::slice::from_raw_parts(data.as_ptr().cast::<u8>(), 256) };
self.queue.write_buffer(&self.buffer, 0, bytes);
}
let mut encoder = self.device.create_command_encoder(&Default::default());
{
let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("hud"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.0, g: 0.0, b: phase as f64 * 0.4, a: 0.4 }),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
}
self.queue.submit([encoder.finish()]);
self.queue.present(frame);
}
}
fn main() {
harness::run("wgpu_frame", |window| Box::new(Gpu::new(window)));
}
+59
View File
@@ -0,0 +1,59 @@
//! Retired user and kernel instructions on the calling thread, from Linux `perf_event_open`, and
//! the thread's CPU time.
//! A Windows build makes the same syscalls directly, which works when it runs under Wine on
//! x86-64 Linux and reads zero elsewhere.
pub struct Counter {
fds: [i64; 2],
}
const PERF_EVENT_OPEN: i64 = 298;
const READ: i64 = 0;
const CLOCK_GETTIME: i64 = 228;
const CLOCK_THREAD_CPUTIME_ID: i64 = 3;
#[cfg(target_os = "linux")]
unsafe fn sys(n: i64, a: i64, b: i64, c: i64, d: i64, e: i64) -> i64 {
unsafe { libc::syscall(n, a, b, c, d, e) }
}
#[cfg(all(windows, target_arch = "x86_64"))]
unsafe fn sys(n: i64, a: i64, b: i64, c: i64, d: i64, e: i64) -> i64 {
let ret: i64;
unsafe {
std::arch::asm!("syscall", inlateout("rax") n => ret, in("rdi") a, in("rsi") b, in("rdx") c,
in("r10") d, in("r8") e, lateout("rcx") _, lateout("r11") _, options(nostack));
}
ret
}
impl Counter {
/// `None` when the kernel refuses (no PMU, `perf_event_paranoid` too high, not Linux).
pub fn new() -> Option<Counter> {
if cfg!(windows) && std::env::var_os("WINE_PERF").is_none() {
return None;
}
let open = |exclude_user: bool| {
// perf_event_attr, version 8 (136 bytes): type HARDWARE, config INSTRUCTIONS.
let mut attr = [0u64; 17];
attr[0] = (136u64 << 32) | 0;
attr[1] = 1;
attr[5] = if exclude_user { 1 << 4 } else { 1 << 5 } | 1 << 6;
unsafe { sys(PERF_EVENT_OPEN, attr.as_ptr() as i64, 0, -1, -1, 0) }
};
let fds = [open(false), open(true)];
(fds[0] >= 0 && fds[1] >= 0).then_some(Counter { fds })
}
/// (user instructions, kernel instructions, CPU nanoseconds) so far.
pub fn read(&self) -> (u64, u64, u64) {
let one = |fd: i64| {
let mut v = 0u64;
unsafe { sys(READ, fd, &mut v as *mut u64 as i64, 8, 0, 0) };
v
};
let mut ts = [0i64; 2];
unsafe { sys(CLOCK_GETTIME, CLOCK_THREAD_CPUTIME_ID, ts.as_mut_ptr() as i64, 0, 0, 0) };
(one(self.fds[0]), one(self.fds[1]), (ts[0] * 1_000_000_000 + ts[1]) as u64)
}
}
+93
View File
@@ -0,0 +1,93 @@
//! A 360×80 window that draws a frame as fast as the loop turns, then prints instructions per
//! frame and CPU time per frame on the drawing thread. `FRAMES` (2,000) are measured after `WARMUP` (300).
use std::sync::Arc;
use std::time::Instant;
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::{Window, WindowId};
use crate::count::Counter;
pub trait Draw {
fn frame(&mut self);
}
pub fn env<T: std::str::FromStr>(name: &str, default: T) -> T {
std::env::var(name).ok().and_then(|s| s.parse().ok()).unwrap_or(default)
}
struct Run<F> {
make: F,
draw: Option<(Arc<Window>, Box<dyn Draw>)>,
counter: Option<Counter>,
frames: u64,
warmup: u64,
measured: u64,
instructions: (u64, u64, u64),
started: Option<Instant>,
}
pub fn run(label: &str, make: impl FnMut(Arc<Window>) -> Box<dyn Draw> + 'static) {
let event_loop = EventLoop::new().expect("event loop");
event_loop.set_control_flow(ControlFlow::Poll);
let mut run = Run {
make,
draw: None,
counter: Counter::new(),
frames: 0,
warmup: env("WARMUP", 300),
measured: env("FRAMES", 2000),
instructions: (0, 0, 0),
started: None,
};
event_loop.run_app(&mut run).expect("run");
let n = run.measured as f64;
let wall = run.started.map(|s| s.elapsed().as_secs_f64()).unwrap_or(0.0);
println!(
"{label}: frames={} kinstr_user={:.2} kinstr_kernel={:.2} cpu_us={:.2} fps={:.0}",
run.measured,
run.instructions.0 as f64 / n / 1e3,
run.instructions.1 as f64 / n / 1e3,
run.instructions.2 as f64 / n / 1e3,
n / wall
);
}
impl<F: FnMut(Arc<Window>) -> Box<dyn Draw>> ApplicationHandler for Run<F> {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.draw.is_none() {
let attrs = Window::default_attributes().with_inner_size(winit::dpi::PhysicalSize::new(360, 80)).with_title("floor");
let window = Arc::new(event_loop.create_window(attrs).expect("window"));
self.draw = Some((window.clone(), (self.make)(window)));
}
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, _: WindowId, event: WindowEvent) {
if let WindowEvent::CloseRequested = event {
event_loop.exit();
}
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
let Some((_, draw)) = self.draw.as_mut() else { return };
let timed = self.frames >= self.warmup;
if timed && self.started.is_none() {
self.started = Some(Instant::now());
}
let before = self.counter.as_ref().map(Counter::read).unwrap_or_default();
draw.frame();
if timed && let Some(c) = &self.counter {
let after = c.read();
self.instructions.0 += after.0 - before.0;
self.instructions.1 += after.1 - before.1;
self.instructions.2 += after.2 - before.2;
}
self.frames += 1;
if self.frames >= self.warmup + self.measured {
event_loop.exit();
}
}
}
@@ -0,0 +1,36 @@
--- a/src/vulkan/command.rs
+++ b/src/vulkan/command.rs
@@ -120,6 +120,7 @@
type A = super::Api;
unsafe fn begin_encoding(&mut self, label: crate::Label) -> Result<(), crate::DeviceError> {
+ if std::env::var_os("LOG_BARRIERS").is_some() { eprintln!("BEGIN {:?}", label); }
if self.free.is_empty() {
let vk_info = vk::CommandBufferAllocateInfo::default()
.command_pool(self.raw)
@@ -208,6 +209,7 @@
let (dst_stage, dst_access) = conv::map_buffer_usage_to_barrier(bar.usage.to);
dst_stages |= dst_stage;
+ if std::env::var_os("LOG_BARRIERS").is_some() { eprintln!("BARRIER buf {:?} -> {:?}", bar.usage.from, bar.usage.to); }
vk_barriers.push(
vk::BufferMemoryBarrier::default()
.buffer(bar.buffer.raw)
@@ -254,6 +256,7 @@
let dst_layout = conv::derive_image_layout(bar.usage.to, bar.texture.format);
dst_stages |= dst_stage;
+ if std::env::var_os("LOG_BARRIERS").is_some() { eprintln!("BARRIER tex {:?} -> {:?} layout {:?} -> {:?}", bar.usage.from, bar.usage.to, src_layout, dst_layout); }
vk_barriers.push(
vk::ImageMemoryBarrier::default()
.image(bar.texture.raw)
--- a/src/vulkan/mod.rs
+++ b/src/vulkan/mod.rs
@@ -1376,6 +1376,7 @@
surface_textures: &[&SurfaceTexture],
(signal_fence, signal_value): (&Fence, crate::FenceValue),
) -> Result<(), crate::DeviceError> {
+ if std::env::var_os("LOG_BARRIERS").is_some() { eprintln!("SUBMIT cbs={} surfaces={}", command_buffers.len(), surface_textures.len()); }
let mut fence_raw = vk::Fence::null();
let mut wait_semaphores = SemaphoreList::new(SemaphoreListMode::Wait);
+155
View File
@@ -0,0 +1,155 @@
// A minimal hand-written Metal HUD for comparing per-frame CPU with Rune's overlay
// (crates/rune/examples/overlay_hud_cost.rs): a 360x80 borderless panel at the bottom of the
// screen whose CAMetalLayer is cleared to an animating colour from a CVDisplayLink callback,
// one command buffer per frame with the drawable presented on it.
//
// swiftc -O metal_hud.swift -o metal_hud && ./metal_hud
//
// Env: HUD_SECONDS (default 12); HUD_EXTRA_CBS=n commits n empty command buffers a frame;
// HUD_SPLIT_PRESENT=1 presents from a command buffer of its own; HUD_DIRECT_PRESENT=1 commits,
// waits until the command buffer is scheduled and presents the drawable with no command buffer;
// HUD_HANDLERS=n adds a completion handler to n command buffers a frame (extras first);
// HUD_LABELS=1 labels each one; HUD_MAIN=1 draws on the main thread (the display link only
// wakes it). These mimic what wgpu does per frame (research/30-overlay-gpu-cost.md).
// Prints frames, fps and CPU ms per second for the main thread, the drawing thread and the rest.
import AppKit
import CoreVideo
import Metal
import QuartzCore
func env(_ name: String, _ fallback: Int) -> Int { Int(ProcessInfo.processInfo.environment[name] ?? "") ?? fallback }
let seconds = Double(env("HUD_SECONDS", 12))
let extraCBs = env("HUD_EXTRA_CBS", 0)
let splitPresent = env("HUD_SPLIT_PRESENT", 0) != 0
let directPresent = env("HUD_DIRECT_PRESENT", 0) != 0
let handlers = env("HUD_HANDLERS", 0)
let labels = env("HUD_LABELS", 0) != 0
let onMain = env("HUD_MAIN", 0) != 0
func threadCPU() -> Double {
var t = timespec()
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t)
return Double(t.tv_sec) * 1e3 + Double(t.tv_nsec) / 1e6
}
func processCPU() -> Double {
var u = rusage()
getrusage(RUSAGE_SELF, &u)
func ms(_ t: timeval) -> Double { Double(t.tv_sec) * 1e3 + Double(t.tv_usec) / 1e3 }
return ms(u.ru_utime) + ms(u.ru_stime)
}
func processCounts() -> [UInt64] {
var info = rusage_info_v4()
let ok = withUnsafeMutablePointer(to: &info) { p in
p.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { proc_pid_rusage(getpid(), RUSAGE_INFO_V4, $0) }
}
return ok == 0 ? [info.ri_instructions, info.ri_cycles, info.ri_interrupt_wkups] : [0, 0, 0]
}
final class Hud {
let device = MTLCreateSystemDefaultDevice()!
lazy var queue = device.makeCommandQueue()!
let layer = CAMetalLayer()
let start = Date()
var frames = 0
var drawCPU = 0.0
var mainCPU0 = 0.0, process0 = 0.0, draw0 = 0.0, frames0 = 0, wall0 = Date()
var warm = false
var counts0: [UInt64] = [0, 0, 0]
var handled = 0
func frame() {
handled = 0
let entered = threadCPU()
frames += 1
let elapsed = Date().timeIntervalSince(start)
if !warm && elapsed >= 2 {
warm = true
process0 = processCPU(); counts0 = processCounts(); draw0 = drawCPU; frames0 = frames; wall0 = Date()
DispatchQueue.main.async { self.mainCPU0 = threadCPU() }
}
if warm && elapsed >= seconds {
let wall = Date().timeIntervalSince(wall0)
let n = Double(frames - frames0)
let draw = drawCPU - draw0
let process = processCPU() - process0
let counts = processCounts()
let per = { (i: Int) in Double(counts[i] - self.counts0[i]) / n }
DispatchQueue.main.async {
let main = threadCPU() - self.mainCPU0
let drawing = onMain ? 0 : draw
print(String(format: "frames=%.0f fps=%.1f main_ms_per_s=%.1f draw_thread_ms_per_s=%.1f other_ms_per_s=%.1f process_cpu_pct=%.1f draw_us_per_frame=%.1f",
n, n / wall, main / wall, drawing / wall, (process - main - drawing) / wall, process / wall / 10, draw * 1e3 / n))
print(String(format: "process_per_frame: kinstructions=%.1f kcycles=%.1f wakeups=%.2f", per(0) / 1e3, per(1) / 1e3, per(2)))
exit(0)
}
}
autoreleasepool {
guard let drawable = layer.nextDrawable() else { return }
let phase = sin(elapsed * 2) * 0.5 + 0.5
for _ in 0..<extraCBs { commit(queue.makeCommandBufferWithUnretainedReferences()!, "extra") }
let cb = queue.makeCommandBufferWithUnretainedReferences()!
let pass = MTLRenderPassDescriptor()
pass.colorAttachments[0].texture = drawable.texture
pass.colorAttachments[0].loadAction = .clear
pass.colorAttachments[0].storeAction = .store
pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: phase * 0.4, alpha: 0.4)
cb.makeRenderCommandEncoder(descriptor: pass)!.endEncoding()
if directPresent {
commit(cb, "frame")
cb.waitUntilScheduled()
drawable.present()
} else if splitPresent {
commit(cb, "frame")
let present = queue.makeCommandBuffer()!
present.present(drawable)
commit(present, "present")
} else {
cb.present(drawable)
commit(cb, "frame")
}
}
drawCPU += threadCPU() - entered
}
func commit(_ cb: MTLCommandBuffer, _ label: String) {
if labels { cb.label = label }
if handled < handlers { handled += 1; cb.addCompletedHandler { _ in } }
cb.commit()
}
}
let app = NSApplication.shared
app.setActivationPolicy(.accessory)
let hud = Hud()
let screen = NSScreen.main!.frame
let size = NSSize(width: 360, height: 80)
let panel = NSPanel(contentRect: NSRect(x: screen.midX - size.width / 2, y: screen.minY + 60, width: size.width, height: size.height),
styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
panel.isOpaque = false
panel.backgroundColor = .clear
panel.level = .statusBar
panel.ignoresMouseEvents = true
let view = NSView(frame: NSRect(origin: .zero, size: size))
view.wantsLayer = true
hud.layer.device = hud.device
hud.layer.pixelFormat = .bgra8Unorm
hud.layer.isOpaque = false
hud.layer.framebufferOnly = true
hud.layer.contentsScale = panel.backingScaleFactor
hud.layer.drawableSize = CGSize(width: size.width * panel.backingScaleFactor, height: size.height * panel.backingScaleFactor)
view.layer = hud.layer
panel.contentView = view
panel.orderFrontRegardless()
var link: CVDisplayLink?
CVDisplayLinkCreateWithActiveCGDisplays(&link)
CVDisplayLinkSetOutputHandler(link!) { _, _, _, _, _ in
if onMain { DispatchQueue.main.async { hud.frame() } } else { hud.frame() }
return kCVReturnSuccess
}
CVDisplayLinkStart(link!)
DispatchQueue.main.asyncAfter(deadline: .now() + seconds + 20) { print("metal_hud: no frames"); exit(1) }
app.run()
@@ -0,0 +1,16 @@
diff --git a/src/device/queue.rs b/src/device/queue.rs
index 1c0ac26..7c9c458 100644
--- a/src/device/queue.rs
+++ b/src/device/queue.rs
@@ -186,7 +186,10 @@ impl Queue {
pending
};
- if pending.is_empty() {
+ if pending.is_empty()
+ || (!needs_clear
+ && pending.iter().all(|p| p.usage.from == wgt::TextureUses::PRESENT))
+ {
// This assert checks that we don't return here if we encoded a
// clear operation for the texture, which would be a problem since
// we haven't done anything yet to ensure it stays alive. If we
@@ -0,0 +1,254 @@
diff --git a/src/metal/command.rs b/src/metal/command.rs
index ba41a63..5993441 100644
--- a/src/metal/command.rs
+++ b/src/metal/command.rs
@@ -153,6 +153,35 @@ impl Encoder<'_> {
}
impl super::CommandEncoder {
+ /// The Metal command buffer, made now if this encoding hasn't needed one yet.
+ fn cmd_buf(&mut self) -> Retained<ProtocolObject<dyn MTLCommandBuffer>> {
+ if self.raw_cmd_buf.is_none() {
+ assert!(self.begun);
+ let queue = &self.queue_shared.raw;
+ let retain_references = self.shared.settings.retain_command_buffer_references;
+ let relay = self.queue_shared.relay.get();
+ let label = self.label.as_deref();
+ let raw = autoreleasepool(move |_| {
+ let cmd_buf_ref = if retain_references {
+ queue.commandBuffer()
+ } else {
+ queue.commandBufferWithUnretainedReferences()
+ }
+ .unwrap();
+ if let Some(label) = label {
+ cmd_buf_ref.setLabel(Some(&NSString::from_str(label)));
+ }
+ if let Some(relay) = relay {
+ let expected = relay.next_release_value.load(atomic::Ordering::Acquire);
+ cmd_buf_ref.encodeWaitForEvent_value(relay.event.as_ref(), expected);
+ }
+ cmd_buf_ref.to_owned()
+ });
+ self.raw_cmd_buf = Some(raw);
+ }
+ self.raw_cmd_buf.clone().unwrap()
+ }
+
pub fn raw_command_buffer(&self) -> Option<&ProtocolObject<dyn MTLCommandBuffer>> {
self.raw_cmd_buf.as_deref()
}
@@ -161,7 +190,7 @@ impl super::CommandEncoder {
if self.state.blit.is_none() {
self.leave_acceleration_structure_builder();
debug_assert!(self.state.render.is_none() && self.state.compute.is_none());
- let cmd_buf = self.raw_cmd_buf.as_ref().unwrap();
+ let cmd_buf = &self.cmd_buf();
// This code path is currently unused since the written timestamp is always 0.
// We should see if we can get it working again, if not remove the code.
@@ -271,7 +300,7 @@ impl super::CommandEncoder {
&& self.state.compute.is_none()
&& self.state.blit.is_none()
);
- let cmd_buf = self.raw_cmd_buf.as_ref().unwrap();
+ let cmd_buf = &self.cmd_buf();
autoreleasepool(|_| {
self.state.acceleration_structure_builder =
cmd_buf.accelerationStructureCommandEncoder().to_owned();
@@ -500,32 +529,9 @@ impl crate::CommandEncoder for super::CommandEncoder {
return Err(crate::DeviceError::Lost);
}
- let raw = autoreleasepool(move |_| {
- let cmd_buf_ref = if retain_references {
- queue.commandBuffer()
- } else {
- queue.commandBufferWithUnretainedReferences()
- }
- .unwrap();
- if let Some(label) = label {
- cmd_buf_ref.setLabel(Some(&NSString::from_str(label)));
- }
- // If strict event sync is enabled on this queue, gate the
- // CB on the relay event at the value the next submit will
- // signal. The CB pauses at the start until the relay fires.
- if let Some(relay) = relay {
- let expected = relay.next_release_value.load(atomic::Ordering::Acquire);
- cmd_buf_ref.encodeWaitForEvent_value(relay.event.as_ref(), expected);
- }
- cmd_buf_ref.to_owned()
- });
-
- // Queries should either be closed out, or cleared in `discard_encoding`.
- // This assertion is here mainly to facilitate comparison with the other
- // backends, which clear in `begin_encoding` rather than `discard_encoding`.
- debug_assert!(self.state.pending_timer_queries.is_empty());
-
- self.raw_cmd_buf = Some(raw);
+ let _ = (queue, retain_references, relay);
+ self.label = label.map(str::to_owned);
+ self.begun = true;
Ok(())
}
@@ -542,7 +548,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
encoder.endEncoding();
}
self.state.pending_timer_queries.clear();
- let had_command_buffer = self.raw_cmd_buf.is_some();
+ let had_command_buffer = std::mem::take(&mut self.begun);
// Clear the Option first so the underlying `metal::CommandBuffer` is
// dropped before we update the counter.
self.raw_cmd_buf = None;
@@ -566,8 +572,9 @@ impl crate::CommandEncoder for super::CommandEncoder {
debug_assert!(self.state.compute.is_none());
debug_assert!(self.state.pending_timer_queries.is_empty());
+ self.begun = false;
Ok(super::CommandBuffer {
- raw: self.raw_cmd_buf.take().unwrap(),
+ raw: self.raw_cmd_buf.take(),
queue_shared: Arc::clone(&self.queue_shared),
})
}
@@ -1049,7 +1056,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
if let Some(mv) = desc.multiview_mask {
descriptor.setRenderTargetArrayLength(32 - mv.leading_zeros() as usize);
}
- let raw = self.raw_cmd_buf.as_ref().unwrap();
+ let raw = &self.cmd_buf();
let encoder = raw.renderCommandEncoderWithDescriptor(&descriptor).unwrap();
if let Some(mv) = desc.multiview_mask {
// Most likely the API just wasn't thought about enough. It's not like they ever allow you
@@ -1260,14 +1267,16 @@ impl crate::CommandEncoder for super::CommandEncoder {
unsafe fn begin_debug_marker(&mut self, group_label: &str) {
if let Some(encoder) = self.active_encoder() {
encoder.pushDebugGroup(&NSString::from_str(group_label));
- } else if let Some(ref buf) = self.raw_cmd_buf {
+ } else if self.begun {
+ let buf = self.cmd_buf();
buf.pushDebugGroup(&NSString::from_str(group_label));
}
}
unsafe fn end_debug_marker(&mut self) {
if let Some(encoder) = self.active_encoder() {
encoder.popDebugGroup();
- } else if let Some(ref buf) = self.raw_cmd_buf {
+ } else if self.begun {
+ let buf = self.cmd_buf();
buf.popDebugGroup();
}
}
@@ -1689,7 +1698,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
debug_assert!(self.state.compute.is_none());
debug_assert!(self.state.render.is_none());
- let raw = self.raw_cmd_buf.as_ref().unwrap();
+ let raw = &self.cmd_buf();
autoreleasepool(|_| {
// TimeStamp Queries and ComputePassDescriptor were both introduced in Metal 2.3 (macOS 11, iOS 14)
@@ -1897,18 +1906,19 @@ impl crate::CommandEncoder for super::CommandEncoder {
command_buffers: &[&super::CommandBuffer],
dependencies: &[&super::AccelerationStructure],
) {
- let Some(first_command_buffer) = command_buffers.first() else {
+ let Some(first_raw) = command_buffers.iter().find_map(|b| b.raw.as_ref()) else {
return;
};
let desc = MTLResidencySetDescriptor::new();
- desc.setLabel(first_command_buffer.raw.label().as_deref());
- let residency_set = first_command_buffer
- .raw
+ desc.setLabel(first_raw.label().as_deref());
+ let residency_set = first_raw
.device()
.newResidencySetWithDescriptor_error(&desc)
.unwrap();
for command_buffer in command_buffers {
- command_buffer.raw.useResidencySet(&residency_set);
+ if let Some(raw) = &command_buffer.raw {
+ raw.useResidencySet(&residency_set);
+ }
}
for dependency in dependencies {
residency_set.addAllocation(ProtocolObject::from_ref(&*dependency.raw));
@@ -1965,7 +1975,8 @@ impl Drop for super::CommandBuffer {
// `command_buffer_created_not_submitted` is usually decremented when the command
// buffer is submitted. But if we're dropping a command buffer that was never
// submitted, we need to decrement the count here.
- let status = self.raw.status();
+ let Some(raw) = &self.raw else { return };
+ let status = raw.status();
if status == MTLCommandBufferStatus::NotEnqueued
|| status == MTLCommandBufferStatus::Enqueued
{
diff --git a/src/metal/device.rs b/src/metal/device.rs
index d7287b9..9ba3335 100644
--- a/src/metal/device.rs
+++ b/src/metal/device.rs
@@ -773,6 +773,8 @@ impl crate::Device for super::Device {
shared: Arc::clone(&self.shared),
queue_shared: Arc::clone(&desc.queue.shared),
raw_cmd_buf: None,
+ begun: false,
+ label: None,
state: super::CommandState::default(),
temp: super::Temp::default(),
counters: Arc::clone(&self.counters),
diff --git a/src/metal/mod.rs b/src/metal/mod.rs
index e227590..831e0f0 100644
--- a/src/metal/mod.rs
+++ b/src/metal/mod.rs
@@ -741,8 +741,9 @@ impl crate::Queue for Queue {
fence_sync.1.notify_all();
});
- let raw = match command_buffers.last() {
- Some(&cmd_buf) => cmd_buf.raw.clone(),
+ let last = command_buffers.iter().rev().find_map(|b| b.raw.clone());
+ let raw = match last.clone() {
+ Some(raw) => raw,
None => {
// We do not bother adjusting `command_buffer_created_not_submitted`
// because we immediately commit this buffer.
@@ -775,14 +776,16 @@ impl crate::Queue for Queue {
}
// only return an extra one if it's extra
- match command_buffers.last() {
+ match last {
Some(_) => None,
None => Some(raw),
}
};
for cmd_buffer in command_buffers {
- cmd_buffer.raw.commit();
+ if let Some(raw) = &cmd_buffer.raw {
+ raw.commit();
+ }
// One command buffer per `end_encoding` call moves from the
// "created but not yet submitted" bucket into the submitted
// set, so update the counter.
@@ -1354,6 +1357,10 @@ pub struct CommandEncoder {
shared: Arc<AdapterShared>,
queue_shared: Arc<QueueShared>,
raw_cmd_buf: Option<Retained<ProtocolObject<dyn MTLCommandBuffer>>>,
+ /// Between `begin_encoding` and `end_encoding`/`discard_encoding`; the Metal command
+ /// buffer is made on first use, so an encoding that records nothing commits nothing.
+ begun: bool,
+ label: Option<String>,
state: CommandState,
temp: Temp,
counters: Arc<wgt::HalCounters>,
@@ -1372,7 +1379,7 @@ unsafe impl Sync for CommandEncoder {}
#[derive(Debug)]
pub struct CommandBuffer {
- raw: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
+ raw: Option<Retained<ProtocolObject<dyn MTLCommandBuffer>>>,
queue_shared: Arc<QueueShared>,
}