# Critique: deterministic core and host parity (critic-core) Angle: State as plain data, migrated field by field; `update(state, input)` replayed from recorded input; `draw` emits commands as data; the native host (SDL3) and the web host (Canvas2D + WebGPU) must produce matching results. Inputs: board.md (including "Owner: layering"), the three research notes, friction-a.md, critique-zig.md, the 12 ports, both helper files, lib/sketchbook/{src,web}, and sketches/shaders/README.md. friction-b.md arrived as I finished. Its C2 (batched ticks with end-of-batch input) is what E1 measures. Its per-tick `frames60(clock, e)` avoids the Clock cap, but the pointer state stays end-of-batch, so it does not replace the host split. Paths: `SB/` = `lib/sketchbook/`, `noc/` = `sketches/noc/`. Experiment files are in `/tmp/claude-1000/-home-goblin-00-projects/b03e088f-d250-44e5-b526-5614572b9fb9/scratchpad/` (`replay/`, `canvas/`, `zt/`). Nothing under SB/ was modified. --- ## 0. What I measured | # | Experiment | Result | | --- | --- | --- | | E1 | **Seek feeds a whole recording to one `update`.** noc's built `accel_to_mouse`, headless: record 60 frames, play to the end, `save 3`, then `seek end`. Compare the state bytes against slot 3 (`replay/replay.script`, `replay/cmp.py`). | Playback ends at pos (581.17, 310.59). Seek ends at **(350.59, 195.29)**. `runLine` calls `self.update(replay)` once (SB/src/host/Host.zig:437, timeline.zig:160-166), and `steps60` caps one update at 8 steps (noc/src/helpers_a.zig:25), so the seek makes 8 steps where the live run made 60. | | E2 | **Input state is not part of the snapshot.** Same recording, played a second time, but after a live `move 80 60` before `play 1`. | Second replay ends at **(163.48, 101.74)** against (581.17, 310.59). `Input.mouse_*`, `buttons` and `keys` are host fields. They are tracked only from fed events (Host.zig:246) and never reset when a snapshot is restored or recorded. A replay therefore chases wherever the live mouse was last. porter-a's "the mouse replays correctly" (friction-a §4) holds only when the recording begins with a mouse event. | | E3 | **`@Vector(2,f32)` in State leaves garbage in its padding.** The control run: two identical replays, positions bit-equal. | **4 bytes still differ**, at offsets 8, 24 and 40: lane 2 of each 16-byte Debug vector (`7aa06e80` vs `0ca16e80`). `Bank.compare` (timeline.zig:69), behind the console's `diff`, compares raw bytes, so it reports these false differences on any sketch that stores `@Vector` (9 of 12 ports). | | E4 | **`in.dt` rebuilt from the recorded tick does not equal the live `in.dt`.** `zt/dt.zig`: u64 ns → f32 seconds (as at Host.zig:233) → ns. | **1098 of 2998** frame lengths between 15 and 18 ms fail to round-trip. 16_666_667 ns comes back as 16_666_668. | | E5 | **Canvas2D cost of a triangle soup**, headless Chrome, software raster, circles of 24 segments, one fill per shape (`canvas/bench.html`). | 1000 circles: **11.0 ms** as triangles in one path, 3.0 ms as one outline polygon, 2.3 ms with `arc`. 5000: **53.2** / 14.8 / 10.0 ms. 20000: 221 / 68 / 48 ms. Filling triangles costs 3.6–3.7× more than filling the outline. Path2D is no better (11.9 ms). | | E6 | **Canvas2D semantics of one shape path** (same page). | Two overlapping triangles with the same winding at α=0.5: **128** (union). Native, which blends per triangle, gives 191. Opposite winding, opaque: **0, a hole** (native: 255). Two opaque triangles filled separately along a shared edge: minimum **192** (a conflation seam; native: 255). | | E7 | **A fringe-shrunk body on the web** (research-love P2: shrink by 0.3 px, the web skips the fringe). | A 1 px line drawn as a 0.4 px body peaks at **128**, and at **64** when it straddles a pixel boundary. The true 1 px body gives 255 and 128. **Web lines come out at half intensity.** | | E8 | **Where float math resolves in the native binaries.** `nm` on the noc executables. | `sinf`, `cosf`, `expf` and `fmaf` are local `compiler_rt.*` symbols, the same code as on wasm. `atan2f`/`powf` imports come from C dependencies, not from Zig (`std.math.atan2` is a musl port in Zig). So research-zig's cross-target float parity holds for Zig code in `update`. | | E9 | `std.mem.zeroes(T)` as `List`'s default (research-zig §1), T holding `enum(u8){a=1,b=2}` (`zt/zeroes.zig`). | **Compile error**: "enum has no tag with value '0'". | | E10 | SDL 3.4 header, `SDL_BLENDMODE_MUL` (zig-pkg/sdl-*/include/SDL3/SDL_blendmode.h:60). | `dstRGB = srcRGB*dstRGB + dstRGB*(1-srcA)`. Canvas `multiply` over an opaque backdrop is `αs·cs·cb + (1-αs)·cb`. Translucent white at α=0.5 over 50 % gray: **SDL 0.75, canvas 0.5**. In canvas, multiplying by white leaves the backdrop unchanged; in SDL it brightens it. | | E11 | State-file open path (SB/src/host/memory.zig:129-146, 226-230). | A file whose magic is not `file_magic`, or whose length does not fit `header_len + slot_count*stride`, is **truncated** (`resize(0)`). The owner's `drat-meout.state` (229 KB, which holds the tracker songs) is such a file to any host whose constants differ. | **critic-zig and I agree on the central point:** the host should call `update` once per tick. critic-zig found it by reading the code (critique-zig.md, "Time and input") and asked me to check it. E1 and E2 confirm it and add the Input-state leak, which splitting alone does not fix. --- ## 1. Layering (owner constraint): which proposals need a host primitive The rule: the new layer is sketch-library code over today's `abi.Command` / `f.emit` / GPU passes / `Input.events`. It has no hidden state and exposes its intermediate data. | Proposal | New host primitive? | Is the low level still reachable? | | --- | --- | --- | | Pen + tessellation | No (lib) | Yes, **if** the Pen's output is a value, `sk.Tessellation { points, ends, indices }`. The sketch can emit it with `f.shape(t, color)`, expand it into a `gpu.Draw` vertex list, or inspect it. A Pen that only emits commands violates the constraint. | | `Command.shape` | **Yes: the one new 2D primitive** | It is the low level: callable directly with hand-made points and indices. | | Clock, Rng, noise, vec math, List | No (lib) | Yes. All are plain data or pure functions over `in.events` and std. `List.buffer`/`len` stay public fields. | | One `update` per tick; Input reset and seeding at record start; `in.dt` from the tick; leaf-wise `diff` | No primitive, only host *behaviour* | Not applicable. These fix the existing low level: `Input.events` keeps its meaning. | | Element-wise migration | No command; it changes the state-file format | Not applicable. | | MSAA `clear = null` load fix; web tint RGB fix | No: these are parity bug fixes | Not applicable. | | `Command.blend` | Yes (deferred) | Yes, if it stays a state command next to `clip`. | | `Command.target`, `Host.newTarget`, `Input.jumped` | Yes, three (deferred) | Yes. | | `image.xf` / `quad` | An ABI field (deferred) | Yes. | | `Shader.samplers` / `Draw.textures`, `Draw.instances` | GPU-pass fields (deferred; `instances` is safe now) | Yes. | | Build options (`.noise`, `.hue`, `.antialias`) | No, but they are hidden modes | **No.** A build mode changes what a low-level call means. | --- ## 2. Verdicts Legend: **A** accept, **AC** accept with changes, **R** reject, **D** defer (not wrong, not first). ### 2.1 Time, input, replay | Proposal | Verdict | Failure scenario and evidence | | --- | --- | --- | | love P3 `Clock.advance(in, hz, max)`; p5 P5 `Clock.steps` "at most 8"; zig `Clock`; helpers_a `steps60` | **AC**: only after the host splits per tick, and the cap must count **per tick, never per update** | E1: a seek, or playback that falls behind, sums every tick and then caps, which gives 8 steps for 60 live frames. Even without a cap, all steps of a batch see the end-of-batch `in.mouse_x`. A Clock test must assert `N updates × 1 tick == 1 update × N ticks`, both in steps and in State bytes. I agree with critic-zig's `hz` as a field. | | p5 P5 "set `in.dt` from the fed ticks in replay" | **R as written** | E4: live `dt` is exact ns, a rebuilt `dt` is not, so 37 % of frames differ. **Fix:** in both modes, derive `in.dt` (and an update-time `in.now`) from the frame's own tick event. Or remove them from what `update` reads. | | porter-b #2 / critic-zig: one `update` per tick | **A, first item** | The fix for E1, the dt bug, and end-of-batch pointer state. Two details: (a) `Timeline.tick` (timeline.zig:148-157) can return part of a frame, because a frame's input events carry earlier times than its tick, so playback and `seekTime` must advance to whole frames (up to and including a tick); (b) the web driver already feeds one frame per update (web.zig:135-160). The game (`src/main.zig:78-86`) is unaffected: it already applies events one by one. | | (new) Input tracked state at record start and restore | **A, ships with the split** | E2. **Fix:** on `play`/`seek`/`step`, reset the tracked fields (`mouse_*`, `buttons`, `keys`) to what they were at the recording's start. Achieve that by having `startRecording` write synthetic events first (a `mouse_move` to the current pointer, a `mouse_down` per held button, a `key_down` per held key) at time 0. The recording format does not change. | | (new) Input fields `update` can read that no event carries | **AC: document now, narrow later** | `now`, `dt`, `frame`, `width`/`height`, `window_*`, `console`, `mode`, `streams`, `sample_rate` all reach `update` and do not replay. A responsive sketch (README "An app") that bounces off `in.width` replays differently after a window resize. A compile-time `UpdateInput` would break every sketch's signature. First say in `abi.Input` which fields are event-derived. | | love P3 / p5 P14 input sugar (`clicked`, `released`, `wheel`, `typed`, `elapsed`, `prevMouse`) | **D** (agree with critic-zig) | Pure functions of events, so they are safe, but only after the split. Before it, `prevMouse` would be "before the batch". | | p5 P13 deterministic export from a recording | **D, then A** | It is correct only with the split (one update, then one draw, per tick), and accumulating targets must start from `jumped`. It is native only, so it does not affect parity. | | (new) Recordings carry no identity of the code that made them | **AC, cheap** | A replay against edited `update` code, or a new Zig std (`Random.float`, compiler-rt `sinf`), diverges silently. That is the real form of research-p5's "pin the PRNG" worry. Stamp `Recording.reserved` with the sketch library's build hash (`sketch_info` can expose it) and warn on `play` when it differs. A warning is enough. | ### 2.2 State, migration, inspection | Proposal | Verdict | Failure scenario and evidence | | --- | --- | --- | | zig §1 / coordinator / p5 P6: element-wise array migration | **AC** | (1) **Do not "bump the magic to SKETCH02 and treat old files as foreign".** E11: a foreign file is truncated on open, so the owner's `drat-meout.state` (and its snapshots, which its recordings depend on) would be wiped by the first new host, which is exactly the tracker-song loss the change is meant to prevent. Read v1 headers (every leaf has `count = 1`) and write v2. Test it on a copy of a real v1 file. (2) The coordinator's "a bare `[N]T` plus a count is enough" is **false on a shrink**: the prefix copy keeps `n > N`, `update` indexes out of bounds, and because State is saved, every restart panics again (a crash loop). The clamp in `List` is required. (3) The overlay, probe and `sk_field` must accept indexed paths, or the new leaves are invisible. | | zig `sk.List` / love `Bounded` / p5 `List` | **AC** | The default must be `@splat(.{})` (T's own defaults), not `std.mem.zeroes` (E9: does not compile for enums without a 0 tag). `items()` clamps to `cap`. Use std's names (critic-zig). | | zig `sk.Ring` | **D** | Only the deferred Layer needs it. | | zig §3 `sk.Vec2 extern struct` for State vs critic-zig's "keep `@Vector`, split lanes" | **AC on critic-zig's side, plus one host fix** | critic-zig is right that lane leaves migrate by path across `-Doptimize`. But E3 shows the padding stays nondeterministic, so **`Bank.compare` must compare leaves, not raw bytes** (about 10 lines, timeline.zig:69). Otherwise `diff` lies, which undermines the main replay tool. With both fixes `@Vector` in State is safe. State doubles in size in Debug; that costs memory, not correctness. | | love P10 `sk.v2` over `@Vector` (compute) | **A** | E8: Zig math resolves to compiler-rt on native and wasm alike. | | zig §6 / critic-zig: script `expect ~tol`, indexed and lane paths | **A** | They remove test-only State fields, which I count as State shaped by the harness. This is not a core risk. | | zig: host constants (`slot_count`, `header_len`, store reserve, …) as build options | **R for `slot_count` and `header_len`, D for the rest** | E11: `valid()` and `slot()` use the reader's constants (memory.zig:157-161, 226-230). A host built with 4 slots or a 128 KiB header **truncates, or misreads as live state**, every file written by another build. These are file-format parameters: they belong in `Header` (which has `reserved`), read from the file, never compiled into the reader. The web event queue, GPU staging and `keep_frames` are process-local, so they are fine as options. | ### 2.3 Randomness and noise | Proposal | Verdict | Failure scenario and evidence | | --- | --- | --- | | love P4 `Rng{s:[4]u32}` / p5 P3 PCG32 + `spare` / zig "free functions over `std.Random`" / critic-zig "concrete `Xoshiro256`, no wrapper" | **A for critic-zig's version** | The core risk is only hidden or uncaptured RNG state. A concrete std generator in State is plain data, migrates as one leaf, and `floatNorm` keeps no spare. "Pin it in case std changes" is the same hazard as editing `update`, and the recording stamp (§2.1) covers both. p5's `spare` in State would also be correct; LÖVE's lossy `getState` is the bug to avoid. | | p5 `rand.at(seed, key)` / love `hash` | **D** | Pure functions, safe in `draw`. No port uses them. | | `sk.noise(seed, x, y, z)` pure, hash-lattice | **A** | A pure function with an explicit seed is replay-safe in both `update` and `draw`. | | GLSL or Zig-SPIR-V noise "twin" matching the CPU | **AC** | It matches only approximately: GPU `Sin`, FMA contraction and denormals are implementation-defined. The rule to write down: GPU results never feed `update` (downloads already reach only `draw`, abi.zig:472). Use integer hashes, never `fract(sin(x)·43758)`, whose output differs between GPUs. | | p5 build options `.noise`, `.hue` | **R** (agree with critic-zig and research-zig) | A `-D` override changes what `update` computes for the same source, and the native and web builds can be given different flags. | ### 2.4 Drawing and parity | Proposal | Verdict | Failure scenario and evidence | | --- | --- | --- | | love P2 `Command.shape { color, triangles, fringe }` | **AC: change the payload and drop `fringe`** | (a) E5: Canvas2D fills a triangle soup 3.6× slower than the same outline. 1000 particles cost 11 ms per frame on the web, 5000 cost 53 ms. (b) E7: a body shrunk for the fringe draws thin lines at half intensity on the web. **Payload:** `shape { color, points: []const [2]f32, ends: []const u32 (subpath ends), indices: []const u32 (triangles into points) }`. The web fills the subpaths as one nonzero path (fast, one fill, no seams). Native passes points and indices to `SDL_RenderGeometry`, which takes indices directly. Both come from the lib tessellator, so both describe one region. (c) **Contract:** the region is the nonzero union of the subpaths, all wound positive by the lib. E6 shows that opposite winding makes holes; that is research-zig's acute-join warning, confirmed. | | Translucent overlap inside one shape (strokes, self-crossing polylines) | **AC: guarantee disjoint triangles, test for it, document the rest** | E6: the web gives the union (128), native double-blends (191). The lib must emit disjoint triangles for fills (fan or ear clipping) and for strokes (strip joins computed on the inner side, bevel past the limit). A **self-crossing translucent polyline cannot be disjoint**, so it stays a known divergence, pinned by a screenshot test. Reject research-p5's "render translucent shapes opaque into a scratch target, then composite" as the default: it costs one target switch, so one render pass, per shape. | | p5 P1 Frame-side batching / host coalescing | **R in the Frame; D in the host** (agree with critic-zig) | Lib batching is hidden state in the Frame. Native coalescing is invisible only for opaque shapes of one color. On the web, merging adjacent shapes removes the seams of E6, so coalescing must not happen in the web host either, or the two hosts' seams diverge. | | love P1 / p5 P2 `Pen` holding `*Frame` vs critic-zig's Pen as plain data plus `f.circle/line/polygon` | **AC: critic-zig's data Pen, plus the layering rule** | Determinism is unaffected either way (draw only, scratch memory). For the layering rule, the tessellator must return `sk.Tessellation`, which `f.shape` or a GPU pass consumes. The segment count from the error bound times `xf` scale is deterministic. | | love P2 fringe / p5 `.antialias` option | **D** | Native is aliased until then, as fractional `rect` fills already are today. If the owner needs native AA, do it host-side (an MSAA SDL_GPU pipeline for `shape`), so the command stays exact and the web is not thinned. | | love P5 / p5 P9 `blend {alpha, add, multiply}` | **D; when added: alpha and add as specified, multiply only with the host premultiplying the vertex color** | E10: SDL `MUL` does not match canvas for α<1. With premultiplied source, `(cs·αs)·cb + cb(1−αs)` equals canvas exactly. For `image` there is no fixed-function equivalent without premultiplied textures, so leave multiply off images. Into transparent targets, alpha also diverges: SDL `ADD` keeps dstA, canvas `lighter` adds alphas. | | GPU-pass blend table (love P5 2nd half) | **A when needed** | Both hosts use fixed-function factors, so the results match. | | love P6 / p5 P10 / zig §5 targets + `Input.jumped` + Layer | **D** (agree with critic-zig); when built: **AC** | (1) Native targets must be premultiplied: SDL `BLEND` into a transparent target stores premultiplied colour, and `Images.setup` draws every texture with `BLEND` (gfx.zig:105-108), so alpha is applied twice and edges darken. The web canvas is correct. (2) A new target must be cleared on both hosts (an SDL target texture's contents are undefined). (3) `jumped` fires on seek, step, snapshot load, `set`, play start, reset, and on any reload (merge it with `in.reloaded`). (4) An accumulation layer is a **Session cache derived from history, not from State**, so after a seek its picture differs from the live run's at the same State. Screenshot tests must not capture one after a jump. Only "exact under seek" data (a bitset, a List in State) is truth. (5) With P8, native must flush the SDL renderer before a GPU pass samples a target. | | porter-a / research-zig: MSAA `clear = null` should load (gpu.zig:214) | **AC, iteration 1** | It is a parity bug: the web loads, native clears. The fix is `RESOLVE_AND_STORE` plus `LOAD`, with one condition: the **first** use of an MSAA attachment must clear on native. A Vulkan texture starts undefined, while WebGPU zero-fills, so a naive `LOAD` would give the two hosts different first frames. | | love P7 / p5 P6b image affine | **D** | When built: canvas antialiases the edges of a rotated `drawImage` even with smoothing off, while SDL `NEAREST` does not. Document it. | | web drops the tint's RGB (web.zig:179 passes `tint.a`) | **A, iteration 1** | An existing silent divergence. Implement RGB on the web: one scratch canvas per image, `multiply` with the tint color, then `destination-in` with the image. Do not cache by tint (an animated tint would thrash the cache). | | love P8 samplers/textures | **D** | Ordering hazard as in targets (5). Also, PNG premultiplication and the initial contents must agree on both hosts. | | love P9 `Draw.instances` | **A whenever wanted** | One argument on each host (gpu.zig:256, host.js:258). No parity risk. | | zig: `draw`/`update` may return `!void` | **D** | An `update` that fails halfway leaves partial State, deterministically, so replay still reproduces it. Log once per error, not every frame. | ### 2.5 Board entries not covered above - research-p5 "batch coalescing must be opaque-only": **agree**, with the web-seam caveat above. - research-p5 `screen` dropped: **agree**. multiply needs the same scrutiny (E10). - research-zig "float determinism verified": **agree for Zig code** (E8). The caveat is that it holds for one compiler version, hence the recording stamp. - porter-a "first tick dt = 0": harmless, and identical in replay. - porter-a concurrent e2e collisions and the segfault on the error path: **agree, iteration 1** (a unique `--state` per run). The segfault is a teardown bug in a half-built host. --- ## 3. First iteration: the minimal set I accept as safe, in order Each item must ship with the tests named below. "Both hosts" means a native headless screenshot and a headless Chrome screenshot of the same command stream, compared with a tolerance only on edge pixels. 1. **Host: one `update` per tick, whole-frame playback and seek, `in.dt` from the tick, Input reset and seeded at record start.** No ABI change. Tests: (a) the E1 script turned into an e2e: record 60 frames with pointer moves, then `play` to the end, `seek end` and `step` forward, and each must equal the snapshot taken at `stop`; (b) the E2 script: replay after a live `move` must equal the first replay; (c) a Timeline unit test in which a partial frame (input events before their tick) is never delivered alone; (d) a unit test that live `in.dt` equals the replayed `in.dt`. 2. **`Bank.compare` by leaf, and lane/index leaves in `layout.flatten`.** Tests: two identical replays of a `@Vector` sketch show `diff` 0 (E3); `get`/`set`/`expect position[0]` work. 3. **Lib-only, no host change: `sk.Clock`** (field `hz`, no per-update cap), **`sk.noise(seed, x, y, z)`**, **vec free functions**, **`sk.List`** (clamped, `@splat(.{})` default). Rng stays a concrete std generator in State (docs). Tests: Clock `N×1 == 1×N` ticks, both in step count and in State bytes; noise golden values compared between native and `wasm32-wasi` builds; `List` with an enum lacking a 0 tag compiles (E9); a shrink clamps. 4. **Element-wise migration with a v1 reader** (no truncation, magic v2 for writes). Tests: a v1 fixture made from a copy of `drat-meout.state` keeps every leaf value; adding a field to an element keeps the other columns; capacity grows and shrinks (`List` clamps); an enum per element is remapped by name; a `[8]Song` with a new field keeps its songs. 5. **`Command.shape { color, points, ends, indices }`, no fringe, plus the lib tessellator returning `sk.Tessellation`, plus the data Pen with `f.circle/line/polygon`** (critic-zig's surface). The only new host primitive. Tests on both hosts: a translucent circle overlapping another (two commands, so it darkens on both); a concave polygon; a translucent zig-zag stroke with acute joins (no holes, no double blend); a 1 px line (same intensity, E7); a unit test that every `shape` the lib emits has positive winding and disjoint triangles. A web performance check: 5000 circles under 16 ms per frame on the reference machine (E5 baseline: 15 ms for outlines). 6. **Parity fixes:** web tint RGB, and the MSAA `clear = null` load with clear-on-first-use. Tests on both hosts: a tinted image; a GPU pass accumulated over 3 frames with `samples = 4`. 7. **Recording stamp:** the sketch build hash in `Recording.reserved`, with a warning on `play`. Test: play after a rebuild warns; play without one does not. Explicitly **not** in iteration 1: blend modes (multiply needs E10's fix), targets, `jumped`, Layer, Ring, image affine, samplers, the fringe, build options for file-format constants (never as compile-time constants), and Frame or host batching.