@rbxts/netweave 0.0.0-stage → 0.1.0

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,613 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Delta
6
+
7
+ What changed, on the wire, against what the receiver already has.
8
+
9
+ A patch is the state layout with every field wrapped in one more presence bit — see
10
+ [Ir.patch], which derives it. This module is the pair of walks over that shape: one that
11
+ compares two values and writes the difference, and one that reads a difference and folds it
12
+ into a baseline.
13
+
14
+ **Why this belongs inside the codec rather than beside it.** `delta-compress` writes a type tag
15
+ per value — nineteen ids covering datatypes and diff operations
16
+ (`_refsrc/delta-compress/src/TypeId.luau:4-22`) — because it has no schema
17
+ and cannot do otherwise (`RESEARCH §1`, M4 phase 1). netweave has one, so a patch of a
18
+ twelve-field struct is *twelve bits saying which moved, then the moved values in schema order*.
19
+ Field identity is a position, not a serialised key. Measured on that schema: three bytes against
20
+ twelve for a resend.
21
+
22
+ Internal. `nw.replicate` is the public read of it.
23
+ ]=]
24
+
25
+ --[[
26
+ Two walks rather than one codec, and the reason is allocation.
27
+
28
+ The obvious shape is `diff(old, new) -> patchTable` followed by an ordinary encode, and a decode
29
+ followed by `apply(baseline, patchTable)`. That builds a table per patch on each side — the
30
+ decode-then-rehash cost `RESEARCH §3.8-S` measures in Blink's and Zap's readers, and that
31
+ `Serdes`'s template clone (ByteNet's trick, the one axis where it beat both) exists to avoid.
32
+
33
+ It is also *wrong* on the receive side, not merely wasteful. A patch table cannot express "this
34
+ optional field changed to nil": an absent key and a key set to nil are the same table. Charm
35
+ Sync spends a `__none` sentinel table on exactly that problem (`charm-sync/src/patch.luau:10`)
36
+ because it rides Roblox's default serialisation. Reading the bit and folding it into the
37
+ baseline in the same pass has no intermediate to lose the distinction in.
38
+ ]]
39
+
40
+ local Buffer = require("../codec/Buffer")
41
+ local Ir = require("../codec/Ir")
42
+ local Serdes = require("../codec/Serdes")
43
+
44
+ type Node = Ir.Node
45
+ type Field = Ir.Field
46
+ type Scope = Ir.Scope
47
+ type Flags = { number }
48
+
49
+ local band = bit32.band
50
+ local bor = bit32.bor
51
+
52
+ --[[
53
+ A patch whose bits say "these fields did not move" is only readable against a value that has
54
+ them. With no baseline it merges into a value missing whatever the patch did not carry, and that
55
+ value reaches the handler as a `t.struct` with a field absent — the one thing every declaration
56
+ promises cannot happen.
57
+
58
+ It is not a hostile case. A client that refuses one change holds a baseline the server has
59
+ already moved past, so the next honest patch is computed against something the reader no longer
60
+ has; the fuzzer produced it in 8 of 4,000 mutated rounds without ever having to aim at it
61
+ (`PLAN-M4` phase 6). The recovery already exists — a refused change desyncs the channel and asks
62
+ for it again — and this is what makes the refusal happen instead of the merge.
63
+
64
+ One shared string rather than a built one: a reason that allocates per packet is the property
65
+ `CLAUDE.md` §9 says the rejection path has to keep, and a flood of short patches is exactly the
66
+ shape that would exercise it.
67
+ ]]
68
+ local NO_BASELINE = "a change patched a subject this endpoint has no baseline for"
69
+
70
+ local PATCH_CHUNK: { [number]: (offset: number, value: number) -> () } = {
71
+ [1] = Buffer.patchU8,
72
+ [2] = Buffer.patchU16,
73
+ [4] = Buffer.patchU32,
74
+ }
75
+
76
+ local READ_CHUNK: { [number]: () -> number } = {
77
+ [1] = Buffer.readU8,
78
+ [2] = Buffer.readU16,
79
+ [4] = Buffer.readU32,
80
+ }
81
+
82
+ local function sized(count: number): any
83
+ return table.create(count)
84
+ end
85
+
86
+ -- -------------------------------------------------------------------------------------------
87
+ -- Equality, guided by the node
88
+ -- -------------------------------------------------------------------------------------------
89
+
90
+ --[[
91
+ Whether two values of this node's type are the same.
92
+
93
+ Reference equality first, at every level. ~~That is how Charm's immutable atoms make their own
94
+ diff cheap; a game that replaces pays a pointer compare.~~ Not through the tick: the baseline it
95
+ compares against is always `Tick.snapshot`'s copy, so the top-level compare never fires there and
96
+ an atom costs what a plain table costs (M4 report finding 59; M4-1). What the pointer compare
97
+ still buys is the merge — a value folded into its base shares every untouched subtree with it,
98
+ and those compare in one step the next time round. Charm's own diff does use it that way
99
+ (`charm-sync/src/patch.luau:60`).
100
+ ]]
101
+ local function sameFor(node: Node): (a: any, b: any) -> boolean
102
+ local kind = node.kind
103
+
104
+ if kind == "buffer" then
105
+ --[[ Buffers have no value equality in Luau, so this is the one leaf that has to look at
106
+ bytes. ]]
107
+ return function(a: any, b: any): boolean
108
+ if a == b then
109
+ return true
110
+ end
111
+
112
+ if a == nil or b == nil then
113
+ return false
114
+ end
115
+
116
+ local length = buffer.len(a)
117
+
118
+ if length ~= buffer.len(b) then
119
+ return false
120
+ end
121
+
122
+ return buffer.readstring(a, 0, length) == buffer.readstring(b, 0, length)
123
+ end
124
+ elseif kind == "optional" then
125
+ local sameInner = sameFor(node.inner :: Node)
126
+ local default = node.default
127
+
128
+ if default ~= nil then
129
+ --[[ Absent and the default are one value to the reader, so they are one value here: a
130
+ game that leaves the field out and then sets it to the default has not moved it. ]]
131
+ return function(a: any, b: any): boolean
132
+ if a == nil then
133
+ a = default
134
+ end
135
+
136
+ if b == nil then
137
+ b = default
138
+ end
139
+
140
+ return a == b
141
+ end
142
+ end
143
+
144
+ return function(a: any, b: any): boolean
145
+ if a == nil or b == nil then
146
+ return a == b
147
+ end
148
+
149
+ return sameInner(a, b)
150
+ end
151
+ elseif kind == "struct" then
152
+ local fields = node.fields :: { Field }
153
+ local count = #fields
154
+ local names: { string } = sized(count)
155
+ local sames: { (a: any, b: any) -> boolean } = sized(count)
156
+
157
+ for index, field in fields do
158
+ names[index] = field.name
159
+ sames[index] = sameFor(field.node)
160
+ end
161
+
162
+ return function(a: any, b: any): boolean
163
+ if a == b then
164
+ return true
165
+ end
166
+
167
+ if a == nil or b == nil then
168
+ return false
169
+ end
170
+
171
+ for index = 1, count do
172
+ local name = names[index]
173
+
174
+ if not sames[index](a[name], b[name]) then
175
+ return false
176
+ end
177
+ end
178
+
179
+ return true
180
+ end
181
+ elseif kind == "union" then
182
+ local branches = node.branches :: { Field }
183
+ local lookup = node.lookup :: { [string]: number }
184
+ local sames: { (a: any, b: any) -> boolean } = sized(#branches)
185
+
186
+ for index, branch in branches do
187
+ sames[index] = sameFor(branch.node)
188
+ end
189
+
190
+ return function(a: any, b: any): boolean
191
+ if a == b then
192
+ return true
193
+ end
194
+
195
+ --[[ A different branch is a different value whatever is inside it, and comparing across
196
+ branches would be comparing two shapes that share no fields. ]]
197
+ if a == nil or b == nil or a.tag ~= b.tag then
198
+ return false
199
+ end
200
+
201
+ --[[ A tag neither branch names cannot be compared, and "changed" is the safe answer: the
202
+ writer refuses it a moment later and says which value it was. ]]
203
+ local index = lookup[a.tag]
204
+
205
+ if index == nil then
206
+ return false
207
+ end
208
+
209
+ return sames[index](a.value, b.value)
210
+ end
211
+ elseif kind == "array" then
212
+ local sameElement = sameFor(node.element :: Node)
213
+
214
+ return function(a: any, b: any): boolean
215
+ if a == b then
216
+ return true
217
+ end
218
+
219
+ if a == nil or b == nil or #a ~= #b then
220
+ return false
221
+ end
222
+
223
+ for index = 1, #a do
224
+ if not sameElement(a[index], b[index]) then
225
+ return false
226
+ end
227
+ end
228
+
229
+ return true
230
+ end
231
+ elseif kind == "map" then
232
+ local sameValue = sameFor(node.value :: Node)
233
+
234
+ return function(a: any, b: any): boolean
235
+ if a == b then
236
+ return true
237
+ end
238
+
239
+ if a == nil or b == nil then
240
+ return false
241
+ end
242
+
243
+ for key, value in a do
244
+ if not sameValue(value, b[key]) then
245
+ return false
246
+ end
247
+ end
248
+
249
+ --[[ The walk above misses keys present only in `b`, so count both ways. Maps are
250
+ bounded by their declared `max`, so this terminates in the schema's own bound. ]]
251
+ for key in b do
252
+ if a[key] == nil then
253
+ return false
254
+ end
255
+ end
256
+
257
+ return true
258
+ end
259
+ end
260
+
261
+ --[[ Every other kind — numbers, strings, booleans, enums, instances and the Roblox datatypes —
262
+ has value equality that means what it says. ]]
263
+ return function(a: any, b: any): boolean
264
+ return a == b
265
+ end
266
+ end
267
+
268
+ -- -------------------------------------------------------------------------------------------
269
+ -- The two walks
270
+ -- -------------------------------------------------------------------------------------------
271
+
272
+ --[[ Writes what differs and answers whether anything did. Flags are set into the accumulator
273
+ rather than the buffer, so an outer bit can be decided after the values under it are written —
274
+ which is what lets a nested struct's bit mean "something inside moved". ]]
275
+ type Differ = (old: any, new: any, flags: Flags) -> boolean
276
+
277
+ --[[ Folds a patch into a baseline. Returns the value and whether it is a new one, so an untouched
278
+ sub-struct is returned by reference instead of being cloned — the result shares everything the
279
+ patch did not touch. ]]
280
+ type Merger = (base: any, flags: Flags) -> (any, boolean)
281
+
282
+ local buildDiffer, buildMerger
283
+
284
+ function buildDiffer(node: Node): Differ
285
+ if node.kind == "struct" then
286
+ local fields = node.fields :: { Field }
287
+ local count = #fields
288
+ local names: { string } = sized(count)
289
+ local differs: { Differ } = sized(count)
290
+
291
+ for index, field in fields do
292
+ names[index] = field.name
293
+ differs[index] = buildDiffer(field.node)
294
+ end
295
+
296
+ return function(old: any, new: any, flags: Flags): boolean
297
+ local changed = false
298
+
299
+ for index = 1, count do
300
+ local name = names[index]
301
+ local before = if old == nil then nil else old[name]
302
+ local after = if new == nil then nil else new[name]
303
+
304
+ if differs[index](before, after, flags) then
305
+ changed = true
306
+ end
307
+ end
308
+
309
+ return changed
310
+ end
311
+ end
312
+
313
+ --[[ Everything else in a patch tree is the presence bit `Ir.patch` put there. ]]
314
+ local chunk = node.chunkIndex :: number
315
+ local mask = node.mask :: number
316
+ local inner = node.inner :: Node
317
+
318
+ if inner.kind == "struct" then
319
+ --[[ A nested struct, recursed into. The bit says "something below moved"; which fields
320
+ moved is the bits below it. ]]
321
+ local innerDiffer = buildDiffer(inner)
322
+
323
+ return function(old: any, new: any, flags: Flags): boolean
324
+ if not innerDiffer(old, new, flags) then
325
+ return false
326
+ end
327
+
328
+ flags[chunk] = bor(flags[chunk], mask)
329
+ return true
330
+ end
331
+ end
332
+
333
+ local same = sameFor(inner)
334
+ local writeInner = Serdes.nodeCodec(inner)
335
+
336
+ return function(old: any, new: any, flags: Flags): boolean
337
+ if same(old, new) then
338
+ return false
339
+ end
340
+
341
+ flags[chunk] = bor(flags[chunk], mask)
342
+
343
+ --[[ When `inner` is itself an optional — the field was `t.optional(T)` in the state — this
344
+ is where removal happens and it costs nothing extra. `Serdes`' optional writer clears
345
+ its own bit for a nil, so the pair reads as "changed, and it is not there now". ]]
346
+ writeInner(new, flags)
347
+ return true
348
+ end
349
+ end
350
+
351
+ function buildMerger(node: Node): Merger
352
+ if node.kind == "struct" then
353
+ local fields = node.fields :: { Field }
354
+ local count = #fields
355
+ local names: { string } = sized(count)
356
+ local mergers: { Merger } = sized(count)
357
+
358
+ for index, field in fields do
359
+ names[index] = field.name
360
+ mergers[index] = buildMerger(field.node)
361
+ end
362
+
363
+ return function(base: any, flags: Flags): (any, boolean)
364
+ local result: any = nil
365
+
366
+ for index = 1, count do
367
+ local name = names[index]
368
+ local value, changed = mergers[index](if base == nil then nil else base[name], flags)
369
+
370
+ if changed then
371
+ --[[ Cloned on the first change and not before, so a sub-struct nothing touched
372
+ comes back by reference. ]]
373
+ result = result or (if base == nil then {} else table.clone(base))
374
+ result[name] = value
375
+ end
376
+ end
377
+
378
+ if result == nil then
379
+ --[[
380
+ Nothing below moved.
381
+
382
+ Against a baseline that had this struct, that is the struct unchanged and it
383
+ comes back by reference — which is the sharing this module exists for.
384
+
385
+ Against **no baseline at all** it is a value whose every field is an absent
386
+ optional, and that value still *exists*. Returning the nil baseline there would
387
+ make it indistinguishable from a subject that was removed, which is the one
388
+ thing the root bit is supposed to separate. Found by testing an arrival of
389
+ `t.struct({ a = t.optional(t.u8), b = t.optional(t.u8) })` with neither set.
390
+ ]]
391
+ if base == nil then
392
+ return {}, true
393
+ end
394
+
395
+ return base, false
396
+ end
397
+
398
+ return result, true
399
+ end
400
+ end
401
+
402
+ local chunk = node.chunkIndex :: number
403
+ local mask = node.mask :: number
404
+ local inner = node.inner :: Node
405
+
406
+ if inner.kind == "struct" then
407
+ local innerMerger = buildMerger(inner)
408
+
409
+ return function(base: any, flags: Flags): (any, boolean)
410
+ if band(flags[chunk], mask) == 0 then
411
+ --[[ A sub-struct the patch did not touch, and nothing to fall back on. See
412
+ `NO_BASELINE`: the whole struct would be absent from the merged value. ]]
413
+ if base == nil then
414
+ Buffer.reject(NO_BASELINE)
415
+ end
416
+
417
+ return base, false
418
+ end
419
+
420
+ return innerMerger(base, flags)
421
+ end
422
+ end
423
+
424
+ local _, readInner = Serdes.nodeCodec(inner)
425
+
426
+ --[[ Whether the *state* said this field may be absent. An `optional` that the patch did not
427
+ touch is legitimately nil against no baseline; anything else is a hole. ]]
428
+ local required = inner.kind ~= "optional"
429
+
430
+ return function(base: any, flags: Flags): (any, boolean)
431
+ if band(flags[chunk], mask) == 0 then
432
+ if required and base == nil then
433
+ Buffer.reject(NO_BASELINE)
434
+ end
435
+
436
+ return base, false
437
+ end
438
+
439
+ --[[ `readInner` returns nil for an inner optional whose bit is clear, which is the removal
440
+ case, and the caller assigns it — dropping the key rather than leaving a sentinel. ]]
441
+ return readInner(flags), true
442
+ end
443
+ end
444
+
445
+ -- -------------------------------------------------------------------------------------------
446
+
447
+ local Delta = {}
448
+
449
+ --[=[
450
+ @interface Delta
451
+ @within Delta
452
+ .layout Layout -- the patch layout, derived from the state layout
453
+ .write (old: any, new: any) -> boolean -- writes a patch, or nothing and false
454
+ .apply (base: any) -> (any, string?) -- reads a patch and folds it into `base`, or a reason
455
+ ]=]
456
+ export type Delta = {
457
+ layout: Ir.Layout,
458
+ write: (old: any, new: any) -> boolean,
459
+ --[[ `(nil, nil)` is the subject going away and `(nil, reason)` is a change that could not be
460
+ read. A caller that treats the two the same drops a subject because a peer sent a short
461
+ packet, which is the difference between a removal and a lie. ]]
462
+ apply: (base: any) -> (any, string?),
463
+ }
464
+
465
+ --[=[
466
+ @within Delta
467
+ @function build
468
+ @param state Layout -- a state layout, from [Ir.lower]
469
+ @return Delta
470
+
471
+ The differ and merger for one schema, built once at declaration.
472
+
473
+ ```lua
474
+ local delta = Delta.build(Ir.lower(schema))
475
+
476
+ Buffer.load(record)
477
+ if delta.write(baseline, current) then
478
+ -- something moved, and the patch is in the outgoing buffer
479
+ end
480
+ ```
481
+
482
+ :::caution
483
+ `write` returns **false and writes nothing** when the two values are the same. A caller that
484
+ frames the result has to ask before it frames, because a patch of nothing is not an empty patch,
485
+ it is the absence of a packet.
486
+ :::
487
+ ]=]
488
+ function Delta.build(state: Ir.Layout): Delta
489
+ local layout = Ir.patch(state)
490
+ local root = layout.root
491
+
492
+ --[[ The root is the existence bit `Ir.patch` put on, and this reads it directly rather than
493
+ through `buildDiffer`'s optional case, because the two branches under it are not "changed
494
+ or not" — they are *gone* and *here is what moved*, and only one of them has a body. ]]
495
+ local rootChunk = root.chunkIndex :: number
496
+ local rootMask = root.mask :: number
497
+ local inner = root.inner :: Node
498
+
499
+ local differ = buildDiffer(inner)
500
+ local merger = buildMerger(inner)
501
+
502
+ --[[ There is always a scope now: the root's own bit guarantees at least one, so the schema with
503
+ no fields that used to need a degenerate branch has one too. ]]
504
+ local scope = layout.scope :: Scope
505
+ local chunks = scope.chunks
506
+ local count = #chunks
507
+ local bytes = scope.bytes
508
+ local accumulator: Flags = table.create(count, 0)
509
+
510
+ local patches: { (offset: number, value: number) -> () } = sized(count)
511
+ local offsets: { number } = sized(count)
512
+ local reads: { () -> number } = sized(count)
513
+
514
+ for index, chunk in chunks do
515
+ patches[index] = PATCH_CHUNK[chunk.width]
516
+ offsets[index] = chunk.offset
517
+ reads[index] = READ_CHUNK[chunk.width]
518
+ end
519
+
520
+ --[[ Where the current call's flag bytes start. An upvalue rather than a local of `write`, so that
521
+ `commit` below is built once here and not once per call: Luau caches a closure only when
522
+ everything it captures is an upvalue or a module local, and `write` runs once per subject
523
+ per recipient per frame, where a closure cost 112 B a call for nothing to hold
524
+ (SECURITY-REPORT-M4 73; `bench/residue` rung 73). ]]
525
+ local flagsAt = 0
526
+
527
+ local function commit(): boolean
528
+ for index = 1, count do
529
+ patches[index](flagsAt + offsets[index], accumulator[index])
530
+ end
531
+
532
+ return true
533
+ end
534
+
535
+ return {
536
+ layout = layout,
537
+
538
+ write = function(old: any, new: any): boolean
539
+ --[[ Marked before the flag bytes are reserved, because "nothing changed" has to leave
540
+ the buffer exactly as it found it — the caller has not decided to send anything
541
+ yet. `rollback` is the same rewind the send path uses for an encode that raised. ]]
542
+ local used, instances = Buffer.mark()
543
+ flagsAt = Buffer.reserve(bytes)
544
+
545
+ for index = 1, count do
546
+ accumulator[index] = 0
547
+ end
548
+
549
+ if new == nil then
550
+ --[[ Gone. The root bit stays clear and there is no body at all, so a removal is the
551
+ flag bytes and the subject that framed them — usually two. Telling a client
552
+ nothing is gone would be the same packet, so that case has to be caught here
553
+ rather than written. ]]
554
+ if old == nil then
555
+ Buffer.rollback(used, instances)
556
+ return false
557
+ end
558
+
559
+ return commit()
560
+ end
561
+
562
+ local changed = differ(old, new, accumulator)
563
+
564
+ --[[ `old == nil` is a subject this client has never seen, and it is sent even when the
565
+ differ found nothing — a struct of optionals that are all absent still has to
566
+ *arrive*, or the client never learns the subject exists. ]]
567
+ if old ~= nil and not changed then
568
+ Buffer.rollback(used, instances)
569
+ return false
570
+ end
571
+
572
+ accumulator[rootChunk] = bor(accumulator[rootChunk], rootMask)
573
+ return commit()
574
+ end,
575
+
576
+ apply = function(base: any): (any, string?)
577
+ --[[ Cleared and then checked, the same two things `Serdes`' reader does and for the same
578
+ reason. Neither was here until M4 phase 6 went looking: a change whose flag bits
579
+ claim fields the packet does not carry read **past its own end**, and the values
580
+ came back as whatever the next packet's bytes happened to be — silently, because
581
+ nothing asked. G5 says one malformed packet must not stop the rest, and a rejection
582
+ carried forward from the packet before would do exactly that. ]]
583
+ Buffer.clearRejection()
584
+
585
+ for index = 1, count do
586
+ accumulator[index] = reads[index]()
587
+ end
588
+
589
+ local short = Buffer.rejected()
590
+
591
+ if short then
592
+ return nil, short
593
+ end
594
+
595
+ --[[ The subject is gone. `nil` with no failure beside it, which is what separates a
596
+ removal from a change that could not be read. ]]
597
+ if band(accumulator[rootChunk], rootMask) == 0 then
598
+ return nil, nil
599
+ end
600
+
601
+ local value = merger(base, accumulator)
602
+ local failure = Buffer.rejected()
603
+
604
+ if failure then
605
+ return nil, failure
606
+ end
607
+
608
+ return value, nil
609
+ end,
610
+ }
611
+ end
612
+
613
+ return Delta