# PSF1 wire format

Status: normative specification of PSF1 as produced and accepted by schema version 2.

PSF1 is the binary encoding of market-data frames on the WebSocket stream
`wss://api.optionsdata.ai/v1/stream`. This document says how every byte of a frame is laid out, how to rebuild
values from it, which state a decoder keeps between frames, and when it must reject a frame. With this document
and the schema message from the session's `hello`, you can write a complete decoder in any language.
How the WebSocket session works (authentication, `hello`, `list`, `sub`, `gap` and error messages) is in
[`protocol.md`](protocol.md) §2. This document covers it only where it touches frames (§7).

The keywords MUST, MUST NOT, SHOULD and MAY are used as in RFC 2119. "Reject" means: report the frame as
invalid and leave all decoder state exactly as it was before the frame (§6).

Contents: 1 scope and versioning · 2 the schema message · 3 primitive encodings · 4 frame layout ·
5 state and delta bases · 6 validation · 7 sequencing on the WebSocket · 8 test vectors · 9 decoder checklist.

---

## 1. Scope and versioning

### 1.1 What PSF1 is

A PSF1 **frame** is one binary WebSocket message. It carries rows for exactly one **stream**, identified by
(underlying iid, expiration). A frame is either a **snapshot**, which replaces the stream's state, or a **delta**,
which applies changes to it. Frames carry no field names or types. Every frame is interpreted using the
**descriptors** (record and field definitions) from the session's schema message.

PSF1 is stateful. Numeric values of some records are sent as differences from the previously sent value (§5).
A decoder therefore has to see every frame of a stream, in order, starting from a snapshot. PSF1 itself is
uncompressed. The WebSocket transport may compress it (permessage-deflate), and your WebSocket library removes
that compression before you see the frame.

### 1.2 Versions

There are three separate version numbers:

| Where | Value today | Meaning |
|---|---|---|
| The magic bytes `PSF1` at the start of every frame | `PSF1` | The frame grammar in this document. There is no separate version byte. A different grammar would use different magic. |
| `hello.version` (session message) | `1` | The WebSocket session protocol ([`protocol.md`](protocol.md) §2). |
| `hello.schema.version` | `2` | The descriptor set: record IDs, field IDs, names, wire types, units. |

The schema message is the only source of descriptors. A decoder MUST build its descriptor tables from the
`schema` object of the `hello` it received on this connection, not from a copy it shipped with.

### 1.3 Compatibility rules

Within one schema `version`, descriptors only grow:

- Record IDs and field IDs are permanent. An ID is never reused for something else.
- **Additive changes** are new records (new record IDs) and new fields (new field IDs) in existing records.
  They keep the same `version`.
- Renaming a field, removing it, or changing its `wire_type` or `unit` requires a new `version`.

What a decoder MUST do:

- **New `hello` on a connection:** discard all frame state (every stream's bases, sequence numbers and folded
  rows) and rebuild the descriptor tables from the new schema.
- **Different schema `version` from the one your application was written for:** the reference decoder
  refuses the schema outright (it will not decode any frame). You MAY decode anyway, but field meanings may have
  changed. Do not assume compatibility across versions.
- **Fields your application does not use or know** ("unknown fields"): the field is still described in the
  received schema. A decoder MUST fully decode its value using the received descriptor (to stay aligned in the
  byte stream) and MUST update its delta base exactly as for any other field (§5.5). It MAY then drop the
  value instead of handing it to the application.
- **Records your application does not use or know** ("unknown records"): same rule. Decode every row of the
  section using the received descriptor, keep the bases, then MAY drop the rows.
- **IDs that are not in the received schema:** a record ID or field ID that does not appear in the received
  schema cannot be decoded (its length is unknown). The decoder MUST reject the frame (§6).
- If your application does have a built-in copy of the descriptors, the reference decoder refuses a received
  schema in which a field it knows (same record ID and field ID) has a different `name`, `wire_type` or `unit`.
  `quantum`, `exact_increment`, `enum_values` and `key` are always taken from the received schema, not
  compared.

---

## 2. The schema message

The `hello` message is a WebSocket text message:

```json
{"type":"hello","version":1,"schema":{ ...schema message... }}
```

`schema` is a JSON object (not a string containing JSON). Its keys:

| Key | JSON type | Meaning |
|---|---|---|
| `version` | integer | Schema version (§1.2). |
| `records` | array | One descriptor per record type. |
| `records[].id` | integer, 0–65535 | Record ID. Appears in frame sections. Unique within the schema. |
| `records[].name` | string | Record name, e.g. `"quote"`. |
| `records[].fields` | array | Field descriptors. |
| `fields[].id` | integer, 0–63 | Field ID; the field's bit in the row mask (§4.5). Unique within the record. |
| `fields[].name` | string | Field name. Unique within the record. |
| `fields[].wire_type` | string or object | How the value is encoded (table below). |
| `fields[].unit` | string | Human-readable unit (`"UTC ns"`, `"currency"`, `"code"`, ...). It does not affect decoding. |
| `fields[].quantum` | number or `null` | For `f64` fields: the grid step of a lossy integer encoding (§4.8). |
| `fields[].exact_increment` | number or `null` | For `f64` fields: the grid step of an exact integer encoding (§4.8). |
| `fields[].enum_values` | array of strings | For `enum` fields: the codes, indexed from 0. Empty for other types. |
| `fields[].key` | `true`, or absent | Present and `true` on a **key field** (§5.1). Absent means `false`. |

`quantum` and `exact_increment` are always present (as `null` when unset). `key` is omitted when false. Treat a
missing `quantum` or `exact_increment` as `null`.

`wire_type` values:

| `wire_type` JSON | Value it carries |
|---|---|
| `"i64"` | signed 64-bit integer |
| `"u64"` | unsigned 64-bit integer |
| `"time_ns"` | signed 64-bit integer: nanoseconds since 1970-01-01T00:00:00 UTC |
| `{"decimal": s}` | exact decimal: signed 64-bit coefficient `c`, value `c × 10^-s`. `s` is an integer 0–18 |
| `"f64"` | binary64 float, sent literally or as an integer on a grid (§4.8) |
| `"f32"` | binary32 float, always sent literally. Never has `quantum` or `exact_increment` |
| `"enum"` | one string from `enum_values`, sent as its index |
| `"bool"` | `true` / `false` |
| `"text"` | UTF-8 string |
| `"date"` | UTF-8 string, `YYYY-MM-DD` by convention (the codec does not check the format) |

Every record in schema version 2 lists a field with `id` 0, named `iid`. Field 0 is never sent as a field: the
row's iid comes from the gap encoding (§4.4), and mask bit 0 is forbidden.

The reference decoder refuses a schema in which any of these hold: two records share an `id`; a field `id` is
greater than 63; two fields of one record share an `id` or a `name`; a `quantum` or `exact_increment` is
non-finite or not greater than 0; a decimal scale is greater than 18; an `f32` field has a `quantum` or
`exact_increment`.

Trimmed example (real output of schema version 2, pretty-printed; most records and fields removed):

```json
{
  "version": 2,
  "records": [
    {"id": 1, "name": "contract", "fields": [
      {"id": 0, "name": "iid", "wire_type": "u64", "unit": "iid", "quantum": null, "exact_increment": null, "enum_values": []},
      {"id": 2, "name": "kind", "wire_type": "enum", "unit": "code", "quantum": null, "exact_increment": null,
       "enum_values": ["option", "equity", "etf", "index"]},
      {"id": 5, "name": "expiration", "wire_type": "date", "unit": "date", "quantum": null, "exact_increment": null, "enum_values": []},
      {"id": 8, "name": "right", "wire_type": "enum", "unit": "code", "quantum": null, "exact_increment": null,
       "enum_values": ["call", "put"]},
      {"id": 9, "name": "strike", "wire_type": {"decimal": 3}, "unit": "currency", "quantum": null, "exact_increment": null, "enum_values": []}
    ]},
    {"id": 2, "name": "quote", "fields": [
      {"id": 0, "name": "iid", "wire_type": "u64", "unit": "iid", "quantum": null, "exact_increment": null, "enum_values": []},
      {"id": 1, "name": "event_time", "wire_type": "time_ns", "unit": "UTC ns", "quantum": null, "exact_increment": null, "enum_values": []},
      {"id": 3, "name": "bid", "wire_type": "f64", "unit": "currency", "quantum": null, "exact_increment": 0.01, "enum_values": []},
      {"id": 4, "name": "ask", "wire_type": "f64", "unit": "currency", "quantum": null, "exact_increment": 0.01, "enum_values": []},
      {"id": 5, "name": "bid_size", "wire_type": "f64", "unit": "contracts", "quantum": null, "exact_increment": null, "enum_values": []},
      {"id": 7, "name": "bid_exchange", "wire_type": "text", "unit": "exchange", "quantum": null, "exact_increment": null, "enum_values": []}
    ]},
    {"id": 5, "name": "print", "fields": [
      {"id": 5, "name": "price", "wire_type": "f64", "unit": "currency", "quantum": null, "exact_increment": 0.01, "enum_values": []},
      {"id": 13, "name": "eth", "wire_type": "bool", "unit": "flag", "quantum": null, "exact_increment": null, "enum_values": []}
    ]},
    {"id": 7, "name": "option_analytics", "fields": [
      {"id": 5, "name": "iv", "wire_type": "f64", "unit": "decimal volatility", "quantum": 0.0001, "exact_increment": null, "enum_values": []},
      {"id": 7, "name": "gamma", "wire_type": "f64", "unit": "per point F squared", "quantum": 1e-10, "exact_increment": null, "enum_values": []}
    ]},
    {"id": 10, "name": "flow", "fields": [
      {"id": 4, "name": "level", "wire_type": "enum", "unit": "code", "quantum": null, "exact_increment": null,
       "enum_values": ["contract", "expiration_right", "underlying_right", "strike"], "key": true},
      {"id": 9, "name": "side", "wire_type": "enum", "unit": "code", "quantum": null, "exact_increment": null,
       "enum_values": ["buy", "sell", "undecided"], "key": true},
      {"id": 13, "name": "volume", "wire_type": "f64", "unit": "contracts", "quantum": null, "exact_increment": null, "enum_values": []},
      {"id": 15, "name": "count", "wire_type": "u64", "unit": "prints", "quantum": null, "exact_increment": null, "enum_values": []}
    ]},
    {"id": 11, "name": "exposure", "fields": [
      {"id": 15, "name": "delta_dollar_oi", "wire_type": "f32", "unit": "currency/1% move", "quantum": null, "exact_increment": null, "enum_values": []}
    ]}
  ]
}
```

Parse `quantum` and `exact_increment` as IEEE-754 binary64 using correct rounding (any standard JSON parser
does). The value arithmetic in §4.8 depends on the exact binary64 value.

---

## 3. Primitive encodings

### 3.1 Unsigned varint (LEB128)

Unsigned integers are unsigned LEB128. Each byte carries 7 bits of the value, least significant group first.
The high bit (0x80) set means another byte follows. The last byte has the high bit clear.

Decoding:

```
value = 0; shift = 0
loop:
    if no byte left: reject (truncated)
    b = next byte
    if shift == 126 and b > 0x03: reject (overflow)
    value |= (b & 0x7f) << shift
    if b < 0x80: return value
    shift += 7
```

- A varint is at most **19 bytes** and decodes into a 128-bit unsigned integer. If the 19th byte is reached, it
  MUST be at most `0x03` (it holds bits 126–127 and has no continuation). Anything else is rejected.
- After decoding, each varint is checked against the range of its target (u16, u32, u64, ... as stated where it
  is used). A value outside that range is rejected.
- Producers always emit the shortest encoding. The reference decoder also accepts non-minimal encodings
  (for example `80 00` for 0), and a conforming decoder MUST accept them within the 19-byte limit.

| Value | Bytes |
|---:|---|
| 0 | `00` |
| 5 | `05` |
| 127 | `7f` |
| 128 | `80 01` |
| 300 | `ac 02` |
| 772 | `84 06` |
| 2^64 − 1 | `ff ff ff ff ff ff ff ff ff 01` |

Worked example, `84 06`: `0x84` has the high bit set and contributes `0x04`. `0x06` is the last byte and contributes
`0x06 << 7 = 768`. Value 772.

### 3.2 Signed integers (zigzag)

A signed integer `n` is mapped to an unsigned integer, then written as a varint (§3.1):

```
encode: z = (n << 1) XOR (n >> 127)       (128-bit two's complement, arithmetic shift)
        i.e. z = 2n for n >= 0, z = -2n - 1 for n < 0
decode: n = (z >> 1) XOR -(z AND 1)       i.e. n = z / 2 if z is even, -(z + 1) / 2 if odd
```

Zigzag works on 128-bit integers, so the decoded `n` lies in [−2^127, 2^127 − 1]. Where a narrower range is needed,
it is checked after decoding.

| n | z | Bytes |
|---:|---:|---|
| 0 | 0 | `00` |
| −1 | 1 | `01` |
| 1 | 2 | `02` |
| −5 | 9 | `09` |
| 5 | 10 | `0a` |
| 125 | 250 | `fa 01` |
| 1 800 000 000 000 000 000 | 3 600 000 000 000 000 000 | `80 80 a0 bb d2 9d f1 fa 31` |

### 3.3 Strings

A string is a varint byte length `L`, then exactly `L` bytes of UTF-8. The length counts bytes, not characters.
There is no terminator. The bytes MUST be valid UTF-8, and `L` MUST NOT exceed the remaining bytes. Otherwise
reject. The empty string is the single byte `00`.

Example: `"2026-12-18"` is `0a 32 30 32 36 2d 31 32 2d 31 38`.

### 3.4 Fixed-width values

| Item | Width | Encoding |
|---|---|---|
| Magic | 4 bytes | ASCII `P S F 1` = `50 53 46 31` |
| Snapshot flag | 1 byte | `00` delta, `01` snapshot. Any other value: reject |
| Value tag | 1 byte | `00`, `01` or `02` (§4.7) |
| Literal `f32` | 4 bytes | IEEE-754 binary32, **little-endian**. 1.25 → `00 00 a0 3f` |
| Literal `f64` | 8 bytes | IEEE-754 binary64, **little-endian**. 10.0 → `00 00 00 00 00 00 24 40` |
| `bool` payload | 1 byte | `00` false, `01` true. Any other value: reject |

Everything else in a frame is a varint or a string. There are no other fixed-width integers and no padding or
alignment. (The node-to-edge feed's big-endian length prefixes are outside PSF1 and never reach WebSocket clients.)

---

## 4. Frame layout

### 4.1 Overview

```
frame   := header section_count:uvarint section{section_count}
header  := "PSF1" underlying_iid:uvarint expiration:string seq:uvarint tick_time:svarint snapshot:u8
section := record_id:uvarint row_count:uvarint row{row_count}
row     := iid_gap:uvarint mask:uvarint value{popcount(mask)}
value   := 0x00                                    -- null
         | 0x01 f32le(4) | 0x01 f64le(8)           -- literal float (f32 / f64 fields only)
         | 0x02 payload                            -- typed value, payload depends on wire_type
```

`uvarint` is §3.1, `svarint` is zigzag + varint (§3.2), `string` is §3.3. The last section MUST end exactly at
the end of the message.

Byte diagram (`|` separates items; `..` means variable length):

```
+----+----+----+----+--------+-------------+-------+------------+------+-------------+
| 50 | 53 | 46 | 31 | uiid.. | len.. exp.. | seq.. | tick_time..| snap | sections..  |
+----+----+----+----+--------+-------------+-------+------------+------+-------------+
  'P'  'S'  'F'  '1'

section:  +------------+-------------+--------+--------+-----+
          | record_id..| row_count.. | row 1  | row 2  | ... |
          +------------+-------------+--------+--------+-----+

row:      +----------+---------+------------------+------------------+-----+
          | iid_gap..| mask..  | value(lowest id) | value(next id)   | ... |
          +----------+---------+------------------+------------------+-----+

value:    +-----+-----------------------------+
          | tag | payload (absent if tag 0)   |
          +-----+-----------------------------+
```

### 4.2 Header

In order:

| # | Field | Encoding | Range / meaning |
|---|---|---|---|
| 1 | magic | 4 bytes | MUST be `50 53 46 31` (`PSF1`) |
| 2 | `underlying_iid` | uvarint | MUST fit u32. Instrument ID of the underlying |
| 3 | `expiration` | string | Empty string: the **underlying stream**. Otherwise the expiration date `YYYY-MM-DD` of an **expiration stream**. Not format-checked by the codec |
| 4 | `seq` | uvarint | MUST fit u64. Frame sequence number of this stream (§7) |
| 5 | `tick_time` | svarint | MUST fit i64. UTC nanoseconds since the Unix epoch |
| 6 | `snapshot` | 1 byte | `00` delta, `01` snapshot |
| 7 | `section_count` | uvarint | Number of sections that follow |

The **stream key** is the pair (`underlying_iid`, `expiration`), with the empty expiration as a value of its own.
All per-stream state in §5 and §7 is indexed by it. Which records each kind of stream carries is described in
[`protocol.md`](protocol.md) ("Streams").

### 4.3 Sections

Each section holds all rows of one record type:

| Field | Encoding | Rules |
|---|---|---|
| `record_id` | uvarint | MUST fit u16. MUST be strictly greater than the previous section's `record_id` in this frame. MUST be a record ID in the received schema |
| `row_count` | uvarint | Number of rows that follow |

Each record ID appears at most once per frame, and sections are in increasing record-ID order. A frame may have
zero sections, and a section may have zero rows. Producers do not emit zero-row sections, but decoders accept them.

### 4.4 Row iid and gap encoding

Each row starts with `iid_gap` (uvarint, MUST fit u32). Within a section:

```
iid = 0                                 -- reset at the start of EVERY section
for each row:
    iid = iid + iid_gap                 -- MUST stay <= 2^32 - 1, else reject
```

The first row's gap is therefore its absolute iid. Rows are in non-decreasing iid order, and a gap of 0 repeats
the previous row's iid. Several rows with the same iid are legal: prints (several trades of one contract in one
tick), and keyed records whose rows are told apart by key fields (§5.1). An iid of 0 is accepted on the wire.

### 4.5 Field mask

After the gap comes `mask`, a uvarint that MUST fit u64 (64 bits). Bit `i` (value `1 << i`, bit 0 the least
significant) set means "this row carries field ID `i`". Field ID `i` ↔ mask bit `i`, so field IDs are 0–63.

- **Bit 0 MUST NOT be set** (reject). Field 0 is the iid, which the row already carries in its gap.
- Every set bit MUST name a field ID present in the received descriptor of the section's record. Otherwise
  reject, because the value's encoding cannot be known.
- A clear bit means the field is **absent**: the row says nothing about it (§5.6).
- A mask of 0 is legal: a row with no fields.

Example: fields 3, 4, 5, 7 → `(1<<3)|(1<<4)|(1<<5)|(1<<7)` = 184 → bytes `b8 01`.

### 4.6 Value order

The row's values follow the mask immediately, one per set bit, **in increasing field-ID order** (lowest set bit
first). There are no separators and no lengths: each value's size follows from its tag and the field's `wire_type`.

### 4.7 Value tags

Every value starts with one tag byte:

| Tag | Name | Allowed for | Payload |
|---|---|---|---|
| `00` | null | any field | none. An explicit null |
| `01` | literal float | `f32` and `f64` fields only | `f32`: 4 bytes LE binary32. `f64`: 8 bytes LE binary64. The value MUST be finite (not NaN, not ±infinity) |
| `02` | typed | every type except `f32` | depends on `wire_type` (§4.8) |

Any other tag, tag `01` on a field that is not `f32`/`f64`, and tag `02` on an `f32` field: reject.
A literal `f32` is widened exactly to binary64 when it is delivered.

### 4.8 Tag 2 payloads and value reconstruction

**Numeric types** (`i64`, `u64`, `time_ns`, `decimal`, `f64`) share one integer path:

```
d     = zigzag-decode(uvarint)            -- 128-bit signed (§3.2)
n     = base + d                          -- 128-bit signed; overflow -> reject
```

`base` is the field's delta base (§5). It is 0 for keyed records, in snapshots, and whenever no base is stored.
`n` is the field's **canonical integer**, and it becomes the new base (§5.3). Then, by type:

| `wire_type` | Range check on `n` (else reject) | Delivered value |
|---|---|---|
| `i64` | −2^63 ≤ n ≤ 2^63 − 1 | integer `n` |
| `time_ns` | −2^63 ≤ n ≤ 2^63 − 1 | `n` nanoseconds since 1970-01-01 UTC |
| `u64` | 0 ≤ n ≤ 2^64 − 1 | integer `n` |
| `decimal` (scale `s`) | −2^63 ≤ n ≤ 2^63 − 1 | exact decimal `n × 10^-s` (see below) |
| `f64` | \|n\| < 2^61, and the field MUST have a `quantum` or `exact_increment` | binary64 `float(n) / (1.0 / q)` (see below) |

**Decimal.** `n` is the coefficient. The value is `n × 10^-s`. Keep it exact: use a decimal type, or keep the
integer and the scale. The canonical text form (used in JSON and REST output) is: if `s = 0`, the integer in
base 10. Otherwise an optional `-` (when `n < 0`), then `|n| div 10^s`, `.`, then `|n| mod 10^s` padded with
zeros to exactly `s` digits. Strike coefficient 4500000 with scale 3 is `4500.000`, −5 with scale 3 is `-0.005`.

**f64 on a grid.** Let `q` be the field's `quantum` if it is not null, otherwise its `exact_increment` (if both
are set, `quantum` wins). If neither is set, a tag-2 value on an `f64` field is rejected. The delivered value
MUST be computed in IEEE-754 binary64, round-to-nearest-even, in exactly this order:

```
inv   = 1.0 / q            -- binary64 division
x     = float(n)           -- integer -> nearest binary64 (ties to even); exact when |n| <= 2^53
value = x / inv            -- binary64 division
```

Do **not** compute `n * q`. It gives a different last bit for many values: with `q = 0.01` and `n = 35`,
`35 / (1.0/0.01)` is `0.35` but `35 * 0.01` is `0.35000000000000003`. For the step values in schema version 2,
`1.0 / q` is exactly 100, 1000, 10 000, 1 000 000 or 10 000 000 000.

The two grid kinds differ only on the producer side: with `quantum` the producer rounds the value to the nearest
step (lossy, error at most half a step plus one binary64 ulp). With `exact_increment` the producer uses tag 2 only
when the reconstruction above returns the original value bit for bit, and otherwise sends a literal. Either way,
a producer sends tag 1 (literal) for an `f64` field without a step, and when `|round(v / q)|` would reach 2^61.
A decoder MUST accept a literal on any `f64` field, including fields that have a step.

**Non-numeric types** (all absolute; they never use a base):

| `wire_type` | Tag 2 payload | Delivered value / rules |
|---|---|---|
| `enum` | uvarint index `k` | `enum_values[k]`. `k` MUST be less than the length of `enum_values`, else reject |
| `bool` | 1 byte | `00` false, `01` true, else reject |
| `text` | string (§3.3) | the string |
| `date` | string (§3.3) | the string (`YYYY-MM-DD`) |
| `f32` | — | tag 2 is forbidden. Reject |

### 4.9 Worked example

Two frames of one expiration stream, built with the reference encoder using the schema-version-2 descriptors
from §2. Values are synthetic. Stream: `underlying_iid` 7, expiration `2026-12-18`.

**Frame 1: snapshot, seq 1.** Rows: contract iid 3 (`kind`=option, `right`=put, `strike`=4500.000); quote iid 3
(`bid` 1.25, `ask` 1.30, `bid_size` 10.0, `bid_exchange` explicit null); quote iid 5 (`bid` 0.05).

```
50 53 46 31 07 0a 32 30 32 36 2d 31 32 2d 31 38 01 80 80 a0 bb d2 9d f1 fa 31 01 02 01 01 03 84 06 02 00
02 01 02 c0 a8 a5 04 02 02 03 b8 01 02 fa 01 02 84 02 01 00 00 00 00 00 00 24 40 00 02 08 02 0a
```

| Bytes | Meaning |
|---|---|
| `50 53 46 31` | magic `PSF1` |
| `07` | underlying_iid = 7 |
| `0a 32 30 32 36 2d 31 32 2d 31 38` | expiration: length 10, `2026-12-18` |
| `01` | seq = 1 |
| `80 80 a0 bb d2 9d f1 fa 31` | tick_time: z = 3 600 000 000 000 000 000 → n = 1 800 000 000 000 000 000 ns |
| `01` | snapshot = true (every numeric base is 0 in this frame) |
| `02` | 2 sections |
| `01` | section: record 1 (`contract`) |
| `01` | 1 row |
| `03` | iid gap 3 → iid = 0 + 3 = **3** |
| `84 06` | mask 772 = bits 2, 8, 9 → fields `kind`, `right`, `strike` |
| `02 00` | field 2 `kind` (enum): tag 2, index 0 → `"option"` |
| `02 01` | field 8 `right` (enum): tag 2, index 1 → `"put"` |
| `02 c0 a8 a5 04` | field 9 `strike` (decimal 3): tag 2, z = 9 000 000 → d = 4 500 000; n = 0 + d = 4 500 000 → **4500.000** |
| `02` | section: record 2 (`quote`) |
| `02` | 2 rows |
| `03` | iid gap 3 → iid = 0 + 3 = **3** (the gap restarts from 0 in each section) |
| `b8 01` | mask 184 = bits 3, 4, 5, 7 → `bid`, `ask`, `bid_size`, `bid_exchange` |
| `02 fa 01` | field 3 `bid` (f64, exact_increment 0.01): z = 250 → n = 125 → 125 / 100.0 = **1.25** |
| `02 84 02` | field 4 `ask`: z = 260 → n = 130 → **1.3** |
| `01 00 00 00 00 00 00 24 40` | field 5 `bid_size` (f64, no step): literal binary64 → **10.0** |
| `00` | field 7 `bid_exchange`: explicit **null** |
| `02` | iid gap 2 → iid = 3 + 2 = **5** |
| `08` | mask 8 = bit 3 → `bid` |
| `02 0a` | `bid`: z = 10 → n = 5 → **0.05** |
| (end) | no bytes remain: valid |

Bases after frame 1 (quote is unkeyed, contract is unkeyed): quote iid 3: bid 125, ask 130, bid_size 0
(literal), bid_exchange 0 (null). Quote iid 5: bid 5. Contract iid 3: strike 4 500 000, kind 0, right 0
(non-numeric values store base 0).

**Frame 2: delta, seq 2.** Rows: quote iid 3 (`bid` 1.20, `bid_size` explicit null); quote iid 5 (`bid` 0.10);
two prints of iid 5 (`price` 0.10 `eth` false, then `price` 0.12 `eth` true).

```
50 53 46 31 07 0a 32 30 32 36 2d 31 32 2d 31 38 02 80 84 cf 9a d3 9d f1 fa 31 00 02 02 02 03 28 02 09 00
02 08 02 0a 05 02 05 a0 40 02 14 02 00 00 a0 40 02 04 02 01
```

| Bytes | Meaning |
|---|---|
| `50 53 46 31 07 0a 32 ... 38` | magic, underlying_iid 7, expiration `2026-12-18` |
| `02` | seq = 2: last committed seq for this stream is 1, so it is accepted |
| `80 84 cf 9a d3 9d f1 fa 31` | tick_time = 1 800 000 000 100 000 000 |
| `00` | delta |
| `02` | 2 sections |
| `02 02` | record 2 (`quote`), 2 rows |
| `03 28` | iid 3; mask 40 = bits 3, 5 |
| `02 09` | `bid`: d = −5; n = base 125 − 5 = 120 → **1.2** (base becomes 120) |
| `00` | `bid_size`: explicit null (base becomes 0) |
| `02 08 02 0a` | iid 3 + 2 = 5; mask bit 3; `bid`: d = +5; n = 5 + 5 = 10 → **0.1** |
| `05 02` | record 5 (`print`), 2 rows |
| `05 a0 40` | iid 5; mask 8224 = bits 5, 13 → `price`, `eth` |
| `02 14` | `price`: d = +10; no stored base for print iid 5, so base 0; n = 10 → **0.1** |
| `02 00` | `eth`: **false** |
| `00 a0 40` | gap 0 → iid 5 again; same mask |
| `02 04` | `price`: d = +2; base is the value of the previous row of this iid in this frame, 10; n = 12 → **0.12** |
| `02 01` | `eth`: **true** |

`ask` of quote iid 3 is absent in frame 2: its application value stays 1.3 and its base stays 130.

---

## 5. State and delta bases

A decoder keeps, per stream: the last committed `seq` (§7), and a table of **delta bases**. An application
usually also keeps the **folded rows** of the stream (§5.7).

### 5.1 Keyed and unkeyed records

A record is **keyed** if any field in its *received* descriptor has `"key": true`. Its key fields are its
dimensions: several rows with the same iid are told apart by the values of their key fields. A record with no key
fields is **unkeyed**: it has one logical row per iid.

In schema version 2:

| Records | Kind | Numeric tag-2 values |
|---|---|---|
| 1 contract, 2 quote, 3 trade, 4 oi, 5 print, 6 underlying_price, 7 option_analytics | unkeyed | deltas from a base |
| 8 term, 9 underlying_analytics, 10 flow, 11 exposure | keyed | absolute (base always 0) |

Keyed records never use bases, in snapshots or in deltas. Every numeric tag-2 value of a keyed record is
`n = 0 + d`, and a decoder MUST NOT store bases for them.

### 5.2 Base identity

For unkeyed records, a base is identified by **(stream, record ID, iid, field ID)**, where stream is
(`underlying_iid`, `expiration`). Rows sharing an iid within one frame share these bases (§5.4). Key fields do not
appear in base identity because keyed records have no bases.

A base is a signed integer: the canonical integer `n` last sent for that field (§4.8). It needs at least
129-bit-safe arithmetic: use 128-bit signed integers with overflow detection, or arbitrary-precision integers
with an explicit check that `n` stays in [−2^127, 2^127 − 1].

### 5.3 How each value sets the base (unkeyed records)

For every field present in a row's mask (every set bit, whether or not the application uses the field):

| Value received | New base for (stream, record, iid, field) |
|---|---|
| tag 2, numeric type (`i64`, `u64`, `time_ns`, `decimal`, `f64`) | `n` (the reconstructed canonical integer) |
| tag 0 (null) | 0 |
| tag 1 (literal float) | 0 |
| tag 2, non-numeric type (`enum`, `bool`, `text`, `date`) | 0 (no effect in practice: these types never read a base) |
| field absent from the mask | unchanged |

A base of 0 and "no base stored" are the same thing. When a stream has no base for a field (new iid, field
never sent, after a null or literal, after a snapshot that did not carry the field), the base is 0 and the next
tag-2 value is effectively absolute. **There is no "missing base" error**: a delta frame can introduce a new
iid, and its values decode against base 0.

### 5.4 Which base a value reads

For a numeric tag-2 value of field `f` in a row with iid `i` of an unkeyed record:

1. If the frame is a **snapshot**: base = 0.
2. Otherwise, if an earlier row **of the same run of rows with iid `i` in this section** (consecutive rows,
   joined by gap 0) carried field `f`: base = the new base that row produced (§5.3).
3. Otherwise: base = the committed base for (stream, record, `i`, `f`), or 0 if none.

Because a section is in non-decreasing iid order and a record appears in only one section per frame, rule 2
means "the latest value of this field earlier in this frame". The simplest correct implementation is a working
copy of the base table, updated value by value while decoding, and committed only when the whole frame is valid.
In a snapshot frame every value still sets the base (§5.3), but each value reads base 0, including repeated rows
of one iid.

### 5.5 Fields and records unknown to the application

Base handling follows the **received descriptor**, not the application's interest. For every unkeyed record
in the received schema, a decoder MUST update bases for every field present in the mask, including fields and
records the application ignores or does not know. Otherwise a later delta of that field decodes wrongly. For keyed
records nothing is stored, known or not. Unknown values MAY be dropped after decoding.

### 5.6 Absent versus null

- **Absent** (mask bit clear): the field did not change. The application keeps its previous value, and the
  base is kept.
- **Explicit null** (tag 0): the field now has no value. The application clears it (its value becomes null),
  and the base becomes 0.

A decoder MUST pass this distinction to the application: a row carries only its present fields, each either a
value or null.

### 5.7 Snapshots and folded state

A **snapshot** frame (`snapshot` = 1) replaces its stream's state. On successful decode of a snapshot:

- every base of that stream (all records, all iids) is discarded, then the snapshot's own values set new bases
  (§5.3). Fields not carried by the snapshot have base 0.
- the stream's folded rows are discarded and replaced by the snapshot's rows.
- the stream's last committed `seq` becomes the snapshot's `seq`.

Other streams are not affected. PSF1 has no row deletion: a row disappears only when a snapshot of its stream
does not contain it.

Application state is the **fold** of the decoded rows. The reference fold works like this:

- Row identity is (record ID, iid) for unkeyed records, and (record ID, iid, value of each key field in
  descriptor order) for keyed records. An explicit null key value is a value of its own. In the reference fold
  an absent key field counts the same as null.
- A decoded row's present fields overwrite the stored row's fields (a null overwrites with null). Absent fields
  keep their stored values.
- Producers send every key field of a keyed record in every row, as a value or an explicit null, changed or
  not, so the identity is always complete.

Records that are events rather than state (prints: several rows with one iid in one frame) fold to one row
per iid in this model. Applications that need every event should read rows from each decoded frame as well.

### 5.8 Dropping a stream

When the client unsubscribes a stream, it SHOULD discard that stream's bases, sequence and rows. The next
frame of that stream it accepts is then a snapshot (the server sends one on subscription).

---

## 6. Validation

A decoder MUST reject a frame in each case below. **A rejected frame changes nothing**: no base, no
sequence number, no folded row of any stream. Decode the whole frame into a scratch copy first, and commit
it only when the last byte has been consumed successfully.

Header:

1. Fewer than 4 bytes, or the first 4 bytes are not `PSF1`.
2. Any varint is truncated (input ends while the high bit is set), or reaches its 19th byte with a value above
   `0x03` (§3.1).
3. `underlying_iid` > 2^32 − 1.
4. `expiration` length exceeds the remaining bytes, or the bytes are not valid UTF-8.
5. `seq` > 2^64 − 1.
6. `tick_time` after zigzag decoding is outside [−2^63, 2^63 − 1].
7. The snapshot byte is missing or not `00`/`01`.
8. **Sequence:** the frame is a delta (`snapshot` = 0) and its stream has no committed frame, or its `seq` is not
   exactly the stream's last committed `seq` + 1 (so no delta can follow seq 2^64 − 1). The reference checks this
   right after the header, before the body. See §7 for telling this apart from a corrupt frame.
9. `section_count` is greater than the number of bytes remaining after it.

Sections and rows:

10. `record_id` > 65535, or not strictly greater than the previous section's `record_id`, or not a record of the
    received schema.
11. `row_count` is greater than (bytes remaining after it) ÷ 2, rounded down. (Every row takes at least 2 bytes.)
12. `iid_gap` > 2^32 − 1, or the running iid exceeds 2^32 − 1.
13. `mask` > 2^64 − 1; mask bit 0 is set; or a set bit names a field ID the received record descriptor lacks.

Values:

14. The tag byte is missing, or is not `00`, `01` or `02`.
15. Tag `01` on a field whose `wire_type` is not `f32` or `f64`; its 4 or 8 bytes are truncated; or the float is
    NaN or ±infinity.
16. Tag `02` on an `f32` field.
17. Numeric tag `02`: `base + d` overflows 128-bit signed; `u64` result outside [0, 2^64 − 1]; `i64`, `time_ns`
    or `decimal` result outside [−2^63, 2^63 − 1]; `f64` field with neither `quantum` nor `exact_increment`;
    `f64` result with |n| ≥ 2^61.
18. `text`/`date`: length exceeds the remaining bytes, or invalid UTF-8.
19. `enum`: index ≥ length of `enum_values`.
20. `bool`: payload byte missing or not `00`/`01`.

End:

21. Bytes remain after the last section (trailing bytes).

The reference decoder does **not** reject the following. A conforming decoder MUST accept them too, so it agrees
with the reference on every frame:

- a frame with zero sections, a section with zero rows, a row with mask 0;
- iid 0, and repeated iids (gap 0) in any record;
- non-minimal varints within 19 bytes;
- a snapshot with any `seq`, including one lower than or equal to the stream's last `seq` (§7);
- a delta that introduces an iid or field with no stored base (base 0, §5.3);
- a literal `f64` on a field that has a `quantum` or `exact_increment`;
- `expiration`, `date` and `text` values in any format (only UTF-8 validity is checked);
- a row of a keyed record that lacks some of its key fields (producers never send one; see §5.7 for how the
  reference fold identifies it).

---

## 7. Sequencing on the WebSocket

Each binary WebSocket message is exactly one PSF1 frame. Text messages are JSON control messages, described
in [`protocol.md`](protocol.md) §2.

- `seq` belongs to one stream. Each stream counts on its own and is contiguous: every delta is the previous
  frame's `seq` + 1.
- After `sub`, the first frame of each stream is a snapshot. A decoder accepts a snapshot whatever its `seq`. The
  snapshot's `seq` becomes the reference for the next delta. A snapshot can restart or lower the sequence (for
  example after the server fails over to another data source).
- A delta whose `seq` is not the last committed `seq` + 1, or a delta for a stream without a committed snapshot,
  is a **sequence break**. The decoder rejects it (§6, rule 8) and nothing changes. To tell a sequence break from
  a corrupt frame, parse the header alone (§4.2, it needs no state). If it parses, is a delta, and its `seq`
  is not the expected one, it is a sequence break. Otherwise the frame is malformed.
- On a sequence break, the client follows [`protocol.md`](protocol.md) §2: drop that stream's state, send
  `unsub` then `sub`, and wait for the new snapshot.
- When the server has to discard data a slow client did not read, it sends a `gap` text message for the stream,
  immediately followed by a recovery **snapshot** frame. The snapshot restores state. Mark the stream degraded
  until it arrives, and do not resubscribe because of a `gap` alone. The snapshot does not restore missing
  print history: the `gap` message names a time range to fetch over REST if you need every print.
- A new `hello` on the connection resets everything (§1.3).

---

## 8. Test vectors

[`psf1/vectors.json`](psf1/vectors.json) holds golden test vectors produced by the reference encoder and
checked against the reference decoder. Its format is described in [`psf1/README.md`](psf1/README.md). In outline:

- `schema_hello`: the `hello` message (with the schema message) that all vectors use.
- `cases[]`: sequences of frames to feed, in order, to **one** decoder built from `schema_hello`. Each
  `frames[]` entry has `hex` (the frame's bytes) and `expect` (the result: the decoded header and rows, or a
  rejection).
- `invalid[]`: frames a decoder must reject, each with the state it must still have afterwards.

To use them: build a fresh decoder for each case, feed each frame's `hex` bytes, and compare the result with
`expect`. That includes absent versus null fields, exact decimal coefficients, and `f64` values compared bit for
bit. For an invalid frame, check both that it is rejected and that the next valid frame of the case still
decodes correctly (proving state was unchanged). Read `psf1/README.md` for the exact field names and the way values
are written in `expect`.

---

## 9. Decoder checklist

1. Parse `hello.schema`. Index records by `id` and fields by (record `id`, field `id`). Note each record's key
   fields and whether it is keyed (§2, §5.1).
2. Implement the unsigned varint with the 19-byte / `0x03` limit and range checks on every use (§3.1).
3. Implement zigzag on 128-bit integers (§3.2), and strings with UTF-8 validation (§3.3).
4. Parse the header: magic, u32 iid, expiration string, u64 seq, i64 zigzag tick time, snapshot byte (§4.2).
5. Apply the sequence rule before touching state: a delta needs a committed snapshot and `seq` = last + 1 (§7).
6. Read sections: strictly increasing known record IDs, row-count bound, iid gaps restarting at 0 per
   section, with u32 overflow check (§4.3–4.4).
7. Read the u64 mask. Reject bit 0 and bits without a descriptor. Read values in increasing field-ID order (§4.5–4.6).
8. Decode tags 0/1/2 per `wire_type`, with every range check (§4.7–4.8, §6).
9. Compute `n = base + d` with the base rules: 0 for keyed records and snapshots, else the in-frame latest
   value for the iid, else the committed base, else 0 (§5.4).
10. Rebuild `f64` as `float(n) / (1.0 / q)` with `quantum` preferred over `exact_increment`. Keep decimals exact (§4.8).
11. Update bases for every present field of unkeyed records (known or not): `n` for numeric tag 2, otherwise 0.
    Store nothing for keyed records (§5.3, §5.5).
12. Reject trailing bytes. Commit bases, sequence and folded rows only after the whole frame is valid (§6).
13. On a snapshot, discard the stream's bases and rows before committing the snapshot's (§5.7).
14. Deliver rows with absent and null kept distinct. Fold by (record, iid, key fields) (§5.6–5.7).
15. Discard all state on a new `hello`, and a stream's state on `unsub` or a sequence break (§1.3, §5.8, §7).
16. Run every case in `psf1/vectors.json` (§8).
