Wire Protocol v3
Machine-readable artifacts published with this site:
wire.schema.json·conformance.json
This document is the language-neutral specification shared by the official TypeScript (@zwire/core/protocol) and Rust (zwire-protocol) implementations of zwire. Both runtimes validate exact wire and behavioral parity against conformance.json and wire.schema.json.
1. Design Goals
Section titled “1. Design Goals”- Zero external codec dependencies: Every message is strict RFC-8259 JSON with no binary framing requirements, enabling direct interop across browsers, Node.js, Bun, Rust servers, Tauri, WebSockets, SSE, and edge workers.
- Deterministic canonical output: Object keys MUST be serialized in lexicographical UTF-8 / code-unit order (
BTreeMapin Rust; sorted keys in JS when canonical comparison is required) so identical logical states produce byte-identical JSON. - Lossless 64-bit integer transfer across JS IEEE-754 & Rust: JavaScript
Numberloses integer precision outside[-9007199254740991, 9007199254740991](±(2^53 - 1)). Signed (i64) and unsigned (u64) integers outside that range are encoded as base-10 decimal strings. - Optimistic-safe synchronization: Remote hydration and sync patches update the committed base value of keyed signals; active optimistic layers (
@zwire/core/tx,zwire-tx) automatically rebase on top without losing local in-flight intents.
2. JSON Data Model & 64-Bit Integer Encoding
Section titled “2. JSON Data Model & 64-Bit Integer Encoding”All wire values belong to the RFC-8259 JSON value set: null, boolean, number, string, array, object.
2.1 Safe-Integer Boundary Rules
Section titled “2.1 Safe-Integer Boundary Rules”| Rust Type | Value Range | Encoded JSON Representation | Decoding Rules |
|---|---|---|---|
i64 |
-9007199254740991 ..= 9007199254740991 |
JSON number (e.g. 42, -9007199254740991) |
Accepts JSON integer, exact integral float in range, or decimal string in i64 range |
i64 |
< -9007199254740991 or > 9007199254740991 |
Decimal JSON string (e.g. "9007199254740992", "-9223372036854775808") |
JavaScript consumers pass directly to BigInt(value) |
u64 |
0 ..= 9007199254740991 |
JSON number (e.g. 9007199254740991) |
Accepts non-negative JSON integer, exact integral float in range, or decimal string in u64 range |
u64 |
> 9007199254740991 |
Decimal JSON string (e.g. "9007199254740992", "18446744073709551615") |
JavaScript consumers pass directly to BigInt(value) |
f64 |
Finite IEEE-754 floats | JSON number | Non-finite values (NaN, ±Infinity) MUST NOT be emitted as raw JSON tokens |
2.2 String & Key Safety
Section titled “2.2 String & Key Safety”- Strings use standard RFC-8259 escaping (
\",\\,\n,\r,\t,\b,\f,\uXXXX) and preserve valid Unicode characters verbatim (e.g."한글/Ω"). - Implementations MUST treat object keys as plain data keys (
__proto__,constructor,prototypeMUST NOT trigger prototype pollution in JavaScript).
3. Out-of-Order Hydration (HydratedState)
Section titled “3. Out-of-Order Hydration (HydratedState)”A HydratedState payload is a JSON object mapping string keys to committed wire values:
{ "count": 42, "enabled": true, "user": "Ada"}Semantics
Section titled “Semantics”- Committed base snapshot (
dehydrate):dehydrate(scope)snapshots ONLY the committed base value of every keyed signal registered inscope, ignoring active optimistic overlays (txlayers) and speculative drafts. - Atomic batched apply (
hydrate):hydrate(scope, state)applies all entries in a single reactive batch while suppressing localSyncBridgeoutbound echo. - Out-of-order delete-on-consume buffer:
- If
hydrate()receives a key that has not yet been registered inscope, the value is stored in the scope’s hydration buffer. - When a lazily loaded route or module subsequently calls
hydratable(key, initial), it immediately consumes the buffered value (deleting it from the buffer) instead ofinitial. - If a key is already registered when
hydrate()runs, its committed base value is updated directly and any stale buffered entry for that key is cleared.
- If
4. Incremental State Synchronization (StatePatch)
Section titled “4. Incremental State Synchronization (StatePatch)”SyncBridge exchanges batches of StatePatch objects encoded as a JSON array:
[ { "key": "count", "origin": "remote", "txId": "srv_1", "value": 99 }, { "key": "user", "origin": "remote", "txId": "srv_1", "value": "Grace" }]Fields
Section titled “Fields”| Field | Type | Required | Description |
|---|---|---|---|
key |
string |
Yes | Logical signal key registered in the scope or explicit bridge map |
value |
JSON value | Yes | Committed base value for key |
origin |
"local" | "remote" |
Yes | Direction of the patch relative to the emitting peer |
txId |
string |
Yes | Unique transaction identifier for batch correlation and echo suppression |
Behavioral Invariants
Section titled “Behavioral Invariants”- Coalesced per-batch outbound emission: Multiple local writes to the same key within one
batch()coalesce into a singleStatePatchcontaining the latest committed value, flushed once at batch completion via the scope’s flush hook. - Echo suppression: Every outbound batch records its
txIdin a bounded ring buffer (at least 64 recent IDs). Incoming patches whosetxIdmatches a recently sent localtxIdMUST be ignored to prevent infinite sync loops. In bidirectional deployments, each peer MUST namespace itstxIdgenerator (e.g.srv_<seq>,cli_<seq>, or UUIDs) to prevent accidental ID collisions across peers. - Remote rebase: Applying a remote patch writes to the signal’s committed base value, automatically rebasing any active optimistic layers (
OptimisticLayer) in creation order. - Unregistered remote keys: Remote patches targeting keys not yet registered in the scope are buffered in the scope’s hydration buffer so lazily initialized signals observe the latest remote state upon registration.
- Inbound replay window: A delivery contains complete transactions. All patches carrying a fresh ID within that delivery apply in wire order. Record its distinct incoming IDs in first-seen order, retaining the latest 64 independently of outbound IDs. A later delivery bearing a remembered ID is ignored, even if the value has changed since the original delivery.
originis relative to the sender and does not identify an echo. Senders must use a new ID for every independent transaction and reuse the original ID and contents on retry. - Push failures: A rejected asynchronous push reports its error and original batch through the TypeScript bridge’s
onPushError, falling back to the scope inspector. The bridge performs one push per batch. Adapters that support retry preserve FIFO order and retry the same transaction IDs and payloads. A successful WebSocket send means the socket accepted the frame. End-to-end delivery guarantees require a transport-level acknowledgement. Acknowledgement and replay beyond the bounded history are application concerns.
5. Conformance Verification
Section titled “5. Conformance Verification”Any change to:
- Optimistic layer rebasing, surgical rollback, or atomic
settlerollback, - STM
Draft(committedvseffectivereads and read-set conflict detection), - Deterministic collection ordering, tie-breaking, filtered range windows, and Top-K boundary pruning,
- Inbound replay, outbound echo suppression, and stable transaction IDs across retries, or
- Wire JSON formatting (
HydratedState,StatePatch,i64/u64boundaries, escaping)
MUST update conformance.json, synchronize the packaged Rust test copy via mise run sync:spec, and pass both the TypeScript (ts/tests/conformance.test.ts) and Rust (rust/crates/zwire/tests/conformance.rs) conformance suites.