@rbxts/netweave 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1353 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Ir
6
+
7
+ Lowers a schema to a node tree annotated with everything the compiler needs to know *before*
8
+ it sees a value: how many bytes a subtree always takes, which flag bits it owns, and what
9
+ shape its result table has.
10
+
11
+ This pass is the reason netweave is not ByteNet with different names. ByteNet builds closures
12
+ straight from the schema, so a closure can never see its siblings — it cannot know that six
13
+ `u8` fields are six contiguous bytes, or that four booleans share one. Lowering first creates
14
+ the window in which those facts exist.
15
+
16
+ Internal. Schemas and channels are the public surface.
17
+ ]=]
18
+
19
+ --[[
20
+ Three facts, computed once at definition time, each paying for a different competitor's
21
+ weakness:
22
+
23
+ `fixedSize` a statically sized packet needs no length prefix, so the framing guarantee
24
+ costs it nothing (`docs/WIRE-FORMAT.md` §2), and one bounds check covers a
25
+ whole run rather than one per field.
26
+ `bits` booleans, optional presence and small enum tags share a bitfield. Blink spends
27
+ a byte on each unless the author reaches for `set` (`RESEARCH §3.9-AA`).
28
+ `template` a pre-sized table for `table.clone`, so decode never rehashes. ByteNet does
29
+ this and it is the one axis where it beat both code generators in M0
30
+ (389 B/packet against 641 and 1474).
31
+ ]]
32
+
33
+ local Types = require("../types")
34
+
35
+ type Descriptor = Types.Descriptor
36
+ type Encoding = Types.Encoding
37
+
38
+ local Ir = {}
39
+
40
+ local MAX_CHUNK_BITS = 32
41
+ local CHUNK_WIDTHS = { 4, 2, 1 }
42
+
43
+ --[[ Keyed by `Encoding` rather than `string`, so `ENCODING_SIZE[node.storage]` is `number?` and a
44
+ ninth encoding added to `Types.Encoding` and not to this table is a diagnostic rather than a
45
+ runtime nil (M4 report finding 47; `CLAUDE.md` §9, the hand-kept list). ]]
46
+ local ENCODING_SIZE: { [Encoding]: number } = {
47
+ u8 = 1,
48
+ u16 = 2,
49
+ u32 = 4,
50
+ i8 = 1,
51
+ i16 = 2,
52
+ i32 = 4,
53
+ f32 = 4,
54
+ f64 = 8,
55
+ }
56
+
57
+ --[=[
58
+ @interface Chunk
59
+ @within Ir
60
+ .width number -- 1, 2 or 4 bytes
61
+ .capacity number -- bits this chunk holds
62
+ .offset number -- byte offset within the bitfield
63
+
64
+ One integer of a bitfield. A bitfield is a list of these rather than a single value because
65
+ there is no 24-bit write: 17 bits is three bytes as `u16 + u8`, and four bytes as `u32`.
66
+ ]=]
67
+ export type Chunk = {
68
+ width: number,
69
+ capacity: number,
70
+ offset: number,
71
+ }
72
+
73
+ --[=[
74
+ @interface Scope
75
+ @within Ir
76
+ .bits number -- total flags in this scope
77
+ .bytes number -- what those flags cost, `ceil(bits / 8)`
78
+ .chunks { Chunk }
79
+
80
+ A bitfield. Opened at the root of a payload and at each element of a dynamic array or map,
81
+ because those are the only places where the number of flags is not known until runtime.
82
+
83
+ A struct does **not** open one: its flags fold into the enclosing scope, so twelve booleans
84
+ nested one struct deep still cost twelve bits rather than a fresh byte.
85
+ ]=]
86
+ export type Scope = {
87
+ bits: number,
88
+ bytes: number,
89
+ chunks: { Chunk },
90
+ }
91
+
92
+ --[=[
93
+ @interface Field
94
+ @within Ir
95
+ .name string
96
+ .node Node
97
+ ]=]
98
+ export type Field = {
99
+ name: string,
100
+ node: Node,
101
+ }
102
+
103
+ --[=[
104
+ @interface Node
105
+ @within Ir
106
+ .kind Kind
107
+ .bits number -- flag bits contributed to the enclosing bitfield
108
+ .fixedSize number? -- bytes always consumed, or nil when it depends on the data
109
+ .instances number? -- instances always consumed, or nil when it depends on the data
110
+ .storage Encoding? -- the narrowed encoding a number is actually written at
111
+ .offset number? -- subtracted before writing, added back on read
112
+ .step number? -- the size of one wire level, when the number is quantised
113
+ .whole boolean? -- whether a number must be an integer, asked on both sides
114
+ .utf8 boolean? -- `string`: the bytes must decode as UTF-8
115
+ .pattern string? -- `string`: a Lua pattern the whole value must match
116
+ .min number? -- a value bound for numbers, a length bound for strings, arrays and maps
117
+ .max number? -- the same, and what the decoder rejects against
118
+ .unit boolean?
119
+ .class string?
120
+ .descendantOf Instance? -- `instance`: the container an arrival must be inside, checked on receive
121
+ .lengthStorage Encoding? -- how a variable length is written; nil when the length is fixed
122
+ .lengthOffset number?
123
+ .count number? -- exact length, when the schema fixed one
124
+ .variants { string }?
125
+ .literal (string | boolean | number)? -- `literal`: the one value; nothing on the wire
126
+ .default (string | boolean | number)? -- `optional`: read where the bit is clear, and never written
127
+ .lookup { [string]: number }? -- variant name to wire index
128
+ .inner Node?
129
+ .element Node?
130
+ .elements { Node }? -- one per position, when an exact-length array's element carries flags
131
+ .key Node?
132
+ .value Node?
133
+ .fields { Field }?
134
+ .branches { Field }? -- `union`: one per branch, in wire order
135
+ .template { [string]: boolean }? -- cloned on decode so the result table never rehashes
136
+ .chunkIndex number? -- which bitfield chunk this node's flag lives in
137
+ .mask number? -- its bit within that chunk
138
+ .tagChunks { number }? -- an enum's tag bits may straddle a chunk boundary
139
+ .tagMasks { number }?
140
+ .scope Scope? -- set when this node opens a bitfield of its own
141
+ ]=]
142
+ export type Node = {
143
+ kind: Types.Kind,
144
+ bits: number,
145
+ fixedSize: number?,
146
+ instances: number?,
147
+ storage: Encoding?,
148
+ offset: number?,
149
+ step: number?,
150
+ whole: boolean?,
151
+ utf8: boolean?,
152
+ pattern: string?,
153
+ min: number?,
154
+ max: number?,
155
+ unit: boolean?,
156
+ class: string?,
157
+ descendantOf: Instance?,
158
+ lengthStorage: Encoding?,
159
+ lengthOffset: number?,
160
+ count: number?,
161
+ variants: { string }?,
162
+ literal: (string | boolean | number)?,
163
+ default: (string | boolean | number)?,
164
+ lookup: { [string]: number }?,
165
+ inner: Node?,
166
+ element: Node?,
167
+ elements: { Node }?,
168
+ key: Node?,
169
+ value: Node?,
170
+ fields: { Field }?,
171
+ branches: { Field }?,
172
+ template: { [string]: boolean }?,
173
+ chunkIndex: number?,
174
+ mask: number?,
175
+ tagChunks: { number }?,
176
+ tagMasks: { number }?,
177
+ scope: Scope?,
178
+ }
179
+
180
+ --[=[
181
+ @interface Layout
182
+ @within Ir
183
+ .root Node
184
+ .scope Scope? -- the payload's own bitfield, if it has any flags
185
+ .fixedSize number? -- total payload bytes, or nil when it varies
186
+ .maxSize number -- the most bytes a payload can ever occupy; always known
187
+ .framing "static" | "counted"
188
+
189
+ Everything a channel needs to encode and decode one payload.
190
+ ]=]
191
+ export type Layout = {
192
+ root: Node,
193
+ scope: Scope?,
194
+ fixedSize: number?,
195
+ maxSize: number,
196
+ instances: number?,
197
+ framing: "static" | "counted",
198
+ }
199
+
200
+ --[[ Smallest number of bits that can index `count` distinct values. One variant needs none. ]]
201
+ local function bitsToIndex(count: number): number
202
+ local bits = 0
203
+ local capacity = 1
204
+
205
+ while capacity < count do
206
+ capacity *= 2
207
+ bits += 1
208
+ end
209
+
210
+ return bits
211
+ end
212
+
213
+ --[[
214
+ Smallest unsigned encoding holding `span`. Signed ranges never reach the wire as signed: the
215
+ lower bound is subtracted first, so `i16(-100, 100)` travels as a single unsigned byte.
216
+ ]]
217
+ local function storageFor(span: number): Encoding
218
+ if span <= 255 then
219
+ return "u8"
220
+ elseif span <= 65535 then
221
+ return "u16"
222
+ end
223
+
224
+ return "u32"
225
+ end
226
+
227
+ --[[
228
+ `table.create` yields `{unknown}` and Luau arrays are invariant, so pre-sizing a typed array
229
+ needs a cast. Returning `any` keeps the cast in one place: the new solver will not push a
230
+ call site's expected type into a generic return (`spike/inference/README.md`).
231
+ ]]
232
+ local function sized(count: number): any
233
+ return table.create(count)
234
+ end
235
+
236
+ --[[ Any unknown makes the sum unknown. ]]
237
+ local function addSize(a: number?, b: number?): number?
238
+ if a == nil or b == nil then
239
+ return nil
240
+ end
241
+
242
+ return a + b
243
+ end
244
+
245
+ --[=[
246
+ @within Ir
247
+ @function bitChunks
248
+ @param bits number
249
+ @return { Chunk }
250
+
251
+ Splits `bits` flags into the fewest bytes that hold them, `ceil(bits / 8)`, by taking the
252
+ widest chunk that fits the remaining bytes.
253
+
254
+ 17 bits becomes `u16 + u8`, three bytes. A single `u32` would also be legal and would waste
255
+ one. Zap caps its accumulators at 16 bits and reaches the same total; the cap is not what
256
+ matters, the byte count is (`docs/WIRE-FORMAT.md` §5).
257
+ ]=]
258
+ function Ir.bitChunks(bits: number): { Chunk }
259
+ local chunks: { Chunk } = {}
260
+
261
+ if bits <= 0 then
262
+ return chunks
263
+ end
264
+
265
+ local remainingBytes = math.ceil(bits / 8)
266
+ local offset = 0
267
+ local assigned = 0
268
+
269
+ while remainingBytes > 0 do
270
+ local width = 1
271
+
272
+ for _, candidate in CHUNK_WIDTHS do
273
+ if candidate <= remainingBytes then
274
+ width = candidate
275
+ break
276
+ end
277
+ end
278
+
279
+ local capacity = math.min(width * 8, MAX_CHUNK_BITS, bits - assigned)
280
+
281
+ table.insert(chunks, {
282
+ width = width,
283
+ capacity = capacity,
284
+ offset = offset,
285
+ })
286
+
287
+ assigned += capacity
288
+ offset += width
289
+ remainingBytes -= width
290
+ end
291
+
292
+ return chunks
293
+ end
294
+
295
+ --[=[
296
+ @within Ir
297
+ @function lengthSize
298
+ @param node Node
299
+ @return number -- bytes the length prefix costs, zero when the length is fixed
300
+ ]=]
301
+ function Ir.lengthSize(node: Node): number
302
+ local storage = node.lengthStorage
303
+ return if storage then ENCODING_SIZE[storage] else 0
304
+ end
305
+
306
+ local function makeScope(bits: number): Scope
307
+ return {
308
+ bits = bits,
309
+ bytes = math.ceil(bits / 8),
310
+ chunks = Ir.bitChunks(bits),
311
+ }
312
+ end
313
+
314
+ local lower: (descriptor: Descriptor) -> Node
315
+
316
+ local function lowerNumber(descriptor: Descriptor): Node
317
+ local min = descriptor.min :: number
318
+ local max = descriptor.max :: number
319
+ local step = (descriptor :: any).step
320
+
321
+ --[[
322
+ A quantised number is an integer count of steps, so it lowers to whichever unsigned encoding
323
+ holds the count — which is the whole point: it is the only range on a fractional value that
324
+ narrows the storage, because it says how much precision the author actually needs rather than
325
+ how large the number gets.
326
+
327
+ `max` is the reconstructed top rather than the declared one. `t.quantized` already refuses a
328
+ range that is not a whole number of steps, so the two agree to within a rounding of the
329
+ division — and `levels * step + min` is what the *reader* will produce at the top level, so
330
+ comparing it against anything smaller would refuse the schema's own maximum. That is the f32
331
+ bound incident (`Serdes.numberReader`) in a second encoding, avoided by deriving the bound
332
+ from the arithmetic that produces the value rather than from the declaration.
333
+ ]]
334
+ if step then
335
+ local levels = math.floor((max - min) / step + 0.5)
336
+ local storage = storageFor(levels)
337
+
338
+ return {
339
+ kind = "number",
340
+ bits = 0,
341
+ fixedSize = ENCODING_SIZE[storage],
342
+ instances = 0,
343
+ storage = storage,
344
+ offset = min,
345
+ step = step,
346
+ min = min,
347
+ max = math.max(max, min + levels * step),
348
+ whole = false,
349
+ }
350
+ end
351
+
352
+ local encoding = descriptor.encoding :: Encoding
353
+
354
+ --[[
355
+ Floats are validated against the range but never re-encoded. Subtracting a lower bound from
356
+ a float and storing it narrower changes which values are representable, which is a
357
+ different promise than the schema made.
358
+ ]]
359
+ if encoding == "f32" or encoding == "f64" then
360
+ return {
361
+ kind = "number",
362
+ bits = 0,
363
+ fixedSize = ENCODING_SIZE[encoding],
364
+ instances = 0,
365
+ storage = encoding,
366
+ offset = 0,
367
+ min = min,
368
+ max = max,
369
+ whole = false,
370
+ }
371
+ end
372
+
373
+ --[[
374
+ **A whole number wider than four bytes.**
375
+
376
+ `u53` and `i53` are the only declared encodings with no storage of their own: a range that
377
+ fits an unsigned 32-bit span narrows exactly like `u32` does, and one that does not is
378
+ carried in an `f64`, where every integer up to 2^53 is exact. That is what makes a `UserId`
379
+ or a millisecond timestamp declarable — until M4 phase 8 the widest integer was `u32` and the
380
+ only thing that reached further was `t.f64`, which is a float and was checked for wholeness
381
+ by the *writer* alone (M4 report).
382
+
383
+ `offset` is zero on the wide path and it has to be. `value - min` for `t.i53` spans 2^54, and
384
+ an odd integer above 2^53 is not representable as a double — so subtracting the bound would
385
+ round the very values this exists to carry. It is subtracted only when the span is small
386
+ enough for a narrower storage, where it is exact by construction.
387
+ ]]
388
+ local wide = encoding == "u53" or encoding == "i53"
389
+ local span = max - min
390
+
391
+ if wide and span > 4294967295 then
392
+ return {
393
+ kind = "number",
394
+ bits = 0,
395
+ fixedSize = ENCODING_SIZE.f64,
396
+ instances = 0,
397
+ storage = "f64",
398
+ offset = 0,
399
+ min = min,
400
+ max = max,
401
+ whole = true,
402
+ }
403
+ end
404
+
405
+ local storage = storageFor(span)
406
+
407
+ return {
408
+ kind = "number",
409
+ bits = 0,
410
+ fixedSize = ENCODING_SIZE[storage],
411
+ instances = 0,
412
+ storage = storage,
413
+ offset = min,
414
+ min = min,
415
+ max = max,
416
+ whole = true,
417
+ }
418
+ end
419
+
420
+ --[[
421
+ Length prefixes narrow the same way values do: `t.array(e, 10, 20)` writes `count - 10` in one
422
+ byte. An exact length has no prefix at all, which is what makes `t.array(entity, 100)` a
423
+ statically sized packet.
424
+ ]]
425
+ local function lowerLength(node: Node, min: number, max: number)
426
+ --[[
427
+ The bounds are carried onto the node, not just consumed here, because the decoder needs
428
+ them: a narrowed prefix admits values the schema forbids. `t.array(e, 0, 200)` writes its
429
+ count in one byte, and a byte holds 255 — so a hostile sender can claim 255 elements
430
+ against a schema that allows 200. The reader rejects that, and it can only do so if the
431
+ limit survived lowering.
432
+ ]]
433
+ node.min = min
434
+ node.max = max
435
+
436
+ if min == max then
437
+ node.count = min
438
+ return
439
+ end
440
+
441
+ node.lengthStorage = storageFor(max - min)
442
+ node.lengthOffset = min
443
+ end
444
+
445
+ local function lowerStruct(descriptor: Descriptor): Node
446
+ local order = descriptor.order :: { string }
447
+ local source = descriptor.fields :: { [string]: Descriptor }
448
+
449
+ local fields: { Field } = sized(#order)
450
+ local template: { [string]: boolean } = {}
451
+
452
+ local bits = 0
453
+ local fixedSize: number? = 0
454
+ local instances: number? = 0
455
+
456
+ for index, name in order do
457
+ local child = lower(source[name])
458
+
459
+ fields[index] = { name = name, node = child }
460
+ template[name] = false
461
+
462
+ bits += child.bits
463
+ fixedSize = addSize(fixedSize, child.fixedSize)
464
+ instances = addSize(instances, child.instances)
465
+ end
466
+
467
+ return {
468
+ kind = "struct",
469
+ bits = bits,
470
+ fixedSize = fixedSize,
471
+ instances = instances,
472
+ fields = fields,
473
+ --[[ Frozen so nothing mutates the shared template. `table.clone` of a frozen table returns
474
+ a mutable copy, which is the intent. ]]
475
+ template = table.freeze(template),
476
+ }
477
+ end
478
+
479
+ --[[
480
+ **A repeated thing that costs nothing is a count, and it has to be refused where it is written.**
481
+
482
+ `PLAN-M3` D-4 bounded a claimed length against the bytes remaining, and the comment under that
483
+ bound says "an element cannot be conjured from no bytes". That is the assumption this check
484
+ exists for, because there are elements that can:
485
+
486
+ * `t.enum({ only = true })` — one variant, `bitsToIndex(1)` is zero bits
487
+ * `t.string(0, 0)` and `t.buffer(0, 0)` — a length of exactly zero, so no prefix and no bytes
488
+ * a `t.struct` whose every field is one of those
489
+
490
+ Measured before this check existed, with two bytes on the wire and no bound in sight:
491
+
492
+ | schema | claimed | result |
493
+ |---|---|---|
494
+ | `t.array(t.u8)` | 65,535 | refused, 0.00 ms — the D-4 bound holds |
495
+ | `t.array(t.enum({ x = true }))` | 65,535 | **accepted**, 65,535 entries, 1.7 ms, +1,024 KB |
496
+ | `t.array(t.buffer(0, 0))` | 65,535 | **accepted**, 7.3 ms, +2,048 KB |
497
+ | `t.array(t.struct({ e = t.enum({ x = true }) }))` | 65,535 | **accepted**, 6.8 ms, +6,144 KB |
498
+
499
+ **No receive-side rule can fix it**, and that is the whole argument for refusing the declaration.
500
+ For an element that costs nothing the honest packet and the flood are the *same bytes*: a length
501
+ and nothing else. Capping the count by the bytes remaining would cap an honest decode to zero,
502
+ because an honest one has no payload either. The only thing that separates them is a schema
503
+ author saying how many there can be, and a schema that repeats a value carrying no information
504
+ is not saying anything a number would not say better.
505
+
506
+ Exact-length arrays are left alone: `t.array(E, 4, 4)` writes no length at all, so there is
507
+ nothing for a peer to claim.
508
+ ]]
509
+ local function carriesNothing(node: Node): boolean
510
+ return node.bits == 0 and node.fixedSize == 0 and (node.instances or 0) == 0
511
+ end
512
+
513
+ local function lowerArray(descriptor: Descriptor): Node
514
+ local elementDescriptor = descriptor.element :: Descriptor
515
+ local element = lower(elementDescriptor)
516
+
517
+ if descriptor.min ~= descriptor.max and carriesNothing(element) then
518
+ error(
519
+ `t.array was given an element that costs no bytes, no flags and no instances, so the `
520
+ .. `array carries only its own length — and a peer claiming 65535 of them builds `
521
+ .. `65535 entries out of two bytes, which an honest packet cannot be told apart `
522
+ .. `from. Send the count itself (t.u16), or give the element something to carry: a `
523
+ .. `single-variant t.enum, t.string(0, 0) and t.buffer(0, 0) are all zero bytes on `
524
+ .. `the wire.`
525
+ )
526
+ end
527
+
528
+ local node: Node = {
529
+ kind = "array",
530
+ bits = 0,
531
+ element = element,
532
+ }
533
+
534
+ lowerLength(node, descriptor.min :: number, descriptor.max :: number)
535
+
536
+ local count = node.count
537
+
538
+ if count then
539
+ --[[
540
+ An exact length unrolls: the element's flags repeat a known number of times, so they
541
+ fold into the enclosing bitfield rather than costing a byte each. This is how
542
+ `boolean[8]` becomes one byte.
543
+ ]]
544
+ node.bits = element.bits * count
545
+ node.fixedSize = if element.fixedSize then element.fixedSize * count else nil
546
+ node.instances = if element.instances then element.instances * count else nil
547
+
548
+ if element.bits > 0 then
549
+ --[[
550
+ Each position needs its own bit slots, and a node holds exactly one slot, so the
551
+ element is lowered once per position. Only arrays whose element carries flags pay
552
+ this — `Entity[100]` of plain numbers keeps a single shared node.
553
+ ]]
554
+ local elements: { Node } = sized(count)
555
+ elements[1] = element
556
+
557
+ for index = 2, count do
558
+ elements[index] = lower(elementDescriptor)
559
+ end
560
+
561
+ node.elements = elements
562
+ end
563
+ else
564
+ --[[
565
+ A count that varies leaves the byte size unknown, but not always the instance count: an
566
+ element that carries no instances carries none however many times it repeats. Saying nil
567
+ here instead would put an always-zero varint in every such packet's frame, which is a byte
568
+ on the wire for information the schema already has (`docs/WIRE-FORMAT.md` §2).
569
+ ]]
570
+ node.instances = if element.instances == 0 then 0 else nil
571
+
572
+ if element.bits > 0 then
573
+ --[[
574
+ A dynamic array cannot fold its elements' flags into the enclosing scope, because the
575
+ count is not known until runtime. Each element opens a scope of its own, so `boolean[]`
576
+ costs a byte per element. Zap has the same limitation; carrying flags across elements
577
+ is possible and deferred (`RESEARCH §3.8-P`).
578
+ ]]
579
+ element.scope = makeScope(element.bits)
580
+ end
581
+ end
582
+
583
+ return node
584
+ end
585
+
586
+ local function lowerMap(descriptor: Descriptor): Node
587
+ local key = lower(descriptor.key :: Descriptor)
588
+ local value = lower(descriptor.value :: Descriptor)
589
+
590
+ --[[ The same hazard as a dynamic array, over key and value together. A map is always dynamic, so
591
+ there is no exact-length case to exempt. ]]
592
+ if carriesNothing(key) and carriesNothing(value) then
593
+ error(
594
+ `t.map was given a key and a value that together cost no bytes, no flags and no `
595
+ .. `instances, so the map carries only its own length — and a peer claiming 65535 `
596
+ .. `entries builds them out of two bytes. A key that costs nothing can only ever `
597
+ .. `name one entry anyway; give the key something to distinguish entries by.`
598
+ )
599
+ end
600
+
601
+ if key.bits > 0 then
602
+ key.scope = makeScope(key.bits)
603
+ end
604
+
605
+ if value.bits > 0 then
606
+ value.scope = makeScope(value.bits)
607
+ end
608
+
609
+ local node: Node = {
610
+ kind = "map",
611
+ bits = 0,
612
+ key = key,
613
+ value = value,
614
+
615
+ --[[ Same derivation as a dynamic array: entries that carry no instances carry none however
616
+ many there are, and saying nil would put an always-zero varint in the frame. ]]
617
+ instances = if key.instances == 0 and value.instances == 0 then 0 else nil,
618
+ }
619
+
620
+ lowerLength(node, descriptor.min :: number, descriptor.max :: number)
621
+ return node
622
+ end
623
+
624
+ function lower(descriptor: Descriptor): Node
625
+ local kind = descriptor.kind
626
+
627
+ if kind == "boolean" then
628
+ return { kind = kind, bits = 1, fixedSize = 0, instances = 0 }
629
+ elseif kind == "number" then
630
+ return lowerNumber(descriptor)
631
+ elseif kind == "string" or kind == "buffer" then
632
+ local node: Node = { kind = kind, bits = 0, instances = 0 }
633
+ lowerLength(node, descriptor.min :: number, descriptor.max :: number)
634
+ node.fixedSize = node.count
635
+
636
+ --[[ Carried through rather than derived: what a string is *allowed to say* is not a property
637
+ of its length, and the codec is where it has to be asked. `buffer` never has them —
638
+ `t.buffer` is opaque bytes by definition — but the two share this branch and copying nil
639
+ costs nothing. ]]
640
+ node.utf8 = (descriptor :: any).utf8
641
+ node.pattern = (descriptor :: any).pattern
642
+
643
+ return node
644
+ elseif kind == "vector2" or kind == "vector3" then
645
+ --[[
646
+ A vector is its component schema, `axes` times over. Bare that is `f32` and the old fixed
647
+ widths; named, everything a number node knows applies per component — a narrowed range
648
+ takes a smaller storage, a declared minimum is subtracted, a quantisation step divides.
649
+
650
+ The component is lowered as a node and carried on `element`, which is what `cloneNode`
651
+ copies, `Protocol.describe` walks and `Serdes` builds a writer from. Nothing about a
652
+ vector needs its own machinery once the component is a node.
653
+ ]]
654
+ local axes = if kind == "vector2" then 2 else 3
655
+ local component = descriptor.element
656
+
657
+ if component then
658
+ local element = lower(component)
659
+
660
+ return {
661
+ kind = kind,
662
+ bits = 0,
663
+ fixedSize = (element.fixedSize :: number) * axes,
664
+ instances = 0,
665
+ unit = descriptor.unit,
666
+ element = element,
667
+ }
668
+ end
669
+
670
+ return { kind = kind, bits = 0, fixedSize = 4 * axes, instances = 0, unit = descriptor.unit }
671
+ elseif kind == "color3" then
672
+ return { kind = kind, bits = 0, fixedSize = 3, instances = 0 }
673
+ elseif kind == "cframe" then
674
+ local component = descriptor.element
675
+
676
+ if component then
677
+ --[[
678
+ The position as three of the component, like a vector; the rotation as a quaternion
679
+ with its largest component dropped — three `i16` and a two-bit index saying which,
680
+ in the enclosing bitfield where an enum's tag would go. Seven bytes of rotation
681
+ become six and two bits, against the twelve of the axis-angle vector below
682
+ (`PLAN-M5` phase 5; the M4 report's "compact cframe" row).
683
+ ]]
684
+ local element = lower(component)
685
+
686
+ return {
687
+ kind = kind,
688
+ bits = 2,
689
+ fixedSize = (element.fixedSize :: number) * 3 + 6,
690
+ instances = 0,
691
+ element = element,
692
+ }
693
+ end
694
+
695
+ --[[
696
+ Position plus an axis-angle vector. Zap keeps a table of 24 common rotations and spends
697
+ one byte when a CFrame matches one; the componented form above is the compact spelling.
698
+ ]]
699
+ return { kind = kind, bits = 0, fixedSize = 24, instances = 0 }
700
+ elseif kind == "instance" then
701
+ return {
702
+ kind = kind,
703
+ bits = 0,
704
+ fixedSize = 0,
705
+ instances = 1,
706
+ class = descriptor.class,
707
+ descendantOf = descriptor.descendantOf,
708
+ }
709
+ elseif kind == "enum" then
710
+ local variants = descriptor.variants :: { string }
711
+ local lookup: { [string]: number } = {}
712
+
713
+ for index, name in variants do
714
+ lookup[name] = index
715
+ end
716
+
717
+ return {
718
+ kind = kind,
719
+ bits = bitsToIndex(#variants),
720
+ fixedSize = 0,
721
+ instances = 0,
722
+ variants = variants,
723
+ lookup = lookup,
724
+ }
725
+ elseif kind == "literal" then
726
+ --[[ Nothing on the wire: the value is in both peers' declarations, and the signature
727
+ carries it so the two agree on which. ]]
728
+ return { kind = kind, bits = 0, fixedSize = 0, instances = 0, literal = descriptor.literal }
729
+ elseif kind == "union" then
730
+ --[[
731
+ A tag, and then whichever branch it names.
732
+
733
+ **The branches fork the bit budget rather than summing it.** Only one branch is ever
734
+ present, so its flags may occupy the same bits another branch's would — `assignBits`
735
+ numbers every branch from the same base and the node reserves the widest. A union of two
736
+ structs each carrying three flags is `1 + 3` bits, not `1 + 6`. Zap sums, so its variants
737
+ consume separate bits even though only one can be there (`RESEARCH §3.9-Y`,
738
+ `WIRE-FORMAT.md` §5).
739
+
740
+ Bytes cannot fork the same way, because a byte offset is a position in a run rather than
741
+ a slot in a bitfield. So `fixedSize` survives only when every branch agrees on it — which
742
+ is a real case (`t.union({ a = t.u16, b = t.i16 })` is two bytes whichever arrives) and
743
+ not the common one.
744
+ ]]
745
+ local variants = descriptor.variants :: { string }
746
+ local source = descriptor.branches :: { [string]: Descriptor }
747
+
748
+ local lookup: { [string]: number } = {}
749
+ local branches: { Field } = sized(#variants)
750
+
751
+ local widest = 0
752
+ local fixedSize: number? = nil
753
+ local instances: number? = nil
754
+ local sameSize = true
755
+ local sameInstances = true
756
+
757
+ for index, name in variants do
758
+ local branch = lower(source[name])
759
+
760
+ lookup[name] = index
761
+ branches[index] = { name = name, node = branch }
762
+
763
+ if branch.bits > widest then
764
+ widest = branch.bits
765
+ end
766
+
767
+ if index == 1 then
768
+ fixedSize = branch.fixedSize
769
+ instances = branch.instances
770
+ else
771
+ if fixedSize ~= branch.fixedSize then
772
+ sameSize = false
773
+ end
774
+
775
+ if instances ~= branch.instances then
776
+ sameInstances = false
777
+ end
778
+ end
779
+ end
780
+
781
+ return {
782
+ kind = kind,
783
+ bits = bitsToIndex(#variants) + widest,
784
+ fixedSize = if sameSize then fixedSize else nil,
785
+ instances = if sameInstances then instances else nil,
786
+ variants = variants,
787
+ lookup = lookup,
788
+ branches = branches,
789
+ }
790
+ elseif kind == "optional" then
791
+ local inner = lower(descriptor.inner :: Descriptor)
792
+
793
+ --[[
794
+ Presence is one bit, and the inner value's own flags are reserved whether or not it is
795
+ present. That is what makes `optional(boolean)` cost two bits and no bytes, and
796
+ therefore keeps a struct of them statically sized.
797
+ ]]
798
+ return {
799
+ kind = kind,
800
+ bits = 1 + inner.bits,
801
+ fixedSize = if inner.fixedSize == 0 then 0 else nil,
802
+ instances = if inner.instances == 0 then 0 else nil,
803
+ inner = inner,
804
+ default = descriptor.default,
805
+ }
806
+ elseif kind == "array" then
807
+ return lowerArray(descriptor)
808
+ elseif kind == "map" then
809
+ return lowerMap(descriptor)
810
+ elseif kind == "struct" then
811
+ return lowerStruct(descriptor)
812
+ end
813
+
814
+ error(`[netweave] cannot lower a "{kind}"`)
815
+ end
816
+
817
+ --[[ Locates bit `index` of a scope: which chunk holds it, and its mask within that chunk. ]]
818
+ local function locate(scope: Scope, index: number): (number, number)
819
+ local remaining = index
820
+
821
+ for chunkIndex, chunk in scope.chunks do
822
+ if remaining < chunk.capacity then
823
+ return chunkIndex, bit32.lshift(1, remaining)
824
+ end
825
+
826
+ remaining -= chunk.capacity
827
+ end
828
+
829
+ error(`[netweave] bit {index} is outside a {scope.bits}-bit scope`)
830
+ end
831
+
832
+ --[[
833
+ Hands out bit positions within one scope, depth first, in the order the encoder will visit
834
+ them. Assignment is per *occurrence*: the same `entity` schema used in two channels gets two
835
+ independent sets of slots, which is why lowering never shares nodes between parents.
836
+ ]]
837
+ local function assignBits(node: Node, scope: Scope, next: number): number
838
+ local kind = node.kind
839
+
840
+ if kind == "boolean" then
841
+ node.chunkIndex, node.mask = locate(scope, next)
842
+ return next + 1
843
+ elseif kind == "enum" or kind == "cframe" then
844
+ --[[ A compact cframe's two index bits live where an enum's tag does. ]]
845
+ local chunks: { number } = sized(node.bits)
846
+ local masks: { number } = sized(node.bits)
847
+
848
+ for index = 1, node.bits do
849
+ chunks[index], masks[index] = locate(scope, next)
850
+ next += 1
851
+ end
852
+
853
+ node.tagChunks = chunks
854
+ node.tagMasks = masks
855
+ return next
856
+ elseif kind == "union" then
857
+ local variants = node.variants :: { string }
858
+ local tagBits = bitsToIndex(#variants)
859
+
860
+ local chunks: { number } = sized(tagBits)
861
+ local masks: { number } = sized(tagBits)
862
+
863
+ for index = 1, tagBits do
864
+ chunks[index], masks[index] = locate(scope, next)
865
+ next += 1
866
+ end
867
+
868
+ node.tagChunks = chunks
869
+ node.tagMasks = masks
870
+
871
+ --[[
872
+ **Every branch numbered from the same slot**, which is the fork `lowerNumber`'s sibling
873
+ above reserved room for. Only one branch is ever present, so branch A's first flag and
874
+ branch B's first flag are the same bit — and the node returns the widest of them so the
875
+ enclosing scope carries on after the longest branch rather than after the last one.
876
+
877
+ A branch with no flags is skipped for the same reason a field with none is: `assignBits`
878
+ has nothing to number and would return `base` anyway.
879
+ ]]
880
+ local base = next
881
+ local widest = base
882
+
883
+ for _, branch in node.branches :: { Field } do
884
+ if branch.node.bits > 0 then
885
+ local after = assignBits(branch.node, scope, base)
886
+
887
+ if after > widest then
888
+ widest = after
889
+ end
890
+ end
891
+ end
892
+
893
+ return widest
894
+ elseif kind == "optional" then
895
+ node.chunkIndex, node.mask = locate(scope, next)
896
+ next += 1
897
+
898
+ local inner = node.inner :: Node
899
+ if inner.bits > 0 then
900
+ next = assignBits(inner, scope, next)
901
+ end
902
+
903
+ return next
904
+ elseif kind == "struct" then
905
+ for _, field in node.fields :: { Field } do
906
+ if field.node.bits > 0 then
907
+ next = assignBits(field.node, scope, next)
908
+ end
909
+ end
910
+
911
+ return next
912
+ elseif kind == "array" then
913
+ local elements = node.elements
914
+
915
+ if elements then
916
+ for _, element in elements do
917
+ next = assignBits(element, scope, next)
918
+ end
919
+ end
920
+
921
+ return next
922
+ end
923
+
924
+ return next
925
+ end
926
+
927
+ --[[
928
+ Elements of dynamic arrays and maps carry their own bitfield, so their slots are numbered from
929
+ zero inside it rather than continuing the enclosing scope.
930
+ ]]
931
+ local function assignNestedScopes(node: Node)
932
+ local kind = node.kind
933
+
934
+ if kind == "array" then
935
+ local element = node.element :: Node
936
+
937
+ if element.scope then
938
+ assignBits(element, element.scope :: Scope, 0)
939
+ end
940
+
941
+ assignNestedScopes(element)
942
+
943
+ if node.elements then
944
+ for _, copy in node.elements :: { Node } do
945
+ assignNestedScopes(copy)
946
+ end
947
+ end
948
+ elseif kind == "map" then
949
+ local key = node.key :: Node
950
+ local value = node.value :: Node
951
+
952
+ if key.scope then
953
+ assignBits(key, key.scope :: Scope, 0)
954
+ end
955
+
956
+ if value.scope then
957
+ assignBits(value, value.scope :: Scope, 0)
958
+ end
959
+
960
+ assignNestedScopes(key)
961
+ assignNestedScopes(value)
962
+ elseif kind == "struct" then
963
+ for _, field in node.fields :: { Field } do
964
+ assignNestedScopes(field.node)
965
+ end
966
+ elseif kind == "union" then
967
+ --[[ A branch does not open a scope of its own — its flags fork into the enclosing one — but
968
+ a branch may *contain* a dynamic array or a map, and those do. ]]
969
+ for _, branch in node.branches :: { Field } do
970
+ assignNestedScopes(branch.node)
971
+ end
972
+ elseif kind == "optional" then
973
+ assignNestedScopes(node.inner :: Node)
974
+ end
975
+ end
976
+
977
+ --[=[
978
+ @within Ir
979
+ @function ceiling
980
+ @param node Node
981
+ @return number
982
+ @private
983
+
984
+ The most bytes this node can ever consume, derived from the schema rather than declared.
985
+
986
+ Every netweave type is bounded — a number by its encoding, a string and an array by the range
987
+ their author gave, an unbounded array by the 65535 its length prefix can express — so a
988
+ ceiling always exists and is often tight. `t.struct({ origin = t.vector3, seq = t.u16 })` can
989
+ never be more than fourteen bytes, and a packet claiming more on that channel is refusable
990
+ before a byte of it is decoded, with the game having declared nothing.
991
+
992
+ That is the point. `RESEARCH §3.7-F` records that no surveyed library checks a payload size at
993
+ all, and the reason is that they would have to ask the author for the number. Here the schema
994
+ already knows it.
995
+ ]=]
996
+ local function ceiling(node: Node): number
997
+ local kind = node.kind
998
+
999
+ --[[
1000
+ A node that opens a **scope of its own** pays for it here.
1001
+
1002
+ ~~Flags live in the enclosing scope's bytes, not here, so `bits` never adds to a node's own
1003
+ ceiling. The layout adds the scope once at the top.~~ **True of the root scope and false of
1004
+ every other one, and it made the ceiling smaller than the encoder** — corrected in M3 phase 9
1005
+ after an external review measured it.
1006
+
1007
+ Three places open a nested scope, all for the same reason: a count that is not known until
1008
+ runtime cannot fold its elements' flags into the enclosing bitfield, so each element carries
1009
+ its own (`lowerArray`, `lowerMap` above). `t.array(t.boolean, 0, 10)` therefore costs a byte
1010
+ per element, and derived **one** byte for ten of them — so `Batch.read` refused an honest
1011
+ three-element packet at stage `budget`, against its own sender, on any channel whose element
1012
+ type contained a boolean, an enum or an optional.
1013
+
1014
+ A fixed-length array is not affected and is the control: its positions unroll into the
1015
+ enclosing scope, so they have no scope of their own to add.
1016
+
1017
+ The root's scope is on the `Layout` rather than on `root`, so adding it here cannot
1018
+ double-count it.
1019
+ ]]
1020
+ local flags = if node.scope then (node.scope :: Scope).bytes else 0
1021
+ local prefix = if node.lengthStorage then ENCODING_SIZE[node.lengthStorage] else 0
1022
+ local max = node.max
1023
+ local body: number
1024
+
1025
+ if kind == "array" then
1026
+ local element = node.element
1027
+
1028
+ --[[ A fixed-length array with per-position flags lowers one node per position, so the
1029
+ element list is the authority when it exists. ]]
1030
+ if node.elements then
1031
+ local total = 0
1032
+
1033
+ for _, positioned in node.elements :: { Node } do
1034
+ total += ceiling(positioned)
1035
+ end
1036
+
1037
+ body = total
1038
+ else
1039
+ body = prefix + (max :: number) * ceiling(element :: Node)
1040
+ end
1041
+ elseif kind == "map" then
1042
+ local entry = ceiling(node.key :: Node) + ceiling(node.value :: Node)
1043
+ body = prefix + (max :: number) * entry
1044
+ elseif kind == "struct" then
1045
+ local total = 0
1046
+
1047
+ for _, field in node.fields :: { Field } do
1048
+ total += ceiling(field.node)
1049
+ end
1050
+
1051
+ body = total
1052
+ elseif kind == "union" then
1053
+ --[[ The widest branch, not their sum. One arrives; the ceiling is the largest one that can.
1054
+ The tag itself is bits in the enclosing scope and is counted there. ]]
1055
+ local widest = 0
1056
+
1057
+ for _, branch in node.branches :: { Field } do
1058
+ local size = ceiling(branch.node)
1059
+
1060
+ if size > widest then
1061
+ widest = size
1062
+ end
1063
+ end
1064
+
1065
+ body = widest
1066
+ elseif kind == "optional" then
1067
+ --[[ Presence is a bit in the enclosing scope; the inner value costs its own ceiling only
1068
+ when it is there, and the ceiling is the worst case. ]]
1069
+ body = ceiling(node.inner :: Node)
1070
+ elseif kind == "string" or kind == "buffer" then
1071
+ body = prefix + (max :: number)
1072
+ else
1073
+ body = node.fixedSize or 0
1074
+ end
1075
+
1076
+ return flags + body
1077
+ end
1078
+ --[=[
1079
+ @within Ir
1080
+ @function lower
1081
+ @param descriptor Descriptor -- a type from `netweave.types`
1082
+ @return Layout
1083
+
1084
+ Lowers a schema and runs the layout passes over it.
1085
+
1086
+ *Lower*, not *compile*: nothing is generated and there is no build step. This walks a schema
1087
+ and annotates it, so that the closure builder never has to ask a question at send time that
1088
+ could have been answered at definition time.
1089
+
1090
+ ```lua
1091
+ local layout = Ir.lower(t.array(t.u8, 100))
1092
+ layout.framing --> "static"
1093
+ layout.fixedSize --> 100
1094
+ ```
1095
+ ]=]
1096
+ function Ir.lower(descriptor: Descriptor): Layout
1097
+ local root = lower(descriptor)
1098
+
1099
+ local scope: Scope? = nil
1100
+ if root.bits > 0 then
1101
+ scope = makeScope(root.bits)
1102
+ assignBits(root, scope :: Scope, 0)
1103
+ end
1104
+
1105
+ assignNestedScopes(root)
1106
+
1107
+ local flagBytes = if scope then scope.bytes else 0
1108
+ local fixedSize = addSize(flagBytes, root.fixedSize)
1109
+
1110
+ return {
1111
+ root = root,
1112
+ scope = scope,
1113
+ fixedSize = fixedSize,
1114
+
1115
+ --[[
1116
+ The most bytes a payload on this schema can ever occupy. Unlike `fixedSize` it is never
1117
+ nil, because every netweave type is bounded — so every channel has a byte ceiling whether
1118
+ or not its author thought to ask for one, and an oversized packet is refusable before it
1119
+ is decoded (`PLAN-M3` D-5).
1120
+ ]]
1121
+ maxSize = flagBytes + ceiling(root),
1122
+
1123
+ --[[
1124
+ How many instances the payload always consumes, or nil when it depends on the data. The
1125
+ transport needs it to skip a refused packet: a packet that is discarded must take its
1126
+ sidecar entries with it, or every instance after it is read against the wrong field
1127
+ (`docs/WIRE-FORMAT.md` §2).
1128
+ ]]
1129
+ instances = root.instances,
1130
+
1131
+ --[[
1132
+ A statically sized packet carries no length prefix: the reader already knows where it
1133
+ ends, so the framing guarantee is free for it (`docs/WIRE-FORMAT.md` §2).
1134
+ ]]
1135
+ framing = if fixedSize then "static" else "counted",
1136
+ }
1137
+ end
1138
+
1139
+ --[[
1140
+ A node tree is assigned into a scope by `assignBits`, which writes `chunkIndex` and `mask` onto
1141
+ the nodes themselves. A derived layout therefore cannot share nodes with the one it derives
1142
+ from — assigning the patch would renumber the state's flags underneath it. Everything below the
1143
+ kind is copied; the assignment fields are deliberately not, because `Ir.patch` reassigns them.
1144
+ ]]
1145
+ local function cloneNode(node: Node): Node
1146
+ --[[
1147
+ Everything the node **is**, and nothing the layout **assigned** to it.
1148
+
1149
+ This was a field-by-field copy, which is `CLAUDE.md` §9's hand-kept list in the one place
1150
+ nothing tests it: a property missing here does not fail to compile and does not fail a round
1151
+ trip — it produces a *patch* layout that reads a different value than the state layout wrote.
1152
+ M4 phase 8 added four properties to `Node` and this copied none of them, so a `t.quantized`
1153
+ field inside `nw.replicate` lost its step on the patch side and came back as a raw count.
1154
+
1155
+ `table.clone` inverts the list to the short one that does not grow: the four bit *positions*,
1156
+ which are assignments `assignBits` makes over each tree separately and which would be stale
1157
+ here. `template` and `scope` come across shared on purpose — both are read-only structure, and
1158
+ dropping the scope left an array element with flags and nowhere to put them.
1159
+ ]]
1160
+ local copy: Node = table.clone(node)
1161
+
1162
+ copy.chunkIndex = nil
1163
+ copy.mask = nil
1164
+ copy.tagChunks = nil
1165
+ copy.tagMasks = nil
1166
+
1167
+ if node.inner then
1168
+ copy.inner = cloneNode(node.inner :: Node)
1169
+ end
1170
+
1171
+ if node.element then
1172
+ copy.element = cloneNode(node.element :: Node)
1173
+ end
1174
+
1175
+ if node.elements then
1176
+ local elements: { Node } = {}
1177
+
1178
+ for index, one in node.elements :: { Node } do
1179
+ elements[index] = cloneNode(one)
1180
+ end
1181
+
1182
+ copy.elements = elements
1183
+ end
1184
+
1185
+ if node.key then
1186
+ copy.key = cloneNode(node.key :: Node)
1187
+ end
1188
+
1189
+ if node.value then
1190
+ copy.value = cloneNode(node.value :: Node)
1191
+ end
1192
+
1193
+ if node.fields then
1194
+ local fields: { Field } = {}
1195
+
1196
+ for index, field in node.fields :: { Field } do
1197
+ fields[index] = { name = field.name, node = cloneNode(field.node) }
1198
+ end
1199
+
1200
+ copy.fields = fields
1201
+ end
1202
+
1203
+ if node.branches then
1204
+ local branches: { Field } = {}
1205
+
1206
+ for index, branch in node.branches :: { Field } do
1207
+ branches[index] = { name = branch.name, node = cloneNode(branch.node) }
1208
+ end
1209
+
1210
+ copy.branches = branches
1211
+ end
1212
+
1213
+ return copy
1214
+ end
1215
+
1216
+ --[[ One presence bit in front of a node, which is exactly what `lower` produces for `t.optional`.
1217
+ Built here rather than through the type layer because `t.optional` refuses to wrap an optional
1218
+ — correctly, since `T??` is `T?` to a reader — and a patch needs both bits to mean different
1219
+ things. See `Ir.patch`. ]]
1220
+ local function optionalOf(inner: Node): Node
1221
+ return {
1222
+ kind = "optional" :: Types.Kind,
1223
+ bits = 1 + inner.bits,
1224
+ fixedSize = if inner.fixedSize == 0 then 0 else nil,
1225
+ instances = if inner.instances == 0 then 0 else nil,
1226
+ inner = inner,
1227
+ }
1228
+ end
1229
+
1230
+ local function patchNode(node: Node, root: boolean): Node
1231
+ if node.kind ~= "struct" then
1232
+ return optionalOf(cloneNode(node))
1233
+ end
1234
+
1235
+ local source = node.fields :: { Field }
1236
+ local fields: { Field } = sized(#source)
1237
+
1238
+ local bits = 0
1239
+ local fixedSize: number? = 0
1240
+ local instances: number? = 0
1241
+
1242
+ for index, field in source do
1243
+ local child = patchNode(field.node, false)
1244
+
1245
+ fields[index] = { name = field.name, node = child }
1246
+ bits += child.bits
1247
+ fixedSize = addSize(fixedSize, child.fixedSize)
1248
+ instances = addSize(instances, child.instances)
1249
+ end
1250
+
1251
+ local patched: Node = {
1252
+ kind = "struct" :: Types.Kind,
1253
+ bits = bits,
1254
+ fixedSize = fixedSize,
1255
+ instances = instances,
1256
+ fields = fields,
1257
+ template = node.template,
1258
+ }
1259
+
1260
+ --[[ A nested struct gets a bit, so "this sub-struct is untouched" costs a bit rather than a
1261
+ walk — and when it is touched, the bits inside say which of its fields moved. The root's
1262
+ own bit is added by `Ir.patch`, because it means something different from all of these. ]]
1263
+ return if root then patched else optionalOf(patched)
1264
+ end
1265
+
1266
+ --[=[
1267
+ @within Ir
1268
+ @function patch
1269
+ @param layout Layout -- a state layout, from [Ir.lower]
1270
+ @return Layout -- the layout of a *change* to a payload on it
1271
+
1272
+ The layout of a patch: which fields moved, and their new values.
1273
+
1274
+ **Every field gains one bit and nothing else.** A twelve-field struct where one field changed is
1275
+ twelve bits and that field's value — field identity is a *position* in the bitfield rather than
1276
+ a serialised key, which is the whole reason delta compression belongs inside a schema-driven
1277
+ codec rather than beside one. `delta-compress` writes a type tag per value because it has no
1278
+ schema and cannot do otherwise (`RESEARCH §1`, M4 phase 1).
1279
+
1280
+ The derivation is one rule applied recursively: **wrap it in an optional**. That is not a trick,
1281
+ it is what the two states of a patched field already are —
1282
+
1283
+ * a non-optional field becomes `optional(T)`: absent is *unchanged*, present is the new value;
1284
+ * a field that was already `optional(T)` becomes `optional(optional(T))`, and the two bits are
1285
+ different questions — the outer is *did it change*, the inner is *is it there now*. Removal
1286
+ needs no sentinel value, which is what Charm Sync spends a `__none` table on because it
1287
+ rides Roblox's default serialisation where `nil` and absent are the same thing.
1288
+
1289
+ Structs recurse; everything else is replaced whole. An array or map patch is the new array or
1290
+ map, because a per-element diff needs its own operation vocabulary — `delta-compress` has five
1291
+ such tags — and that is a schema the state schema does not describe. Recorded as a limit rather
1292
+ than hidden: a state whose changes are mostly inside a large array gets no win from this, and
1293
+ `PLAN-M4` acceptance 8 measures the crossover instead of assuming one.
1294
+
1295
+ :::caution
1296
+ The result shares no node with `layout`. `assignBits` writes onto nodes, so a shared tree would
1297
+ renumber the state's own flags when the patch was assigned.
1298
+ :::
1299
+ ]=]
1300
+ function Ir.patch(layout: Layout): Layout
1301
+ --[[
1302
+ The root's bit is **is this subject still there**, and it is the reason a patch needs no
1303
+ second packet shape beside it.
1304
+
1305
+ A replicated subject has three states for a given client: unchanged, changed, and gone.
1306
+ Unchanged is no packet at all. The other two are one packet whose root bit separates them —
1307
+ set, and the bits below say what moved; clear, and there is nothing below because the
1308
+ subject has left that client's audience or stopped existing (`PLAN-M4` D-4, "one leaving
1309
+ needs to be told to forget").
1310
+
1311
+ It is usually free. A patch's flags are a bitfield rounded up to whole bytes, so a
1312
+ twelve-field struct goes from twelve bits to thirteen and stays at two; it costs a byte only
1313
+ on a schema whose bit count was already an exact multiple of eight.
1314
+ ]]
1315
+ local root = optionalOf(patchNode(layout.root, true))
1316
+
1317
+ local scope: Scope? = nil
1318
+ if root.bits > 0 then
1319
+ scope = makeScope(root.bits)
1320
+ assignBits(root, scope :: Scope, 0)
1321
+ end
1322
+
1323
+ assignNestedScopes(root)
1324
+
1325
+ local flagBytes = if scope then scope.bytes else 0
1326
+ local fixedSize = addSize(flagBytes, root.fixedSize)
1327
+
1328
+ return {
1329
+ root = root,
1330
+ scope = scope,
1331
+ fixedSize = fixedSize,
1332
+ maxSize = flagBytes + ceiling(root),
1333
+ instances = root.instances,
1334
+
1335
+ --[[
1336
+ **Always `counted`, whatever the sizes say.**
1337
+
1338
+ ~~`if fixedSize then "static" else "counted"`~~, copied from `lower` — and wrong here, for
1339
+ a reason `lower` has no way to know: the same channel emits a *removal*, which is the flag
1340
+ bytes and nothing else, and a change carrying values. Where a refused one ends cannot be
1341
+ known from the schema, so the length prefix earns its byte (`docs/WIRE-FORMAT.md` §2,
1342
+ `Batch.writeChange`).
1343
+
1344
+ `t.struct({ a = t.boolean, b = t.enum{x,y} })` patched reported `static` at one byte, and
1345
+ `Channel.make` hardcoded `"counted"` beside it — so nothing read this and nothing was
1346
+ broken, which is exactly how the next reader of `delta.layout.framing` gets an answer the
1347
+ wire format contradicts (M4 report finding 42).
1348
+ ]]
1349
+ framing = "counted",
1350
+ }
1351
+ end
1352
+
1353
+ return Ir