diff --git a/doc/2026-11-01_design_id805.md b/doc/2026-11-01_design_id805.md new file mode 100644 index 0000000000..771ac2ee02 --- /dev/null +++ b/doc/2026-11-01_design_id805.md @@ -0,0 +1,403 @@ +# Design: F12.11 delta and binary frames + +- Date: 2026-11-01 +- Status: **decision-ready design**; implementation remains on issue #805. +- Issue: [#805 — id: F12.11 delta and binary frames (screen patches, resume tokens)](https://github.com/developing-today/code/issues/805). +- Scope: design only. This record does not close #805 or change implementation. + +## The decision + +Choose how the existing cell-run `ScreenPatch` becomes a compatible session +protocol: first as a revisioned patch, then optionally binary-encoded and +compressed, with a resume token that identifies the exact screen revision a +client has applied. The design must preserve full-view fallback, distinguish a +screen revision from the existing world-event cursor, and decide whether the +binary representation is allowed to proceed while the broader F11.12 work is +still planned. + +```text +world state ──► connection-local ScreenSurface ──► revisioned ScreenPatch + │ │ + └── full View on reset ├── JSON v1 (legacy / fallback) + └── binary v2 (negotiated) + └── optional compression +client's last-applied resume token ──► retained base ──► patch to current view +``` + +The existing `ScreenPatch` is the canonical delta model. JSON and binary are +encodings of that same model, not separate patch semantics. + +## 1. Context and current state + +### 1.1 Issue scope and the completed first slice + +Issue #805 calls for cell-run screen patches, optional binary encoding and +compression, resume tokens that let reconnecting clients receive a patch, a +patched-client/full-frame parity test, and a bandwidth target under 10% of a +full frame. The issue's newest implementation note says PR #1802 merged the +transport-neutral `ScreenPatch` first slice; binary encoding, compression, +resume tokens, and transport/session wiring remain on #805 ([issue comment, +2026-10-28](https://github.com/developing-today/code/issues/805#issuecomment-6481676637)). + +At this checkout, `ScreenPatch` and `CellRun` are public Serde types. A patch +contains the screen version/dimensions and row-major replacement runs; +`diff` refuses mismatched versions or dimensions and groups adjacent changed +cells ([`world_presentation.rs:112-181`](../pkgs/id/src/world_presentation.rs#L112-L181)). +`apply` checks the base version/dimensions and rejects unordered, overlapping, +or out-of-range runs ([`world_presentation.rs:183-209`](../pkgs/id/src/world_presentation.rs#L183-L209)). The existing tests cover +parity and measure JSON-serialized size, not binary encoding or compression +([`world_presentation.rs:537-591`](../pkgs/id/src/world_presentation.rs#L537-L591)). The +small-change test compares JSON strings for `ScreenPatch` and `ScreenSurface`, +not the complete serialized server `View` or a transport frame +([`world_presentation.rs:557-570`](../pkgs/id/src/world_presentation.rs#L557-L570)). + +One validation gap should be closed before decoded patches are accepted from a +remote client: `apply` constructs the result directly, while +`ScreenSurface::from_cells` validates glyphs, wide-cell continuations, and +styles ([`world_presentation.rs:45-77`](../pkgs/id/src/world_presentation.rs#L45-L77), +[`world_presentation.rs:183-209`](../pkgs/id/src/world_presentation.rs#L183-L209)). +The patch path must ensure that applying untrusted run contents cannot produce +a `ScreenSurface` that the normal constructor would reject. + +### 1.2 The F11.9 baseline is not a wire-size baseline + +F11.9 is complete: its committed record names the rerunnable measurement test +and the measured-at commit ([`baseline_bytes_per_frame.md:1-19`](2026-10-27T00-00-00Z_baseline_bytes_per_frame.md#L1-L19)); the table has +seven checked-in examples, with raw guest-frame sizes from 7 to 1,010 bytes +([`baseline_bytes_per_frame.md:21-31`](2026-10-27T00-00-00Z_baseline_bytes_per_frame.md#L21-L31)). The record explicitly says +these bytes are measured at the sandbox boundary and presenter JSON/ANSI +encodings are out of scope ([`baseline_bytes_per_frame.md:9-19`](2026-10-27T00-00-00Z_baseline_bytes_per_frame.md#L9-L19)). The older Phase 11 +status table still says F11.9 is planned ([`2026-10-20_phase-11-status.md:19`](../.opencode/plans/2026-10-20_phase-11-status.md#L19)), but #542's later +completion note records PR #1429 merged and the baseline committed +([issue #542, completion note](https://github.com/developing-today/code/issues/542#issuecomment-6449102224)). Use the committed +baseline, not the stale status row. + +The under-10% test must compare bytes at one layer. It must not divide an +encoded presentation patch by the raw guest bytes and call that a wire-size +ratio. Keep the F11.9 values as context, and compare a patch to the full-screen +payload encoded with the same protocol version and codec. The exact metric is +an open question for Drew in §7. + +### 1.3 The current session protocol sends full views as text + +`send_view` obtains the view for a connection's viewport, parses an optional +typed screen surface, fits it to that viewport, then sends a full `View` +([`world_session/mod.rs:2038-2083`](../pkgs/id/src/world_session/mod.rs#L2038-L2083)). A `View` currently carries +`sequence`, legacy string `data`, and optional full `surface` +([`world_session/types.rs:279-285`](../pkgs/id/src/world_session/types.rs#L279-L285)). The centralized +`send_json` serializes every current server frame to a `String` and counts the +serialized payload bytes ([`world_session/mod.rs:2466-2479`](../pkgs/id/src/world_session/mod.rs#L2466-L2479)). + +The low-level Iroh/SSH envelope is already arbitrary bytes: a big-endian +`u32` length and payload, capped at 1 MiB +([`frames.rs:1-20`](../pkgs/id/src/frames.rs#L1-L20), +[`frames.rs:34-47`](../pkgs/id/src/frames.rs#L34-L47)). But the session seam +narrows frames back to UTF-8 text: `SessionIo::send` takes `String`, and +`Inbound` represents non-UTF-8 input as `Unsupported` +([`world_session/types.rs:35-56`](../pkgs/id/src/world_session/types.rs#L35-L56)). Iroh and SSH +decode bodies as UTF-8, and the WebSocket adapter rejects binary messages +([`world_net.rs:110-125`](../pkgs/id/src/world_net.rs#L110-L125), +[`world_ssh.rs:637-655`](../pkgs/id/src/world_ssh.rs#L637-L655), +[`web/world_ws.rs:416-455`](../pkgs/id/src/web/world_ws.rs#L416-L455)). Changing +`frames.rs` alone therefore cannot deliver binary screens end to end. + +The shell contract says additive changes bump its revision; changing a frame +or field requires protocol v2 and a new ALPN; it also says a new frame kind +waits for F11.12. It records Iroh, WebSocket, and SSH envelopes separately +([`shell-contract.v1.json:5-23`](../pkgs/id/contract/shell-contract.v1.json#L5-L23)). +F11.12's state is not a simple yes/no: issue #227's specific rollback/version +contract landed in PR #1353 and the issue closed, while the newer Phase 12 plan +still says F11.12 remains planned because `journal check` and `journal backup` +are absent ([issue #227, completion note](https://github.com/developing-today/code/issues/227#issuecomment-6440210260); +[`phase-12-platform-flexibility.md:81`](../.opencode/plans/phase-12-platform-flexibility.md#L81)). The shell-contract gate +therefore needs an explicit interpretation before a new binary frame kind is +introduced; see Q1. + +### 1.4 Event cursors do not identify screen revisions + +The optional `join.after` is a world-event sequence cursor +([`world_session/types.rs:78-82`](../pkgs/id/src/world_session/types.rs#L78-L82)). Reconnect currently +replays retained events when possible, otherwise sends a snapshot, and then +sends full views; a lagged live event stream also causes a snapshot and full +view ([`world_session/mod.rs:1846-1919`](../pkgs/id/src/world_session/mod.rs#L1846-L1919), +[`world_session/mod.rs:1989-2007`](../pkgs/id/src/world_session/mod.rs#L1989-L2007)). The view watch's +sequence is the world sequence at a state change and remains unchanged for +host events ([`world/handle.rs:155-159`](../pkgs/id/src/world/handle.rs#L155-L159)); therefore +multiple rendered views can share an event sequence. A resume token must name +a distinct view revision and must not overload `join.after`. + +Screen state is also viewport-specific: resize is connection-local and causes +an immediate full `send_view`; the screen is fitted to at most 120×50 +([`world_session/mod.rs:2183-2199`](../pkgs/id/src/world_session/mod.rs#L2183-L2199), +[`world_presentation.rs:14-19`](../pkgs/id/src/world_presentation.rs#L14-L19)). A baseline from a different +viewport or screen version cannot be patched; `ScreenPatch::diff` already +returns `None` when dimensions or version differ +([`world_presentation.rs:143-151`](../pkgs/id/src/world_presentation.rs#L143-L151)). + +### 1.5 Adjacent performance work stays separate + +Issue #561 covers server-side redraw coalescing; #562 covers terminal-side +incremental ANSI rendering. Neither replaces this transport-neutral screen +patch and resume design ([#561](https://github.com/developing-today/code/issues/561), +[#562](https://github.com/developing-today/code/issues/562)). + +## 2. Viable options and trade-offs + +### 2.1 Patch representation and compatibility + +| Option | Benefits | Costs / risks | +| ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Keep full JSON `View` frames | No client or transport changes; easy to inspect. | Does not deliver deltas or the issue's binary option. | +| Add an optional JSON patch inside the existing `view` frame | Reuses `ScreenPatch`; can roll out additively; old clients can keep receiving full `surface`. | Still JSON; must negotiate support and bump shell-contract revision; cannot by itself satisfy binary framing. | +| Send base64/hex binary bytes inside JSON v1 | Preserves text transports and current `SessionIo`. | Encoding overhead can erase the binary savings; compression and binary framing remain hidden inside text. Not recommended for the bandwidth path. | +| Add a negotiated binary representation on a versioned session protocol while retaining v1 JSON | True bytes for WebSocket, Iroh, and SSH; old clients remain on v1; clean place for codec and compression tags. | Requires a byte-capable session seam and each transport adapter; contract v2/new ALPN or transport paths add rollout work. | +| Add an additive `binary_view` frame kind to v1 | Could preserve old clients that ignore unknown server kinds. | Current contract says a new kind waits for F11.12; WebSocket currently rejects binary messages; the logical/wire compatibility rule needs Drew's ruling. | + +### 2.2 Binary codec + +| Option | Benefits | Costs / risks | +| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| MessagePack with existing Rust and TypeScript codecs | `rmp-serde` and `msgpackr` already exist in the relevant packages; one wire format can serve the Rust transports and browser. | Both codecs need cross-language golden-vector tests; the envelope and schema still need explicit versions. | +| Serialize the existing Serde `ScreenPatch` with `postcard` | Compact Rust encoding and an existing Rust dependency. | The browser needs another decoder; schema evolution and field order must be pinned by codec version and golden vectors. | +| Hand-pack cell runs into a custom byte layout | Full control over tag widths and compactness. | Duplicates validation/serialization logic and creates a second schema to maintain. | +| Use a self-describing format such as CBOR | Easier to inspect and evolve. | Requires selecting/adding a codec dependency and may encode more metadata than this fixed DTO needs. | + +Recommend MessagePack for the initial codec: `rmp-serde` is already an +optional `world` dependency in `pkgs/id/Cargo.toml:19,103`, and `msgpackr` is +already in `pkgs/id/web/package.json:17-21`. Wrap the payload in an explicit +screen-codec version and pin Rust↔TypeScript encoding/decoding with golden +vectors. Do not serialize Rust memory layout or transmute structs into bytes. + +### 2.3 Compression + +| Option | Benefits | Costs / risks | +| ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | +| No compression | Lowest CPU and simplest decoder. | Misses the issue's optional compression opportunity for repetitive larger screens. | +| Compress every binary screen | Simple policy. | Small patches may grow once tags/headers are counted; consumes CPU even when there is no net saving. | +| Attempt compression and emit it only when the complete compressed frame is smaller | Keeps a single logical patch model and avoids sending a known larger representation. | Requires a bounded decompressor and per-frame CPU work; the chosen codec needs measurement. | + +Recommend the third policy. Compression is a transport encoding after patch +serialization; it never changes `ScreenPatch` semantics. Start with one codec +identifier, benchmark it against representative sparse and dense redraws, and +keep the uncompressed binary form when the complete compressed form is not +smaller. Cap both compressed input and decompressed output at the protocol's +frame limit; never allocate based only on an untrusted claimed output size. + +### 2.4 Resume state + +| Option | Benefits | Costs / risks | +| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | +| Reuse `join.after` as the screen cursor | No new token or state. | Incorrect: it is a world-event cursor; host-driven views may share it, and event projection can skip hidden events. | +| Retain unbounded per-client view history | Can produce a patch from any old view. | Memory grows with disconnected clients and time; not bounded by the existing 1,024-event journal replay window. | +| Opaque token for a bounded, retained screen baseline; full-view fallback when absent or expired | Bounded storage; token names the view the client actually applied; predictable fallback for stale or incompatible baselines. | Requires a retention policy and a cache keyed to the right world/participant/viewport lineage. | + +Recommend the bounded baseline. The token is a cursor, not an authorization +credential: reconnect still requires the existing join capability. Bind the +token to world, participant/session lineage, view revision, screen version, +and viewport dimensions. Retain enough baseline state to diff it against the +current view; if the baseline is evicted, invalid, or belongs to another +viewport, send a full view instead. The server never sends a patch unless it +knows the client's base. + +## 3. Recommendation + +1. **Ship JSON patches first on the existing `view` semantics.** Keep + `ScreenPatch` as the only delta model. Add a monotonic per-session + `view_revision` and explicit patch base/target revisions; keep the existing + world-event `sequence` unchanged. Clients that do not negotiate patch + support continue receiving full `surface` views. +2. **Add resume over the same JSON patch path.** The client stores a resume + token only after it has applied the corresponding view/patch. A valid, + retained baseline receives a patch to the latest screen; stale, missing, + resized, or incompatible state receives a full view. Resize, module + replacement, a view-format change, or a detected gap resets the baseline. +3. **Keep protocol v1 text JSON; add binary as an explicitly versioned, + negotiated representation.** Do not smuggle binary as base64 and do not + change v1's text envelope. Retain the v1 path for old shells. For binary, + use a v2 session protocol/path (`/id-world/2`, `/ws/world/2`, and + `id-world/2`) and extend the transport interface to carry either text or + bytes. Encode the same logical view/patch semantics with a versioned + envelope and bounded decoder. The binary rollout is conditional + on Drew's answer to Q1; if the existing F11.12 gate is intended to include + ephemeral presentation frames, keep this phase behind that gate. +4. **Add optional compression after binary encoding.** Negotiate it, use one + initial codec, and send compressed bytes only when the whole encoded result + is smaller. Bound decompression by the same frame-size ceiling. +5. **Measure parity and bytes at the session-frame layer.** Compare the + complete logical `View` payload passed to `SessionIo` (including type, + revision, and codec/compression metadata) with a full snapshot encoded + using the same negotiated version/codec. Record F11.9's raw guest-frame + baseline alongside the new measurements, but do not mix the two layers. + Send a full snapshot whenever a patch is larger than the corresponding + snapshot. + +This keeps the first usable patch path low-risk, makes reconnect correctness +independent of transport encoding, and makes binary/compression optional +optimizations rather than prerequisites for patch parity. + +## 4. Invariants for implementation + +- A patch is applied only to a screen with the same version, dimensions, and + `base_view_revision`; applying it yields the same validated `ScreenSurface` + as a full view at `target_view_revision`. +- A decoded patch cannot produce an invalid portable grid: validate the + patched result, including one/two-column glyphs and continuations, before it + reaches a renderer. +- `view_revision` is monotonically increasing for each session lineage and + independent of event `sequence`; `join.after` keeps its current event-replay + meaning. +- Only a screen presentation uses `ScreenPatch`. Legacy text and any future + non-screen presentation continue as full `View.data`. +- A client receives a patch only from the exact retained base it claims to + have applied. A missing, stale, malformed, or mismatched resume token, a + resize, module change, or history gap causes a full-view reset. +- The resume token does not confer join authority; every resume is subject to + the existing capability validation and projection rules. +- Binary is opt-in. V1 clients keep receiving the current text JSON shape; + unknown or unsupported encodings are refused or fall back to v1/full view, + never guessed. +- The binary decoder rejects unknown versions, invalid dimensions/runs, + truncated data, oversized frames, and decompression that exceeds the frame + bound. Existing screen bounds remain 120×50 and the framed payload remains + at most 1 MiB (`world_presentation.rs:14-19`; `frames.rs:16-20`). +- Compression is not mandatory and is used only when the complete compressed + representation is smaller than its uncompressed equivalent. +- The <10% result is measured on representative sparse redraws against a full + snapshot with the same wire version and codec. Dense changes may use a full + snapshot; parity remains mandatory for both paths. +- Screen patches and resume metadata remain ephemeral presentation state; + they do not add journal entries or alter world-event replay. + +## 5. Acceptance criteria + +1. Existing full-view clients continue to work unchanged on protocol v1. +2. A negotiated JSON patch client and a full-view client render byte-identical + normalized screen surfaces after the same sequence of changes. +3. Property/unit coverage includes empty changes; one-cell, adjacent-cell, + style-only, and wide-glyph changes; malformed/out-of-order/overlapping + runs; invalid cells; dimension/version mismatch; and patch-size fallback. +4. A retained valid resume token reconnects with a patch from its applied + revision to current state. Expired/unknown tokens, viewport changes, module + changes, and retention gaps produce a full view, not a speculative patch. +5. JSON and binary paths decode to identical `ScreenSurface` values. Binary + golden vectors pin the encoding version; unsupported versions and + malformed/truncated payloads fail closed. +6. Compression round-trips to the same logical frame, enforces bounded output, + and is selected only when the complete compressed frame is smaller. +7. The repeatable size test records complete logical `View` payload bytes for + full snapshots and patches, excluding only transport-specific outer + framing, for the F11.9 example set at 80×24 and 200×60 and defined sparse + redraw fixtures. The nominated typical-redraw cases meet the under-10% + ratio; the report separately retains the raw F11.9 baseline values. +8. End-to-end tests cover WebSocket, Iroh, and SSH session adapters, including + v1 JSON fallback and the selected v2 binary path. The browser applies + patches without replacing the full-surface validation/fallback path + (`web/src/world-surface.ts:343-449`). + +## 6. Phased implementation plan + +Each phase can merge independently with binary disabled by default and the +existing full-view path intact. + +1. **Revisioned JSON patches.** Add per-session view revisions, patch base and + target revisions, capability negotiation, and JSON patch application to the + existing `view` semantics. Keep `sequence` as the event cursor. On resize, + module switch, or missing base, send a full view. Update the shell contract + additively. **Done when:** both patch and legacy clients pass parity tests; + no new binary transport is required. +2. **Resume tokens and bounded baselines.** Issue tokens for a specific + applied view revision; retain a bounded baseline cache; compute a catch-up + patch when the token is valid. Fall back to a full view on expiry, cache + miss, viewport/version mismatch, or gap. **Done when:** reconnect tests + cover retained, expired, tampered, and wrong-viewport tokens; tokens never + bypass join authorization. +3. **Versioned binary representation.** Add a byte-capable `SessionIo`/inbound + frame abstraction and a versioned screen codec. Keep protocol v1 text JSON + unchanged; add negotiated v2 routes (`/id-world/2`, `/ws/world/2`, and + `id-world/2`) for clients that support binary. Update WebSocket, Iroh, and + SSH adapters and the shell contract together. + **Gate:** resolve Q1 before adding the binary protocol path. **Done when:** + all three adapters round-trip the same logical surface and old clients + remain on v1. +4. **Optional compression.** Add one negotiated compression codec around the + v2 binary screen payload; select it only when its complete frame is + smaller, and cap decompressed output. **Done when:** compressed and raw + parity tests pass and no small-frame fixture grows on the wire. +5. **Measure and enable.** Add repeatable sparse/dense redraw fixtures and + report complete logical `View` payload bytes for full snapshots versus + patches, excluding transport-specific outer framing, across the F11.9 + viewport/example matrix. Keep full-frame fallback for dense + changes. **Done when:** parity and the agreed under-10% metric pass, with + all transport adapters tested; binary remains opt-in unless separately + rolled out. + +## 7. Questions for Drew + +### Q1 — Does F11.12 gate ephemeral binary presentation frames? + +The shell contract says a new frame kind waits for F11.12 +([`shell-contract.v1.json:5`](../pkgs/id/contract/shell-contract.v1.json#L5)). The specific +rollback/versioning work tracked by #227 landed in PR #1353, but the latest +Phase 12 plan still says F11.12 remains planned because journal check/backup +are not implemented ([#227 completion note](https://github.com/developing-today/code/issues/227#issuecomment-6440210260); +[`phase-12-platform-flexibility.md:81`](../.opencode/plans/phase-12-platform-flexibility.md#L81)). The shell contract +classifies connection-local presentation context as ephemeral and never +journaled ([`shell-contract.v1.json:31-35`](../pkgs/id/contract/shell-contract.v1.json#L31-L35)). + +- **Option A — keep the gate broad:** finish all F11.12 work, including the + journal check/backup tools, before introducing any binary screen frame. + This follows the literal frame-kind gate but delays binary F12.11 work. +- **Option B — scope the gate to journaled kinds (recommended):** keep v1 + JSON; add binary screen encoding as a versioned v2 representation of the + existing ephemeral `View`, with a separate negotiated route and no journal + entry. Amend the contract language so F11.12 gates journaled kinds only. +- **Option C — avoid a binary wire frame:** carry encoded bytes inside v1 JSON + (base64/hex). This avoids a new transport envelope but risks erasing the + bandwidth gain. + +Recommendation: **B**, because `View` is explicitly ephemeral and the issue +does not add persistent world state. If Drew chooses A, leave phase 3 gated; +the design and earlier JSON-patch/resume phases still stand. + +### Q2 — What is the denominator for the under-10% target? + +- **Option A:** raw guest-frame bytes from F11.9. +- **Option B (recommended):** complete logical `View` payload bytes passed to + `SessionIo`, including patch metadata but excluding transport-specific outer + framing; compare with a full snapshot encoded with the same protocol version + and codec, and list the F11.9 raw sizes separately. +- **Option C:** full transport bytes including each adapter's outer framing. + +Recommendation: **B**. F11.9 explicitly excludes presenter encodings, so A +mixes layers; C varies by transport envelope. If Drew wants C as a second +metric, report it separately rather than changing the parity/size gate. + +No other decision needs Drew before implementation can start; the codec +algorithm and adaptive compression threshold can be selected by the +repeatable size/CPU measurements in phases 4–5. + +## Non-goals + +- Do not change the `ScreenPatch` cell-run meaning or redo the merged first + slice. +- Do not change world-event `sequence`, journal formats, event replay, or + capability semantics. +- Do not replace or remove protocol v1, its JSON view, or the current + full-surface render fallback. +- Do not implement server redraw batching (#561) or terminal ANSI diffing + (#562) here. +- Do not promise that every dense redraw is smaller than a full frame; send a + full snapshot when that is the smaller or safer representation. + +## References + +- [Issue #805](https://github.com/developing-today/code/issues/805) and its + latest implementation/scope note (PR #1802 merged; + [comment](https://github.com/developing-today/code/issues/805#issuecomment-6481676637)). +- [F11.9 bytes-per-frame baseline](2026-10-27T00-00-00Z_baseline_bytes_per_frame.md). +- `pkgs/id/src/world_presentation.rs`, `pkgs/id/src/frames.rs`, + `pkgs/id/src/world_session/{types.rs,mod.rs}`, + `pkgs/id/src/{world/handle.rs,world_net.rs,world_ssh.rs}`, + `pkgs/id/src/web/world_ws.rs`, and `pkgs/id/web/src/world-surface.ts`. +- `pkgs/id/contract/shell-contract.v1.json`. +- [F12.11 roadmap entry](../.opencode/plans/phase-12-platform-flexibility.md#L50).