@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,597 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Tick
6
+
7
+ Once a frame: what each client should see, against what it already has.
8
+
9
+ Everything else in `src/replication/` is a piece — the diff, the baselines, the seam. This is
10
+ the loop that uses them, and it is the only place that knows a replicated channel is *driven*
11
+ rather than called.
12
+
13
+ Internal. `Driver` runs it between the intent dispatch and the flush, so a change rides the same
14
+ batch as everything else the frame produced.
15
+ ]=]
16
+
17
+ --[[
18
+ Subject-major, and the alternative is written down rather than left to be rediscovered.
19
+
20
+ Each recipient's change is computed against *that recipient's* baseline, so there is nothing to
21
+ serialise once and copy — which is the trick `Outbound.publish` uses and the reason it does not
22
+ apply here. What is left is a `switchTo` per recipient per subject, where a recipient-major loop
23
+ would switch once per recipient and pay a table of recipients per subject instead.
24
+
25
+ ~~Which is cheaper depends on the ratio of subjects to players and on what `switchTo` costs, and
26
+ the benchmark cannot see either yet.~~ **`bench/tick.luau` sees it now**, and it narrows the
27
+ question rather than answering it: since phase 8 a pair with nothing to send does not reach
28
+ `switchTo` at all, so the trade only exists for the subjects that moved. Fifty players and five
29
+ hundred subjects with everything moving is 33.99 ms a tick and every bit of that is pairs with
30
+ something to write — which a recipient-major loop would still have to write, one buffer switch
31
+ cheaper each. That is the version worth building if this ever needs building; a world at rest
32
+ costs 1.63 ms and has nothing left to win.
33
+ ]]
34
+
35
+ local Baseline = require("./Baseline")
36
+ local Ir = require("../codec/Ir")
37
+ local Observer = require("../api/Observer")
38
+ local Outbound = require("../transport/Outbound")
39
+ local Recipients = require("../transport/Recipients")
40
+
41
+ local Tick = {}
42
+
43
+ type Slot = {
44
+ --[[ Which subjects the store listed last time. A subject that was there and is not any more has
45
+ to be taken off every client that has it, and nothing else would notice — it is absent from
46
+ the store, so the loop below never reaches it. ]]
47
+ held: { [any]: boolean },
48
+ scratch: { [any]: boolean },
49
+
50
+ --[[ The snapshot most recently handed out for each subject, kept across ticks rather than
51
+ rebuilt per tick. It is the same table every up-to-date recipient's baseline points at,
52
+ which is what makes the gate below a pointer comparison. Cleared with `held`, so it holds
53
+ nothing the store has stopped listing. ]]
54
+ kept: { [any]: any },
55
+
56
+ --[[ Subjects whose last change could not be written to anyone, keyed to the snapshot that
57
+ failed, so they are not attempted again until the value moves. ]]
58
+ stuck: { [any]: any },
59
+
60
+ --[[ The schema's shape, from the channel's layout: which keys `snapshot` and `moved` read. ]]
61
+ shape: any,
62
+ }
63
+
64
+ --[=[
65
+ @interface Config
66
+ @within Tick
67
+ .outbound Outbound
68
+ .baselines Baseline
69
+ .roster Roster
70
+ .channels () -> { any } -- the replicated channels, read late because ids are assigned late
71
+ ]=]
72
+ --[[
73
+ The three collaborators were `any`, so a renamed method or a wrong argument order was not a
74
+ diagnostic and `lune run analyze` was clean because there was nothing to check (M4 report
75
+ finding 46). `channels` stays `{ any }`: a channel record is `any` across the whole transport
76
+ boundary and typing it here alone would be a fence with one post.
77
+ ]]
78
+ export type Config = {
79
+ outbound: Outbound.Outbound,
80
+ baselines: Baseline.Baseline,
81
+ roster: Recipients.Roster,
82
+ channels: () -> { any },
83
+ }
84
+
85
+ --[=[
86
+ @within Tick
87
+ @function new
88
+ @param config Config
89
+ @return () -> ()
90
+
91
+ The loop, bound to its collaborators once.
92
+ ]=]
93
+ function Tick.new(config: Config): () -> ()
94
+ local outbound = config.outbound
95
+ local baselines = config.baselines
96
+ local roster = config.roster
97
+ local channels = config.channels
98
+
99
+ --[[
100
+ The schema's shape, read once per channel from its lowered layout: what the differ reads and
101
+ nothing else.
102
+
103
+ `snapshot` and `moved` below used to walk the game's whole table, which made the phase 8
104
+ gate schema-unaware. A key the schema never reads but which changes every frame — `lastSeen =
105
+ os.clock()`, a `Character` reference — made every subject "moved", and the per-pair attempt
106
+ the gate removed was back: 31.02 ms a tick at 50 × 500 with nothing the schema reads moving,
107
+ against 1.65 ms idle (`bench/tick`, `extra key`). A subtree the schema never reads — the
108
+ inventory a `Replica.Data` carries that this channel does not replicate — was cloned into
109
+ every baseline and walked every tick. And a cycle through such a key overflowed the stack, a
110
+ fourth way for a game's own data to abort the frame's flush (M4-1). A walk over the shape is
111
+ finite by construction, so that one closes with the same change.
112
+
113
+ `false` marks a leaf — a scalar, a datatype, a buffer — so a field lookup can tell "not in
114
+ the schema" (nil) from "in the schema and carried by value" (false).
115
+ ]]
116
+ type Shape = {
117
+ fields: { [string]: any }?,
118
+ element: any,
119
+ count: number?,
120
+ value: any,
121
+ branches: { [string]: any }?,
122
+ }
123
+
124
+ local function shapeOf(node: Ir.Node): any
125
+ local kind = node.kind
126
+
127
+ if kind == "struct" then
128
+ local fields: { [string]: any } = {}
129
+
130
+ for _, field in node.fields :: { Ir.Field } do
131
+ fields[field.name] = shapeOf(field.node)
132
+ end
133
+
134
+ return { fields = fields }
135
+ elseif kind == "array" then
136
+ local elements = node.elements
137
+ local element = if elements then elements[1] else node.element :: Ir.Node
138
+
139
+ return { element = shapeOf(element), count = node.count }
140
+ elseif kind == "map" then
141
+ return { value = shapeOf(node.value :: Ir.Node) }
142
+ elseif kind == "optional" then
143
+ return shapeOf(node.inner :: Ir.Node)
144
+ elseif kind == "union" then
145
+ local branches: { [string]: any } = {}
146
+
147
+ for _, branch in node.branches :: { Ir.Field } do
148
+ branches[branch.name] = shapeOf(branch.node)
149
+ end
150
+
151
+ return { branches = branches }
152
+ end
153
+
154
+ return false
155
+ end
156
+
157
+ local slots: { [any]: Slot } = {}
158
+
159
+ --[[ Reused across ticks and channels. `Recipients.of` fills a caller-owned array for exactly
160
+ this reason: a `state` channel resolves an audience per subject per tick, and returning a
161
+ table there would allocate once per subject per frame for the life of the server. ]]
162
+ local recipients: { any } = {}
163
+
164
+ --[[ Which players this subject reaches, as a set, so the removal pass below asks one lookup per
165
+ player instead of scanning the audience. `among` used to scan: O(players) per player per
166
+ subject, which at 50 × 500 with a `select` returning the roster was 14.32 ms a tick to
167
+ conclude nothing (`bench/tick`, `select-all`). One table, cleared per subject. ]]
168
+ local marked: { [any]: boolean } = {}
169
+
170
+ local function slotOf(channel: any): Slot
171
+ local slot = slots[channel]
172
+
173
+ if not slot then
174
+ slot = {
175
+ held = {},
176
+ scratch = {},
177
+ kept = {},
178
+ stuck = {},
179
+ shape = shapeOf(channel.codec.layout.root),
180
+ }
181
+ slots[channel] = slot
182
+ end
183
+
184
+ return slot
185
+ end
186
+
187
+ --[[
188
+ A baseline must not be the store's own table.
189
+
190
+ Found by the first end-to-end run. `Replica.Data.hp = 4` mutates in place — that is what
191
+ ReplicaService's whole API does (`ReplicaService.lua:403`) — so a baseline holding a
192
+ reference to it *becomes* the new value the moment the game writes, and the next diff
193
+ compares a table against itself and finds nothing. The subject would freeze at whatever it
194
+ was when it was first sent, silently, on every client.
195
+
196
+ Charm does not have the problem because its atoms are immutable, which is exactly why a seam
197
+ that only worked for Charm would have been the wrong seam (D-3).
198
+
199
+ Copied once per subject per tick rather than once per recipient: every client that was sent
200
+ something this tick was sent the *same* value, so they can share the snapshot. A buffer field
201
+ is carried by reference and a game that mutates one in place would defeat this — noted rather
202
+ than solved, because `t.buffer` is for opaque payloads a game hands over rather than edits.
203
+
204
+ Only the schema's keys are copied (see `shapeOf`). A table where the schema says leaf is a
205
+ game bug the differ will refuse; it is carried by reference here rather than walked.
206
+ ]]
207
+ local function snapshot(value: any, shape: any): any
208
+ if type(value) ~= "table" or not shape then
209
+ return value
210
+ end
211
+
212
+ local out = {}
213
+ local fields = shape.fields
214
+
215
+ if fields then
216
+ for name, inner in fields do
217
+ local field = value[name]
218
+ out[name] = if inner and type(field) == "table" then snapshot(field, inner) else field
219
+ end
220
+
221
+ return out
222
+ end
223
+
224
+ local element = shape.element
225
+
226
+ if element ~= nil then
227
+ for index = 1, shape.count or #value do
228
+ local item = value[index]
229
+ out[index] = if element and type(item) == "table" then snapshot(item, element) else item
230
+ end
231
+
232
+ return out
233
+ end
234
+
235
+ local inner = shape.value
236
+
237
+ if inner ~= nil then
238
+ for key, item in value do
239
+ out[key] = if inner and type(item) == "table" then snapshot(item, inner) else item
240
+ end
241
+
242
+ return out
243
+ end
244
+
245
+ local branches = shape.branches
246
+
247
+ if branches then
248
+ local tag = value.tag
249
+ local chosen = branches[tag]
250
+ local carried = value.value
251
+
252
+ out.tag = tag
253
+ out.value = if chosen and type(carried) == "table" then snapshot(carried, chosen) else carried
254
+ end
255
+
256
+ return out
257
+ end
258
+
259
+ --[[
260
+ `snapshot`'s inverse, and the reason the snapshot is worth taking at all.
261
+
262
+ Every recipient that is up to date holds *the same table* — the one `send` below returned and
263
+ the slot kept — so one comparison against the current value answers for all of them. That is
264
+ the whole of the phase 8 fix: the differ used to run once per (subject, recipient) pair and
265
+ now runs once per pair that could possibly have something to write.
266
+
267
+ It has to be **at least as strict as the differ**, never less. Anything it calls unmoved is a
268
+ packet that will not be sent, so an equality looser than the schema's would be a silent
269
+ freeze. Structural over the schema's keys is the safe side: two values the differ would
270
+ encode identically — a number that snaps to the same f32 — are called *moved* here, which
271
+ costs an attempt that writes nothing. The reverse cannot happen: if every key the schema
272
+ reads compares equal then every field the differ reads compares equal, because they are the
273
+ same keys.
274
+
275
+ The one value it inherits a hole on is `buffer`, which `snapshot` carries by reference (see
276
+ above) — so a game that mutates one in place defeats this exactly as far as it already
277
+ defeated the baseline, and no further.
278
+ ]]
279
+ local function moved(current: any, last: any, shape: any): boolean
280
+ if current == last then
281
+ return false
282
+ end
283
+
284
+ if type(current) ~= "table" or type(last) ~= "table" or not shape then
285
+ return true
286
+ end
287
+
288
+ local fields = shape.fields
289
+
290
+ if fields then
291
+ for name, inner in fields do
292
+ local now, was = current[name], last[name]
293
+
294
+ if
295
+ now ~= was
296
+ and (not inner or type(now) ~= "table" or type(was) ~= "table" or moved(now, was, inner))
297
+ then
298
+ return true
299
+ end
300
+ end
301
+
302
+ return false
303
+ end
304
+
305
+ local element = shape.element
306
+
307
+ if element ~= nil then
308
+ --[[ An exact length is walked by position, because an exact array of optionals may have
309
+ holes and `#` over one is not a length. A dynamic array cannot hold optionals, so
310
+ there `#` is the length on both sides. ]]
311
+ local count = shape.count
312
+
313
+ if not count then
314
+ count = #current
315
+
316
+ if count ~= #last then
317
+ return true
318
+ end
319
+ end
320
+
321
+ for index = 1, count do
322
+ local now, was = current[index], last[index]
323
+
324
+ if
325
+ now ~= was
326
+ and (
327
+ not element
328
+ or type(now) ~= "table"
329
+ or type(was) ~= "table"
330
+ or moved(now, was, element)
331
+ )
332
+ then
333
+ return true
334
+ end
335
+ end
336
+
337
+ return false
338
+ end
339
+
340
+ local inner = shape.value
341
+
342
+ if inner ~= nil then
343
+ for key, now in current do
344
+ local was = last[key]
345
+
346
+ if
347
+ now ~= was
348
+ and (not inner or type(now) ~= "table" or type(was) ~= "table" or moved(now, was, inner))
349
+ then
350
+ return true
351
+ end
352
+ end
353
+
354
+ --[[ And the keys the baseline has that the current value does not — an entry removed
355
+ is a change, and the loop above cannot see one. ]]
356
+ for key in last do
357
+ if current[key] == nil then
358
+ return true
359
+ end
360
+ end
361
+
362
+ return false
363
+ end
364
+
365
+ local branches = shape.branches
366
+
367
+ if branches then
368
+ if current.tag ~= last.tag then
369
+ return true
370
+ end
371
+
372
+ local chosen = branches[current.tag]
373
+ local now, was = current.value, last.value
374
+
375
+ return now ~= was
376
+ and (not chosen or type(now) ~= "table" or type(was) ~= "table" or moved(now, was, chosen))
377
+ end
378
+
379
+ return false
380
+ end
381
+
382
+ --[[ Returns the snapshot it kept, so a caller sending the same subject to several recipients
383
+ copies once and hands the copy on; and whether the attempt *failed* rather than merely
384
+ wrote nothing, which is the difference between a recipient who is up to date and a change
385
+ that cannot be written at all. ]]
386
+ local function send(
387
+ channel: any,
388
+ who: any,
389
+ subject: any,
390
+ current: any,
391
+ kept: any,
392
+ shape: any
393
+ ): (any, boolean)
394
+ local base = baselines.of(who, channel, subject)
395
+
396
+ --[[ `change` answers false when this recipient is already up to date, which is the common
397
+ case and costs nothing on the wire. The baseline is only advanced when something was
398
+ actually written, or a failed encode would leave the server believing it had sent
399
+ what it had not. ]]
400
+ local written, failure = outbound.change(channel, who, subject, base, current)
401
+
402
+ if not written then
403
+ return kept, failure ~= nil
404
+ end
405
+
406
+ if current == nil then
407
+ baselines.drop(who, channel, subject)
408
+ return kept, false
409
+ end
410
+
411
+ local copy = kept or snapshot(current, shape)
412
+
413
+ baselines.keep(who, channel, subject, copy)
414
+ return copy, false
415
+ end
416
+
417
+ local function tickChannel(channel: any, everyone: { any })
418
+ local store = channel.store
419
+ local slot = slotOf(channel)
420
+ local shape = slot.shape
421
+ local present = slot.scratch
422
+ local population = #everyone
423
+
424
+ table.clear(present)
425
+
426
+ local kept = slot.kept
427
+ local stuck = slot.stuck
428
+
429
+ for _, subject in store.subjects() do
430
+ local current = store.read(subject)
431
+
432
+ if current == nil then
433
+ continue
434
+ end
435
+
436
+ present[subject] = true
437
+
438
+ local count = Recipients.of(channel.audience, subject, roster, recipients, channel, everyone)
439
+ local broadcast = count == -1
440
+ local audience = recipients
441
+
442
+ if broadcast then
443
+ --[[ Everyone: the frame's roster, read in place. It used to be copied into the
444
+ scratch so the loop below read both branches the same way, which was one
445
+ write per player per subject per tick for a list that was already in hand
446
+ (SECURITY-REPORT-M4 77). ]]
447
+ audience = everyone
448
+ count = population
449
+ end
450
+
451
+ --[[
452
+ One comparison for the whole audience, in place of one encode attempt per member
453
+ of it.
454
+
455
+ Measured before this existed, by `bench/tick.luau`: fifty players and five
456
+ hundred subjects with **nothing moving** cost 36.3 ms a tick — twice a frame at
457
+ 60 FPS — at 1,450 ns for every pair, whether or not there was anything to say. A
458
+ tenth of the world moving cost the same 36.5 ms, which is the finding in one
459
+ number: the price was the asking, not the answering.
460
+
461
+ `held` is the snapshot every settled recipient's baseline points at, so
462
+ `base == held` is a pointer comparison that proves the differ would write
463
+ nothing. It is only asked when the value itself has not moved; when it has, every
464
+ recipient is attempted as before.
465
+ ]]
466
+ local held = kept[subject]
467
+ local settled = held ~= nil and not moved(current, held, shape)
468
+
469
+ --[[
470
+ A subject no recipient could take last time — a change past the packet's two-byte
471
+ length, which the encoder refuses — is not tried again until the value moves. It used
472
+ to be attempted once per recipient per tick for ever, with the same report each
473
+ time (M4 report, finding 24). `Outbound` reports the attempt through the repeat
474
+ suppression, so the game is told once per value that cannot be sent.
475
+ ]]
476
+ local jammed = settled and stuck[subject] == held
477
+
478
+ --[[ Seeded with the snapshot rather than nil, so a client that joins into a world
479
+ at rest is handed the table everyone else already holds instead of a second one
480
+ equal to it. Two tables would split the audience into identity classes and cost
481
+ every one of them the attempt above, for ever. ]]
482
+ local copy: any = if settled then held else nil
483
+ local broken = false
484
+
485
+ if not jammed then
486
+ for index = 1, count do
487
+ local who = audience[index]
488
+
489
+ if settled and baselines.of(who, channel, subject) == held then
490
+ continue
491
+ end
492
+
493
+ local failed
494
+ copy, failed = send(channel, who, subject, current, copy, shape)
495
+ broken = broken or failed
496
+ end
497
+ end
498
+
499
+ if broken then
500
+ --[[ Kept even though nothing was sent, so the next tick can see the value has not
501
+ moved since it could not be sent. One snapshot per subject that cannot go. ]]
502
+ copy = copy or snapshot(current, shape)
503
+ stuck[subject] = copy
504
+ elseif not jammed then
505
+ stuck[subject] = nil
506
+ end
507
+
508
+ --[[ Only when something was actually sent, or could not be. A subject nobody can see
509
+ would otherwise allocate a snapshot per tick for the life of the server, and a
510
+ failed encode would record a value no client has. ]]
511
+ if copy ~= nil then
512
+ kept[subject] = copy
513
+ end
514
+
515
+ --[[
516
+ And the players who are *not* recipients but still hold a baseline for this
517
+ subject — a player who walked out of a `nearby` radius, or whose ownership
518
+ changed.
519
+
520
+ `PLAN-M4` D-4 said one leaving needs to be told to forget, and this is where
521
+ that is said. Without it the subject would sit on that client at whatever value
522
+ it had when they left, forever, and nothing on either side would know.
523
+
524
+ Skipped outright when the recipients are everyone — a broadcast, or a `select`
525
+ that returned the whole roster, which after `Recipients.of` has dropped what is
526
+ not a player and what is duplicated means the same set.
527
+ ]]
528
+ if not broadcast and count < population then
529
+ table.clear(marked)
530
+
531
+ for index = 1, count do
532
+ marked[recipients[index]] = true
533
+ end
534
+
535
+ --[[ Baseline first: a player who has never seen this subject answers in three lookups
536
+ and is most of the roster, so the set is asked only about the ones who have. ]]
537
+ for _, who in everyone do
538
+ if baselines.of(who, channel, subject) ~= nil and not marked[who] then
539
+ send(channel, who, subject, nil, nil, shape)
540
+ end
541
+ end
542
+ end
543
+ end
544
+
545
+ --[[ Subjects the store no longer lists at all — a destroyed replica, a key removed from
546
+ the table. The loop above cannot see them, so they are found by what was there last
547
+ time. ]]
548
+ for subject in slot.held do
549
+ if not present[subject] then
550
+ --[[ Dropped here rather than left to be overwritten: a store that lists a
551
+ million subjects once and never again would otherwise keep a snapshot of
552
+ each of them for the life of the server. ]]
553
+ kept[subject] = nil
554
+ stuck[subject] = nil
555
+
556
+ for _, who in everyone do
557
+ if baselines.of(who, channel, subject) ~= nil then
558
+ send(channel, who, subject, nil, nil, shape)
559
+ end
560
+ end
561
+ end
562
+ end
563
+
564
+ --[[ Swapped rather than copied, so a tick allocates no table of its own. ]]
565
+ slot.held, slot.scratch = present, slot.held
566
+ end
567
+
568
+ --[[
569
+ One channel's tick under one `pcall`, so a raise inside game code — a store, a selector,
570
+ a subject that is NaN — loses that channel's frame and not every channel's flush. `Driver`
571
+ runs this before `outbound.flush`, and until PLAN-M4-BUG phase 5 a raise here stalled every
572
+ outbound channel for every player for as long as the value persisted (M4 report, finding
573
+ 20). Per channel rather than per subject because a `pcall` with arguments costs nothing to
574
+ set up and the loop's locals would otherwise have to be threaded through a closure.
575
+ ]]
576
+ return function()
577
+ local everyone = roster.all()
578
+
579
+ for _, channel in channels() do
580
+ local ok, failure = pcall(tickChannel, channel, everyone)
581
+
582
+ if not ok then
583
+ Observer.emit(
584
+ channel.qualified,
585
+ nil,
586
+ "replicate",
587
+ `the tick raised inside game code, so this channel was skipped this frame: {tostring(
588
+ failure
589
+ )}`,
590
+ 0
591
+ )
592
+ end
593
+ end
594
+ end
595
+ end
596
+
597
+ return Tick