@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,1508 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Inbound
6
+
7
+ The receive half. Walks each arriving batch, decides what to admit, and dispatches what
8
+ survives.
9
+
10
+ Internal.
11
+ ]=]
12
+
13
+ --[[
14
+ Ten stages can refuse a packet here (`Observer.Stage`), which is why `nw.observe` reports a
15
+ stage rather than a boolean. `RESEARCH §3-G6`, as corrected, records that the only surveyed
16
+ library to attempt reporting rejections is Warp and that it gets it wrong, and `§3.7-K` records
17
+ what that costs: Warp blackholes a player whose packet fails and nothing anywhere says so.
18
+
19
+ Nothing on this path raises. The bytes came from a peer, so every failure — including one thrown
20
+ by the game's own handler — is caught and reported, because a batch is other players' traffic
21
+ and one bad packet must not take it (`DESIGN-API.md` G4, G5).
22
+ ]]
23
+
24
+ local Baseline = require("../replication/Baseline")
25
+ local Batch = require("./Batch")
26
+ --[[ Aliased, because this module already exports a type named `Config` for its own constructor
27
+ options and two `Config`s in one file is a reading hazard even where Luau permits it. ]]
28
+ local Settings = require("../api/Config")
29
+ local Context = require("../api/Context")
30
+ local Observer = require("../api/Observer")
31
+ local Protocol = require("../api/Protocol")
32
+ local Query = require("./Query")
33
+
34
+ local Inbound = {}
35
+
36
+ --[[
37
+ Blink's queue for a listener-less event is `table.insert` with no bound: past 256 it warns on
38
+ every insert and keeps inserting, so a missing listener becomes warn spam plus unbounded memory
39
+ (`Generator/init.luau:413-418`, `RESEARCH §3.7-H`). Zap uses read and write cursors and grows by
40
+ doubling, which is better and is what this takes — with one change.
41
+
42
+ **A full queue drops the oldest and says so.** Growing without bound turns a forgotten `:listen`
43
+ into a memory leak that looks like a networking library, and the packets worth keeping when a
44
+ handler finally attaches are the recent ones, not the ones from a minute ago.
45
+ ]]
46
+ --[[ A default rather than a constant since M3: `nw.configure` moves it, and it is read when a
47
+ queue is first created so a game that raises it before declaring gets the queue it asked for.
48
+ Stored on the queue itself, because changing the limit must not desynchronise the ring
49
+ arithmetic of a queue that already exists. ]]
50
+ local DEFAULT_QUEUE_CAPACITY = 256
51
+
52
+ --[[ Constant like every other refusal reason, and reached only by an endpoint that was handed a
53
+ replicated channel without anywhere to keep what the other end has — which is a wiring mistake
54
+ rather than anything a peer can provoke. ]]
55
+ local NO_BASELINES = "a replicated packet arrived at an endpoint with no baseline store, so there "
56
+ .. "is nothing to fold it into. Pass `baselines` to Inbound.new"
57
+
58
+ --[[ A peer asked for a channel that is not replicated, or is not a channel at all. Constant,
59
+ because it is the one thing about replication a hostile peer can send at will. ]]
60
+ local NOT_REPLICATED = "a peer asked to be resynchronised on an id that is not a replicated channel"
61
+
62
+ --[[ Constant because a flood is exactly when it is said. It used to carry `dropped {n} so far`,
63
+ which allocated a string per dropped packet to print a number three times — the repeat
64
+ suppression caps the console at three lines per stage, and `nw.observe` sees every one and can
65
+ count them itself (M3 phase 9). ]]
66
+ local QUEUE_FULL = "no handler is attached and the queue is full, so the oldest was dropped. "
67
+ .. "Attach a :listen, or raise the queueCapacity limit"
68
+
69
+ type Queue = {
70
+ values: { any },
71
+ senders: { any },
72
+ read: number,
73
+ count: number,
74
+ capacity: number,
75
+ dropped: number,
76
+ }
77
+
78
+ export type Config = {
79
+ --[[ The channel with that wire id, or nil. ]]
80
+ resolve: (id: number) -> any,
81
+ --[[ nil to accept the packet, or a reason to refuse it. Runs before the payload is decoded. ]]
82
+ admit: (channel: any, sender: any?, bytes: number) -> string?,
83
+ --[[ Server-side handlers receive a context; client-side ones receive the payload alone. ]]
84
+ isServer: boolean,
85
+ --[[ Request/response, when this endpoint does any. One record rather than four callbacks: an
86
+ endpoint either serves queries or refuses them, and there is no half of it that makes
87
+ sense on its own. Absent, a query packet is reported and dropped. ]]
88
+ queries: Query.Queries?,
89
+ --[[ Who has agreed on the declarations. Absent, every peer is taken at its word — which is what
90
+ a test that is not about the handshake wants. ]]
91
+ agreement: Protocol.Agreement?,
92
+ --[[ What each peer has, per replicated subject. On a client this is what arrived; on a server
93
+ it is what was sent, and the same store serves both because "the other end has this" is
94
+ one fact seen from two directions. Absent, a replicated packet is reported and dropped. ]]
95
+ baselines: Baseline.Baseline?,
96
+ --[[ Called when a replicated packet was refused, which means this endpoint's picture of that
97
+ channel is now unknowable. The driver wires it to the packet that asks for everything
98
+ again; a test that does not care leaves it out and the baseline is simply cleared. ]]
99
+ desynced: ((channel: any) -> ())?,
100
+ }
101
+
102
+ export type Inbound = {
103
+ --[[ `{ unknown }`, because the sidecar is wire data and the read phase is what checks it
104
+ (M4 report finding 50). ]]
105
+ receive: (packed: buffer, instances: { unknown }?, sender: any?) -> (),
106
+ drain: (channel: any) -> (),
107
+ tick: () -> (),
108
+ forget: (sender: any) -> (),
109
+ --[[ How many pending lists are parked in the free list right now. For `bench/residue`, which
110
+ counts the pool rather than weighing it: lune cannot force a collection, so what the pool
111
+ retains is not otherwise observable. ]]
112
+ pooled: () -> number,
113
+ }
114
+
115
+ --[[ `pcall` of a function whose return pack is empty is typed as returning `boolean` alone, so the
116
+ error cannot be destructured out of it. The alias widens the pack without changing what runs,
117
+ and is hoisted so neither guard builds one per batch. ]]
118
+ local read: (...any) -> ...any = Batch.read
119
+
120
+ --[[ `xpcall` with a shared handler allocates no closure per call. A traceback is worth the string
121
+ because a handler error is a game bug and the line is the whole of the diagnosis. ]]
122
+ local function traceback(message: any): string
123
+ return `{tostring(message)}\n{debug.traceback("", 2)}`
124
+ end
125
+
126
+ --[[ A digest whose body does not parse inside its declared length, or claims more than a
127
+ declaration can hold. One string, for the same reason as the next one. ]]
128
+ local MALFORMED_DIGEST = "a digest's body ends before the namespaces it counts do, or claims more "
129
+ .. "namespaces or a longer name than any declaration can hold"
130
+
131
+ --[[ One string for every report of its kind, because a flood of yielding handlers is a flood, and
132
+ a reason built per packet is a reason that differs per packet (`CLAUDE.md` §9, "count it"). ]]
133
+ local YIELDED_ACROSS_PACKET = "the handler yielded, and another packet of this player was dispatched "
134
+ .. "before it resumed, so the ctx it held was refreshed under it and every read after the yield "
135
+ .. "was that later request's. Copy the fields you need before yielding — local player = "
136
+ .. "ctx.player — or declare the channel a query, whose handler may yield on a thread of its own"
137
+
138
+ --[[
139
+ What a `replicate` handler is given **is** this endpoint's baseline, and until M4 phase 8 it
140
+ could be written to.
141
+
142
+ `Delta`'s merger returns the value and whether it is a new one, so a subtree the patch did not
143
+ touch comes back by reference — and that sharing is the whole reason a twelve-field subject with
144
+ one field moved costs three bytes. The consequence nobody wrote down is that the table handed to
145
+ `:listen` is the same table `store.keep` records. The habit every state library teaches —
146
+ `Replica.Data.hp = 4`, a client-side prediction, `value.hp -= 1` — writes straight into it, and
147
+ the next patch carries only the fields the server changed while the rest are read back out of the
148
+ corrupted base. Measured: `seen.hp = 3`, then a gold-only patch, and the server says hp=10 while
149
+ the client sees hp=3 — silently, and for ever (M4 report).
150
+
151
+ A defensive copy is the other way out and it is the wrong one: it would have to be deep, it would
152
+ run per subject per patch, and it is precisely the sharing thrown away to protect it. Freezing
153
+ allocates nothing and turns a silent corruption into a raise on the line that caused it.
154
+
155
+ It is also nearly free for the same reason the hazard exists. An untouched subtree is already
156
+ frozen by the patch that built it, so the walk stops there and visits only what this patch made —
157
+ `table.clone` hands back an unfrozen copy, which is what lets the merger keep working above.
158
+
159
+ `table.freeze` is shallow in Luau, hence the recursion. A `t.buffer` field is carried by
160
+ reference and cannot be frozen at all, which is the same hole `Tick.snapshot` documents from the
161
+ sending end.
162
+ ]]
163
+ local function harden(value: any)
164
+ if type(value) ~= "table" or table.isfrozen(value) then
165
+ return
166
+ end
167
+
168
+ for _, inner in value do
169
+ harden(inner)
170
+ end
171
+
172
+ table.freeze(value)
173
+ end
174
+
175
+ --[[
176
+ A batch is read to completion **before** anything is dispatched, and that is a correctness
177
+ requirement rather than a tidiness one.
178
+
179
+ A handler is game code and may yield. Roblox runs each remote callback on its own coroutine, so
180
+ a yield lets the next batch in — and the decoder's cursor is global state (`src/codec/Buffer`,
181
+ which is global on purpose so a write costs one upvalue rather than a parameter chain). Reading
182
+ and dispatching in one pass therefore means: handler yields, the next batch calls `beginRead`,
183
+ and when the first resumes it walks the *second* batch's bytes while attributing them to the
184
+ first batch's sender.
185
+
186
+ That is not a crash. It is one player's packets delivered as another player's, which is the
187
+ worst shape a networking bug can take.
188
+
189
+ Reading first closes it structurally. The read phase calls no game code and therefore cannot
190
+ yield; by the time a handler runs, this batch's bytes are already values and nothing shared is
191
+ still being consumed. Each pending entry carries its own sender, so nothing is attributed by
192
+ timing.
193
+ ]]
194
+ --[[
195
+ `calls` and `statuses` carry the query correlation through the same wait.
196
+
197
+ A reply is delivered on the caller's side by resuming a parked thread, and that thread is game
198
+ code that may yield — so resuming it during the read phase would reintroduce the exact bug this
199
+ structure exists to prevent, one packet later. A reply waits its turn in the pending list like
200
+ everything else.
201
+
202
+ `statuses` is `-1` for anything that is not a reply, never nil: a stale positive left over from
203
+ a previous batch would make an ordinary packet dispatch as somebody's answer.
204
+ ]]
205
+ type Pending = {
206
+ channels: { any },
207
+ senders: { any },
208
+ values: { any },
209
+ --[[ Which replicated value this is. Its own array rather than packed into `values`, because
210
+ packing would allocate a table per packet on the one path whose whole argument is that it
211
+ does not. Empty for every other class. ]]
212
+ subjects: { any },
213
+ sizes: { number },
214
+ calls: { number },
215
+ statuses: { number },
216
+ count: number,
217
+ }
218
+
219
+ local function emptyPending(): Pending
220
+ return {
221
+ channels = {},
222
+ senders = {},
223
+ values = {},
224
+ subjects = {},
225
+ sizes = {},
226
+ calls = {},
227
+ statuses = {},
228
+ count = 0,
229
+ }
230
+ end
231
+
232
+ --[=[
233
+ @within Inbound
234
+ @function new
235
+ @param config Config
236
+ @return Inbound
237
+ ]=]
238
+ function Inbound.new(config: Config): Inbound
239
+ local resolve = config.resolve
240
+ local admit = config.admit
241
+ local isServer = config.isServer
242
+ local queries = config.queries
243
+ local baselines = config.baselines
244
+ local onDesync = config.desynced
245
+ local agreement = config.agreement
246
+
247
+ --[[
248
+ The sender of the batch currently being **read**.
249
+
250
+ Safe as shared state precisely because of the split above: the read phase runs no game code,
251
+ so it cannot yield, so there is no window in which another batch can change this while it is
252
+ still being used. It is never read after a handler has run.
253
+ ]]
254
+ local sender: any = nil
255
+
256
+ local queues: { [any]: Queue } = {}
257
+
258
+ --[[
259
+ Pending lists, held by whoever is walking one.
260
+
261
+ ~~Indexed by re-entrancy depth.~~ **That assumed claims and releases nest, and they do not.**
262
+ Roblox resumes remote callbacks in whatever order their waits complete, not in nesting order,
263
+ so a batch that yielded second and finished first put the depth back while another loop was
264
+ still walking the list at that depth — and the next batch to arrive claimed that list out
265
+ from under it, reset its count, and overwrote the entries it had not reached. Silent loss,
266
+ then `attempt to index nil with 'handler'` on the receive path from ordinary traffic
267
+ (`PLAN-M3` phase 9; found by an external review, reproduced in `transport_runtime`).
268
+
269
+ A free list has no order to get wrong. A list is taken by a `receive`, `drain` or `tick` that
270
+ is going to walk it, and given back when that walk ends; two overlapping walks hold different
271
+ lists because neither has returned its own. The high-water mark is the number of dispatches
272
+ in flight at once, which is what the depth counter was reaching for and could not express.
273
+
274
+ At one batch a frame — every ordinary frame — this is still the same seven arrays reused
275
+ forever and still costs nothing.
276
+
277
+ Capped on the way back in. The pool used to keep every list it ever needed, so the most walks
278
+ ever in flight at once — a burst of yielding handlers — set its size for the life of the
279
+ server, each list seven arrays sized by the largest batch it carried (M4-1; `bench/residue`
280
+ counts it). Past the cap a returning list is dropped for the collector, and the walk that
281
+ needs one more than the cap allocates it: game code that yields in a handler pays for the
282
+ overlap it creates, once per overlap, rather than the server keeping the peak.
283
+ ]]
284
+ local POOLED = 8
285
+ local free: { Pending } = { emptyPending() }
286
+
287
+ --[[
288
+ At most one `intent` per player per tick reaches the handler. Stale input has no value, so an
289
+ attacker who fills the rate budget cannot convert it into per-packet server work — and that
290
+ is what makes `rate` on an intent a number that means something rather than a cap nobody
291
+ hits (`DESIGN-API.md` §3).
292
+
293
+ This is the one place merging is semantically safe. `RESEARCH §3.7-E` argues batching
294
+ unreliable traffic is a semantic error in general, because losing one datagram loses N
295
+ events; an intent is the exception, because losing a superseded input costs nothing.
296
+ ]]
297
+ local coalescedValue: { [any]: { [any]: any } } = {}
298
+ local coalescedBytes: { [any]: { [any]: number } } = {}
299
+
300
+ local function report(channel: any, who: any?, stage: Observer.Stage, reason: string, bytes: number)
301
+ Observer.emit(if channel then channel.qualified else "?", who, stage, reason, bytes)
302
+ end
303
+
304
+ --[[
305
+ Everything this endpoint believed about a replicated channel, given up.
306
+
307
+ A change is only meaningful against the value it was computed from, so a change that did not
308
+ arrive — refused at any stage, for any reason — makes every change after it unreadable. There
309
+ is no partial recovery and no way to notice later: the values would simply be wrong.
310
+
311
+ So the baseline goes and the other end is asked to start again. `PLAN-M4` D-2 called this a
312
+ break detector and expected a sequence number on the wire to find the gap; there is none,
313
+ because **this endpoint already knows** — it is the one that refused the packet.
314
+ ]]
315
+ local function desync(channel: any)
316
+ --[[
317
+ **Only the end that receives changes gives one up**, and the asymmetry is a bound rather
318
+ than a tidiness.
319
+
320
+ Replication flows server to client, so the client is the one that can lose a change. On
321
+ the server a packet on a replicated id is a client sending something it must not — G6
322
+ refuses it before decode — and the server's baseline is authoritative: nothing was lost.
323
+ Clearing it there would let any peer force a full resend of everything it can see with
324
+ one malformed byte, which is a cheaper amplifier than the resync packet that at least
325
+ has to name a real channel.
326
+ ]]
327
+ if isServer then
328
+ return
329
+ end
330
+
331
+ local store = baselines
332
+
333
+ if store then
334
+ store.desync(sender, channel)
335
+ end
336
+
337
+ if onDesync then
338
+ onDesync(channel)
339
+ end
340
+ end
341
+
342
+ --[[
343
+ The policy, and whether it said yes.
344
+
345
+ Factored out of `call` because `serveQuery` needs the identical decision on a different
346
+ thread, and D-1 and D-2 are exactly the kind of rule that gets one of its two copies fixed.
347
+ The narrowed value is returned rather than assigned through, so neither caller can forget
348
+ which of the two things a verdict carries.
349
+ ]]
350
+ local function decide(channel: any, who: any?, ctx: any, value: any, bytes: number): (boolean, any)
351
+ --[[ Annotated because it is read off an `any` channel and truth-tested, which narrows to a
352
+ type that is not callable. ]]
353
+ local authorize: ((any, any) -> any)? = channel.authorize
354
+
355
+ if not authorize then
356
+ return true, nil
357
+ end
358
+
359
+ --[[
360
+ A policy is game code, and game code does not get the batch.
361
+
362
+ M2 wrapped the handler and left this call bare, which made the authorization layer a
363
+ denial-of-service surface: one input that trips a game's policy takes every packet
364
+ batched behind it, and the queue drain crosses senders, so those packets are not
365
+ necessarily the same player's. `RESEARCH §3.8-R` is this failure at the codec layer,
366
+ which netweave already avoids; `PLAN-M3` D-1 is the same discipline applied to the
367
+ game's own code.
368
+
369
+ `xpcall` with the module-level `traceback` handler allocates no closure per call.
370
+ ]]
371
+ local generation = Context.generation(who)
372
+ local ran, verdict = xpcall(authorize, traceback, ctx, value)
373
+
374
+ --[[ A check that yielded across another packet of this player read a refreshed record after
375
+ the yield; the policy's own docstring forbids the yield, and this is where breaking that
376
+ stops being silent. One integer compare, one constant reason (`PLAN-M5` D-5). ]]
377
+ if Context.generation(who) ~= generation then
378
+ report(channel, who, "authorize", YIELDED_ACROSS_PACKET, bytes)
379
+ end
380
+
381
+ if not ran then
382
+ report(channel, who, "authorize", `the policy raised: {tostring(verdict)}`, bytes)
383
+ return false, nil
384
+ end
385
+
386
+ --[[
387
+ `ok == true`, not truthy, and only off a table.
388
+
389
+ A policy that returns nothing is a policy someone forgot to finish, and the safe
390
+ reading of an unfinished policy is "no" — this is the one place in netweave where a
391
+ shrug must not mean yes. The pre-fix check was `if not allowed`, which admitted
392
+ `ok = "yes"` and raised outright on `nil` (`PLAN-M3` D-2).
393
+
394
+ Read out of the shared verdict record before anything else can overwrite it
395
+ (`src/api/Policy.luau`).
396
+ ]]
397
+ local shaped = if type(verdict) == "table" then verdict else nil
398
+
399
+ if shaped == nil or shaped.ok ~= true then
400
+ local reason = if shaped then shaped.reason else nil
401
+
402
+ report(
403
+ channel,
404
+ who,
405
+ "authorize",
406
+ reason
407
+ or (if shaped then "denied" else `the policy returned {typeof(verdict)}, not a verdict`),
408
+ bytes
409
+ )
410
+
411
+ return false, nil
412
+ end
413
+
414
+ return true, shaped.value
415
+ end
416
+
417
+ --[[
418
+ One request, from the policy to the answer, on a thread of its own.
419
+
420
+ `nw.query` is the only class whose handler is allowed to yield, and that permission forces
421
+ everything unusual here. It runs off the dispatch loop, so a datastore read does not hold up
422
+ the rest of the batch or the frame's flush; it gets a detached context, because the shared
423
+ per-player one is refreshed out from under a handler that yields; and every exit writes a
424
+ reply, because the caller is parked on a deadline and silence costs it the whole timeout.
425
+
426
+ The query record is a parameter rather than an upvalue so that the non-nil narrowing survives
427
+ into it — this is spawned from a place where the field is still `Queries?`.
428
+ ]]
429
+ local function serveQuery(
430
+ serving: Query.Queries,
431
+ channel: any,
432
+ who: any,
433
+ value: any,
434
+ bytes: number,
435
+ id: number
436
+ )
437
+ local ctx = Context.detached(who, channel.qualified)
438
+ local allowed, narrowed = decide(channel, who, ctx, value, bytes)
439
+
440
+ if not allowed then
441
+ serving.answer(channel, who, id, Batch.REFUSED, nil)
442
+ return
443
+ end
444
+
445
+ if narrowed ~= nil then
446
+ value = narrowed
447
+ end
448
+
449
+ local handler: (...any) -> ...any = channel.handler
450
+
451
+ --[[ Attached when the packet was read and gone by the time this ran. `:handle` cannot be
452
+ detached, but a namespace can be reset out from under an in-flight call, and calling nil
453
+ here would raise on a thread with nobody to catch it. ]]
454
+ if not handler then
455
+ serving.answer(channel, who, id, Batch.UNHANDLED, nil)
456
+ return
457
+ end
458
+
459
+ local ok, result = xpcall(handler, traceback, ctx, value)
460
+
461
+ if not ok then
462
+ report(channel, who, "handler", tostring(result), bytes)
463
+ serving.answer(channel, who, id, Batch.FAILED, nil)
464
+ return
465
+ end
466
+
467
+ serving.answer(channel, who, id, Batch.OK, result)
468
+ end
469
+
470
+ local function call(channel: any, who: any?, value: any, bytes: number, id: number, subject: any?)
471
+ --[[ Annotated so `xpcall` resolves: a handler read off an `any` channel is narrowed to "not
472
+ false or nil" by the caller's check, which is not a callable type. ]]
473
+ local handler: (...any) -> ...any = channel.handler
474
+
475
+ if not isServer then
476
+ --[[ A client's inbound is the server's outbound, and the server is not a peer to be
477
+ checked. No context, no policy — the payload alone, and for a replicated channel
478
+ the subject in front of it, because the client keeps one value per subject and a
479
+ handler that could not tell them apart would be useless. A `nil` value there is the
480
+ subject going away. ]]
481
+ --[[ Two statements rather than an `if` expression, which yields one value where this
482
+ needs two. ]]
483
+ local ok, failure
484
+
485
+ if channel.class == "replicate" then
486
+ ok, failure = xpcall(handler, traceback, subject, value)
487
+ else
488
+ ok, failure = xpcall(handler, traceback, value)
489
+ end
490
+
491
+ if not ok then
492
+ report(channel, nil, "handler", tostring(failure), bytes)
493
+ end
494
+
495
+ return
496
+ end
497
+
498
+ if channel.class == "query" then
499
+ local serving = queries
500
+
501
+ if not serving then
502
+ report(channel, who, "handler", "this endpoint does not serve queries", bytes)
503
+ return
504
+ end
505
+
506
+ --[[ The slot is taken here, synchronously, rather than on the spawned thread. Taking it
507
+ there would run the check after the thread it exists to prevent. ]]
508
+ if serving.enter(channel, who, id) then
509
+ serving.spawn(serveQuery, serving, channel, who, value, bytes, id)
510
+ end
511
+
512
+ return
513
+ end
514
+
515
+ local ctx = Context.acquire(who, channel.qualified)
516
+ local allowed, narrowed = decide(channel, who, ctx, value, bytes)
517
+
518
+ if not allowed then
519
+ Context.release(who)
520
+ return
521
+ end
522
+
523
+ if narrowed ~= nil then
524
+ value = narrowed
525
+ end
526
+
527
+ local generation = Context.generation(who)
528
+ local ok, failure = xpcall(handler, traceback, ctx, value)
529
+
530
+ if not ok then
531
+ report(channel, who, "handler", tostring(failure), bytes)
532
+ end
533
+
534
+ --[[
535
+ The handler yielded, and while it was parked another packet of the same player was
536
+ dispatched: `acquire` refreshed the shared record and `release` moved its generation, so
537
+ every `ctx` read the handler made after resuming was that later request's. The batch
538
+ survives — reading and dispatching are separate passes for this reason — and until now
539
+ the corruption did too, silently, everywhere the Studio guard is not. Reported with a
540
+ constant reason so a flood of them allocates nothing (`CLAUDE.md` §9, "count it").
541
+ ]]
542
+ if Context.generation(who) ~= generation then
543
+ report(channel, who, "handler", YIELDED_ACROSS_PACKET, bytes)
544
+ end
545
+
546
+ Context.release(who)
547
+ end
548
+
549
+ --[[
550
+ Hand a pending list to the caller, run it dry, and give it back.
551
+
552
+ The entries are cleared as they are dispatched rather than afterwards, so a handler that
553
+ raises — already caught, but still — cannot leave a value referenced by a list that will be
554
+ reused for the next frame.
555
+ ]]
556
+ local function claim(): Pending
557
+ local taken: Pending? = table.remove(free)
558
+ local list = taken or emptyPending()
559
+
560
+ list.count = 0
561
+ return list
562
+ end
563
+
564
+ local function walk(list: Pending)
565
+ local channels = list.channels
566
+ local senders = list.senders
567
+ local values = list.values
568
+ local subjects = list.subjects
569
+ local sizes = list.sizes
570
+ local calls = list.calls
571
+ local statuses = list.statuses
572
+ local count = list.count
573
+
574
+ list.count = 0
575
+
576
+ for index = 1, count do
577
+ local channel = channels[index]
578
+ local who = senders[index]
579
+ local value = values[index]
580
+ local subject = subjects[index]
581
+ local id = calls[index]
582
+ local status = statuses[index]
583
+
584
+ channels[index] = nil
585
+ senders[index] = nil
586
+ values[index] = nil
587
+ subjects[index] = nil
588
+
589
+ --[[ A status of zero or more is a reply, and a reply resumes a thread instead of calling
590
+ a handler. Anything else — including a query *request* — goes to `call`. ]]
591
+ if status >= 0 then
592
+ local waiting = queries
593
+
594
+ --[[ Not guarded: `answered` resumes a thread, and a resume returns false rather
595
+ than raising. ]]
596
+ if waiting then
597
+ waiting.answered(channel, id, status, value)
598
+ end
599
+ else
600
+ --[[
601
+ Guarded per entry, not only per batch. `call` runs the policy and the handler
602
+ under `xpcall`, but the code between those two — the call-id record, the
603
+ context, the reply — is not, and a raise there used to reach `dispatch`'s one
604
+ `pcall`, which protects the list and not the entries behind the one that raised:
605
+ the rest of the batch was dropped with a report naming no channel and no player
606
+ (M4 report, finding 32). G5 is per packet in the read phase; this makes it per
607
+ packet here too. `pcall` with arguments allocates no closure.
608
+ ]]
609
+ local ok, failure = pcall(call, channel, who, value, sizes[index], id, subject)
610
+
611
+ if not ok then
612
+ report(channel, who, "handler", `dispatch raised: {tostring(failure)}`, sizes[index])
613
+ end
614
+ end
615
+ end
616
+
617
+ --[[
618
+ The list goes back **after** the loop, not before it.
619
+
620
+ Returning it first looks harmless — the entries have already been read into locals — and
621
+ is not: a handler that yields lets the next batch in, and that batch would then `claim`
622
+ this very list and overwrite the entries this loop has not reached yet. The failure is
623
+ silent and size-dependent, which is why it survived a first test: the interleaved batch
624
+ only corrupts the outer one when it is at least as long.
625
+
626
+ A raise inside the loop leaks one list rather than corrupting one, which is the trade the
627
+ free list buys over the counter it replaced — and `dispatch` below takes even that back.
628
+ ]]
629
+ end
630
+
631
+ --[[
632
+ Guarantee G4, structurally.
633
+
634
+ `walk` calls game code through `call`, which `xpcall`s the policy and the handler, so the
635
+ raises anyone thought of are already values. The two that broke G4 were the ones nobody
636
+ thought of — a table in the sidecar, and a pooled list two loops both believed they owned —
637
+ and both are fixed above. What is not fixed by fixing them is that the *next* one inherits
638
+ the same shape: a raise here would leave the list unreturned and the rest of the batch
639
+ undelivered with nothing said.
640
+
641
+ So the claim stops resting on inspection. One `pcall` per dispatch, the list returned either
642
+ way, and a raise that reaches here is reported like any other failure rather than escaping
643
+ into the remote callback that called it. `PLAN-M3` phase 9.
644
+ ]]
645
+ local attempt: (...any) -> ...any = walk
646
+
647
+ local function dispatch(list: Pending)
648
+ local ok, failure = pcall(attempt, list)
649
+
650
+ if #free < POOLED then
651
+ table.insert(free, list)
652
+ end
653
+
654
+ if not ok then
655
+ report(nil, nil, "handler", `dispatch raised: {tostring(failure)}`, 0)
656
+ end
657
+ end
658
+
659
+ --[[
660
+ A channel nobody is listening to yet. The packets are kept rather than dropped, because a
661
+ handler attached one frame late is an ordering accident and losing the traffic to it is a
662
+ bug the game cannot see.
663
+ ]]
664
+ local function enqueue(channel: any, who: any?, value: any, bytes: number)
665
+ local queue = queues[channel]
666
+
667
+ if not queue then
668
+ local capacity = Settings.limitOf("queueCapacity") or DEFAULT_QUEUE_CAPACITY
669
+
670
+ queue = {
671
+ values = table.create(capacity),
672
+ senders = table.create(capacity),
673
+ capacity = capacity,
674
+ read = 0,
675
+ count = 0,
676
+ dropped = 0,
677
+ }
678
+
679
+ queues[channel] = queue
680
+ end
681
+
682
+ if queue.count == queue.capacity then
683
+ --[[ Drop the oldest and step the read cursor past it. Reported once per drop so a
684
+ forgotten `:listen` is visible rather than merely quiet. ]]
685
+ queue.read = (queue.read + 1) % queue.capacity
686
+ queue.count -= 1
687
+ queue.dropped += 1
688
+
689
+ report(channel, who, "queue", QUEUE_FULL, bytes)
690
+ end
691
+
692
+ local slot = (queue.read + queue.count) % queue.capacity
693
+ queue.values[slot + 1] = value
694
+ queue.senders[slot + 1] = who
695
+ queue.count += 1
696
+ end
697
+
698
+ --[[ One string per class rather than one per packet.
699
+
700
+ This is the reason a hostile peer can provoke most cheaply — send anything at all on a
701
+ `state` or `event` id and every packet in the batch lands here — so building it per refusal
702
+ would have made the check that stops the flood the thing the flood costs. Seven classes, and
703
+ `isServer` is fixed for the life of this `Inbound`, so the table cannot grow. ]]
704
+ local directionReasons: { [string]: string } = {}
705
+
706
+ local function directionReason(class: string): string
707
+ local reason = directionReasons[class]
708
+
709
+ if not reason then
710
+ reason = `{class} is sent by the {if isServer then "server" else "client"}, so nothing `
711
+ .. `may arrive on it here — netweave guarantee G6, which the declaration enforces at `
712
+ .. `analysis and this enforces on the wire`
713
+ directionReasons[class] = reason
714
+ end
715
+
716
+ return reason
717
+ end
718
+
719
+ --[[ The list the read phase is filling. Set for the duration of one `Batch.read`, which cannot
720
+ yield, for the same reason `sender` is safe. ]]
721
+ local filling: Pending = emptyPending()
722
+
723
+ --[[ Set when the pending set fills, cleared when a batch starts. Not a field on `Pending`
724
+ because a batch that arrives inside another batch's dispatch has its own, and the outer
725
+ one's state is restored around it the way `sender` and `filling` are. ]]
726
+ local full = false
727
+
728
+ --[[
729
+ How long a peer waits between resyncs that are acted on, in `tick` calls — frames, where the
730
+ driver runs it. Half a second at 60 Hz, which is the trade written out: an honest client's
731
+ *first* ask is always honoured immediately, so this is only ever the gap before a *second*
732
+ one, and a second one inside half a second is either a peer with a very bad connection or a
733
+ peer trying to make the server work. The first gets its state a frame or two later; the
734
+ second gets a sixtieth of what it asked for.
735
+ ]]
736
+ --[[ Read from `Config` at each use rather than once: the limit takes effect immediately, which
737
+ is what a game reaching for it under attack needs. ]]
738
+ local function resyncWindow(): number
739
+ return Settings.limitOf("resyncTicks")
740
+ end
741
+
742
+ --[[ Constant, so a peer asking every frame costs a report and no allocation: §9's "nothing on
743
+ the receive path is silent" — a deferred ask used to return without a word, so a peer
744
+ asking ninety times in ninety frames was invisible to `nw.observe` (M4-1). ]]
745
+ local RESYNC_DEFERRED = "a resync arrived inside the window since the last one was acted on; it is "
746
+ .. "remembered and honoured when the window closes. A peer asking every frame is either on a "
747
+ .. "very bad connection or trying to make this server work; nw.configure({ limits = { resyncTicks "
748
+ .. "= n } }) widens the window"
749
+
750
+ local ticks = 0
751
+
752
+ --[[ Per sender, the tick each channel's resync was last acted on; and per channel, the senders
753
+ who asked again too soon. Two shapes because they are walked from opposite ends: the first
754
+ by a packet that names a sender, the second by `tick`, which walks everything owed. ]]
755
+ local resyncs: { [any]: { [any]: number } } = {}
756
+ local owed: { [any]: { [any]: boolean } } = {}
757
+
758
+ --[[ What the game configured, and what this endpoint enforces — the same number on a server and
759
+ no ceiling at all on a client. `refreshCeiling` below says why. Both are kept because the
760
+ reason strings quote the configured one, and a client that reports nothing still has to be
761
+ able to say what the limit was if it ever does. ]]
762
+ local configuredCeiling = Settings.limitOf("pendingPerBatch")
763
+ local pendingCeiling = if isServer then configuredCeiling else math.huge
764
+
765
+ --[[
766
+ The two reasons whose only variable is the ceiling, built when it moves rather than per
767
+ refusal.
768
+
769
+ An external review measured a 12,000-packet flood producing 11,744 distinct reason strings,
770
+ against an `Observer` and a `Budget` whose comments both promise a refused packet allocates
771
+ nothing (M3 phase 9). The promise was true of them and false here, which is the worst place
772
+ for it to be false: the flood is the case the limit exists for, so the limit was paying
773
+ garbage in proportion to the attack it was refusing.
774
+
775
+ The ceiling changes only when the game reconfigures, so this is one interpolation per
776
+ `nw.configure` rather than one per dropped packet.
777
+ ]]
778
+ local ceilingReason = ""
779
+ local ceilingReplyReason = ""
780
+
781
+ --[[
782
+ **The ceiling is the server's, and applying it on a client is what broke replication at scale.**
783
+
784
+ The bound exists because the batch's size is chosen by an *untrusted* peer (`PLAN-M3` D-6). On
785
+ a client the peer is the server: the batch is what this game chose to send, already bounded at
786
+ the other end by this very limit, and refusing its tail saves no memory an attacker could have
787
+ claimed — it drops traffic the game asked for, and reports it against a peer that cannot be
788
+ asked to send less.
789
+
790
+ On a replicated channel it costs more than the tail. Past the ceiling the client refuses, a
791
+ refused change gives up the channel, and giving up clears the baselines it applied earlier in
792
+ the same batch; the resync then makes the server clear what it believed, and the next tick
793
+ sends the same oversized batch again. Measured with the real tick at the default limits before
794
+ this line existed:
795
+
796
+ | subjects visible to one client | every frame |
797
+ |---|---|
798
+ | 256 | frame 1 converges, then 0 bytes |
799
+ | 257 | 1,543 B down, 5 B up, mirror stuck at 256, **both sides holding nothing** |
800
+ | 300 | 1,801 B down, 177 B up, 44 refusals and 44 resyncs, forever |
801
+
802
+ One subject over the limit was a channel that never worked, and the suite could not see it
803
+ because `tests/replication_runtime.luau` restored the limit after a single frame.
804
+
805
+ This is the same asymmetry `Driver` already writes down for `Baseline` — bounded on the
806
+ server, unbounded on the client — and for the same reason.
807
+ ]]
808
+ local function refreshCeiling()
809
+ local limit = Settings.limitOf("pendingPerBatch")
810
+
811
+ if limit == configuredCeiling and ceilingReason ~= "" then
812
+ return
813
+ end
814
+
815
+ configuredCeiling = limit
816
+ pendingCeiling = if isServer then limit else math.huge
817
+ ceilingReason = `batch holds more than {limit} packets; the rest were dropped`
818
+ ceilingReplyReason = `the answer arrived in a batch holding more than {limit} packets and `
819
+ .. `was dropped`
820
+ end
821
+
822
+ refreshCeiling()
823
+
824
+ --[[ A query request that was refused before it ever reached a handler. The caller is already
825
+ parked on a deadline, so the refusal goes back as a code rather than being left for the
826
+ timeout to discover — the difference between a call that fails in a frame and one that
827
+ fails in five seconds.
828
+
829
+ Writing during the read phase is safe: `src/codec/Buffer.luau` keeps the incoming cursor and
830
+ the outgoing buffer in separate state, and nothing here calls game code. ]]
831
+ local function decline(channel: any, who: any?, id: number?, status: number)
832
+ local serving = queries
833
+
834
+ if serving and id and isServer and channel and channel.class == "query" then
835
+ serving.refuse(channel, who, id, status)
836
+ end
837
+ end
838
+
839
+ --[[
840
+ An answer, on the side that asked, held until dispatch.
841
+
842
+ Resuming the parked thread here would run game code inside the read phase, and the thread it
843
+ resumes is free to yield — which is the corruption the read-then-dispatch split exists to
844
+ prevent, arriving through the one path that did not go through a handler.
845
+ ]]
846
+ local function holdReply(channel: any, id: number, status: number, value: any?, bytes: number)
847
+ local count = filling.count + 1
848
+
849
+ if count > pendingCeiling then
850
+ full = true
851
+ report(channel, sender, "budget", ceilingReason, bytes)
852
+
853
+ --[[
854
+ A dropped *reply* is not like a dropped packet, because somebody is waiting for it.
855
+
856
+ Reaching here needs `callsInFlight` above `pendingPerBatch`, which is a
857
+ misconfiguration rather than a hostile peer — but what it produced before M3 phase 4's
858
+ audit was a five second stall ending in "no answer within 5s", said about an answer
859
+ that had arrived, decoded, and been thrown away one frame earlier. The caller is told
860
+ what happened instead, on the next tick, which is later in this same frame.
861
+ ]]
862
+ local waiting = queries
863
+
864
+ if waiting and channel.class == "query" then
865
+ waiting.abandon(channel, id, ceilingReplyReason)
866
+ end
867
+
868
+ return
869
+ end
870
+
871
+ filling.count = count
872
+ filling.channels[count] = channel
873
+ filling.senders[count] = sender
874
+ filling.values[count] = value
875
+ filling.subjects[count] = nil
876
+ filling.sizes[count] = bytes
877
+ filling.calls[count] = id
878
+ filling.statuses[count] = status
879
+ end
880
+
881
+ local sink: Batch.Sink = {
882
+ resolve = resolve,
883
+
884
+ --[[ The endpoint's side of a query, not the packet's. A server reads requests, a client
885
+ reads replies, and neither ever reads the other (`src/transport/Batch.luau`). ]]
886
+ answers = isServer,
887
+
888
+ admit = function(channel: any, bytes: number): (string?, Observer.Stage?)
889
+ --[[ Once the pending set is full the rest of the batch is refused here, before decode,
890
+ rather than decoded and then dropped. Refusing has to stay cheaper than accepting or
891
+ the limit becomes the amplifier. ]]
892
+ if full then
893
+ return ceilingReason, "budget"
894
+ end
895
+
896
+ --[[
897
+ A peer whose declarations disagree with this one's is refused **before decode**, and
898
+ that ordering is the point rather than an optimisation.
899
+
900
+ Their ids map to different channels, so their bytes would not fail to decode — they
901
+ would decode into whatever channel this peer has at that number, and be delivered to
902
+ its handler as a well-formed payload. A wrong payload arriving successfully is worse
903
+ than no payload, and it is the failure `PLAN-M3` D-7 is written against.
904
+
905
+ Checked per packet rather than per batch because the hello is *in* the first batch:
906
+ the packets behind it in that same batch are the first ones that must not land.
907
+ ]]
908
+ if agreement then
909
+ local disagreement = agreement.verdict(sender)
910
+
911
+ if disagreement then
912
+ return disagreement, "protocol"
913
+ end
914
+ end
915
+
916
+ --[[
917
+ Direction, on the wire rather than only in the views.
918
+
919
+ A packet arriving on a channel this peer is the *sender* of is one nobody can
920
+ legitimately send: `nw.state` and `nw.event` go server to client, and a client's
921
+ packet on that id is a confused build or a hostile one. It was decoded and queued
922
+ until M3 phase 9, and it could not be budgeted because those classes declare no rate —
923
+ which is the argument for forbidding `rate` on them, resting on a check that was not
924
+ there.
925
+
926
+ Refused here, before decode, so a flood of them costs an id read and a seek. That is
927
+ the same place and the same reason as the byte ceiling below.
928
+ ]]
929
+ if not (if isServer then channel.fromClient else channel.fromServer) then
930
+ return directionReason(channel.class), "direction"
931
+ end
932
+
933
+ --[[ The injected `admit` is the rate budget, which has one stage; naming it here rather
934
+ than defaulting keeps the two callers of `sink.refuse` symmetrical. ]]
935
+ return admit(channel, sender, bytes), "budget"
936
+ end,
937
+
938
+ --[[ A peer announcing its own declarations. Handled here rather than routed onward, because
939
+ what it decides is whether the rest of this batch is admitted at all. ]]
940
+ hello = function(hash: number, bytes: number)
941
+ if not agreement then
942
+ return
943
+ end
944
+
945
+ --[[ `greet` answers a reason only the first time a peer is found to be wrong, so this is
946
+ one report per mismatched peer rather than one per hello. Before M3 phase 9 the
947
+ mismatch was recorded and nothing was said until a data packet followed it. ]]
948
+ local disagreement = agreement.greet(sender, hash)
949
+
950
+ if disagreement then
951
+ report(nil, sender, "protocol", disagreement, bytes)
952
+ end
953
+ end,
954
+
955
+ --[[
956
+ A peer's per-namespace digest, beside its hello.
957
+
958
+ Decoded only when it changes something: the peer is refused and its reason does not yet
959
+ name a namespace. Every other digest — from a peer that agrees, from one already named,
960
+ from a peer that never said hello — is stepped over at the cost of one table read, which
961
+ is what bounds a flood of them (`PLAN-M5` D-7). The one that is decoded rewrites the
962
+ reason and is reported once more at `protocol`, so the console that printed two hashes
963
+ now prints the namespace.
964
+ ]]
965
+ --[[ Absent, not silent, on an endpoint with no agreement: `Batch` then reports the kind as one
966
+ this build does not read, which is what it is here, rather than stepping over it without
967
+ a word — the fuzzer's client rig has no agreement and found the silence. ]]
968
+ digest = if agreement == nil
969
+ then nil
970
+ else function(bytes: number)
971
+ if not agreement.wants(sender) then
972
+ return
973
+ end
974
+
975
+ local entries = Batch.readDigest()
976
+
977
+ if not entries then
978
+ report(nil, sender, "parse", MALFORMED_DIGEST, bytes)
979
+ return
980
+ end
981
+
982
+ local named = agreement.digest(sender, entries)
983
+
984
+ if named then
985
+ report(nil, sender, "protocol", named, bytes)
986
+ end
987
+ end,
988
+
989
+ --[[
990
+ A peer asking for a replicated channel in full.
991
+
992
+ Clearing what this endpoint believes that peer has is the whole answer: the next tick
993
+ finds no baseline and writes a change against nothing, which is every field. There is no
994
+ separate snapshot path to invoke because there is no separate snapshot.
995
+
996
+ Refused rather than assumed when the id names nothing, or names something that is not
997
+ replicated — a peer that can ask about an id it made up could otherwise make the server
998
+ walk its channel table on demand.
999
+ ]]
1000
+ resync = function(id: number, bytes: number)
1001
+ --[[
1002
+ **A peer whose declarations disagree does not get to make this endpoint work.**
1003
+
1004
+ Control packets are read before `sink.admit` because resolving id 0 would fail, and
1005
+ until M4 the verdict was consulted for `HELLO` and for data packets and not here — so
1006
+ a peer already refused at `protocol`, whose every data packet costs an id read and a
1007
+ seek, could still spend five bytes and buy a full state re-encode. `HELLO` stays
1008
+ exempt because it is how a disagreement is discovered and how it is cleared; nothing
1009
+ else is.
1010
+ ]]
1011
+ if agreement then
1012
+ local disagreement = agreement.verdict(sender)
1013
+
1014
+ if disagreement then
1015
+ report(nil, sender, "protocol", disagreement, bytes)
1016
+ return
1017
+ end
1018
+ end
1019
+
1020
+ local channel = resolve(id)
1021
+
1022
+ if not channel or channel.class ~= "replicate" then
1023
+ report(nil, sender, "replicate", NOT_REPLICATED, bytes)
1024
+ return
1025
+ end
1026
+
1027
+ local store = baselines
1028
+
1029
+ --[[ Reported, the way `change` reports it: an endpoint with no baselines cannot honour
1030
+ the ask, and returning without a word was the one silent exit on this path — found
1031
+ by the fuzzer the moment its corpus learned to write a resync (PLAN-M4-BUG phase 6). ]]
1032
+ if not store then
1033
+ report(channel, sender, "replicate", NO_BASELINES, bytes)
1034
+ return
1035
+ end
1036
+
1037
+ --[[
1038
+ **Coalesced, not refused**, and the difference is the whole design.
1039
+
1040
+ What a resync costs is not the clear — that is a table drop — it is the tick after it,
1041
+ which finds no baseline and writes every subject that peer can see. One five-byte
1042
+ packet a frame therefore bought a full state re-encode a frame, measured at 601 bytes
1043
+ a frame downstream for a hundred subjects against a steady state of zero, outside
1044
+ every budget netweave has: a replicated channel declares no `rate`, so `Budget.admit`
1045
+ has nothing to charge (M4 report).
1046
+
1047
+ Refusing the extra ones would be worse than it sounds. A client asks once, at the
1048
+ moment it gave up on the channel, and **nothing retries** — it has already cleared its
1049
+ own baselines, so a refused resync leaves it holding nothing while the server believes
1050
+ it holds everything, wrong for the rest of the session. A bound that can strand an
1051
+ honest client is not a bound, it is a second defect.
1052
+
1053
+ So the ask is never dropped: it is honoured now if the window is open, and remembered
1054
+ and honoured by `tick` if it is not. An attacker gets one full resend per window
1055
+ however fast they send; a client that lost a change gets its resend on the next frame,
1056
+ because the window starts open.
1057
+ ]]
1058
+ local seen = resyncs[sender]
1059
+
1060
+ if not seen then
1061
+ seen = {}
1062
+ resyncs[sender] = seen
1063
+ end
1064
+
1065
+ local honoured = seen[channel]
1066
+
1067
+ if honoured and ticks - honoured < resyncWindow() then
1068
+ seen[channel] = honoured
1069
+ owed[channel] = owed[channel] or {}
1070
+ owed[channel][sender] = true
1071
+ report(channel, sender, "replicate", RESYNC_DEFERRED, bytes)
1072
+ return
1073
+ end
1074
+
1075
+ seen[channel] = ticks
1076
+ store.desync(sender, channel)
1077
+ end,
1078
+
1079
+ deliver = function(channel: any, value: any, bytes: number, id: number?)
1080
+ --[[
1081
+ A packet with no handler is queued and does **not** count against `pendingPerBatch`,
1082
+ which an external review read as the ceiling being bypassed. Examined in M3 phase 9
1083
+ and left alone, because the two limits answer different questions and moving this one
1084
+ would break the thing the queue is for.
1085
+
1086
+ What the queue holds is bounded by `queueCapacity`, per channel, and it drops the
1087
+ *oldest* — which is the right policy for its case, a `:listen` that attached a frame
1088
+ late. The batch ceiling drops the newest, so applying it here would lose exactly the
1089
+ traffic the queue exists to keep.
1090
+
1091
+ What is left is decode *work*, and on an inbound class that is what `rate` licenses:
1092
+ the packets would have been decoded anyway had a handler been attached. The genuinely
1093
+ unbounded case the finding pointed at was an outbound-class id, which declares no rate
1094
+ and is now refused above, before decode.
1095
+ ]]
1096
+ if not channel.handler then
1097
+ --[[
1098
+ A query nobody is answering is refused, not queued.
1099
+
1100
+ The queue exists so a handler attached one frame late does not lose the traffic
1101
+ that arrived first, and for a fire-and-forget class late is better than never. A
1102
+ request is the opposite: the caller is holding a thread against a deadline, so
1103
+ keeping the request until a handler appears converts an immediate, legible
1104
+ "nothing is listening" into a timeout that says nothing at all.
1105
+ ]]
1106
+ if isServer and id and channel.class == "query" then
1107
+ decline(channel, sender, id, Batch.UNHANDLED)
1108
+ return
1109
+ end
1110
+
1111
+ enqueue(channel, sender, value, bytes)
1112
+ return
1113
+ end
1114
+
1115
+ if channel.class == "intent" then
1116
+ local byPlayer = coalescedValue[channel]
1117
+
1118
+ if not byPlayer then
1119
+ byPlayer = {}
1120
+ coalescedValue[channel] = byPlayer
1121
+ coalescedBytes[channel] = {}
1122
+ end
1123
+
1124
+ --[[ Latest wins. The superseded value is not reported: it was not refused, it was
1125
+ replaced, and reporting it would make an intent channel look like it is
1126
+ failing. ]]
1127
+ byPlayer[sender] = value
1128
+ coalescedBytes[channel][sender] = bytes
1129
+ return
1130
+ end
1131
+
1132
+ --[[
1133
+ The pending set is bounded, and the bound is the price of reading a batch to completion
1134
+ before dispatching any of it.
1135
+
1136
+ That order is not negotiable — a yielding handler plus a global decode cursor attributes
1137
+ one player's bytes to another (`PLAN-M2` phase 3) — but it means every decoded value in
1138
+ a batch is live at once. The benchmark measured what that costs: `ArrayHeavy` decode
1139
+ allocation went 1184.8 B to 9309.2 B on the same payload, because two hundred decoded
1140
+ values were alive where one had been. The batch's size is chosen by an untrusted client,
1141
+ which makes it a resource limit rather than a performance note (`PLAN-M3` D-6).
1142
+
1143
+ Past the bound the batch stops. Dispatching early to make room is the one thing that
1144
+ cannot be done here, because it is the order the bound exists to protect.
1145
+ ]]
1146
+ local count = filling.count + 1
1147
+
1148
+ if count > pendingCeiling then
1149
+ full = true
1150
+ report(channel, sender, "budget", ceilingReason, bytes)
1151
+ decline(channel, sender, id, Batch.REFUSED)
1152
+ return
1153
+ end
1154
+
1155
+ filling.count = count
1156
+ filling.channels[count] = channel
1157
+ filling.senders[count] = sender
1158
+ filling.values[count] = value
1159
+ filling.subjects[count] = nil
1160
+ filling.sizes[count] = bytes
1161
+ filling.calls[count] = id or 0
1162
+ filling.statuses[count] = -1
1163
+ end,
1164
+
1165
+ --[[
1166
+ A replicated subject's change, folded into what this endpoint has.
1167
+
1168
+ The fold happens **here, during the read**, because the bytes are here and nowhere else;
1169
+ the handler runs in the dispatch phase like every other class, so a handler that yields
1170
+ cannot let the next packet decode against a half-applied value. That is D-6's
1171
+ read-then-dispatch applied to a payload that mutates state rather than replacing it.
1172
+ ]]
1173
+ change = function(channel: any, subject: any, bytes: number)
1174
+ local store = baselines
1175
+
1176
+ if not store then
1177
+ report(channel, sender, "replicate", NO_BASELINES, bytes)
1178
+ return
1179
+ end
1180
+
1181
+ local base = store.of(sender, channel, subject)
1182
+ local value, failure = channel.delta.apply(base)
1183
+
1184
+ --[[ A change that could not be read is not a removal, and treating it as one would drop
1185
+ a subject because a peer sent a short packet. The baseline is left exactly as it was
1186
+ and the channel is given up on: this endpoint cannot know how much of that change it
1187
+ took before it ran out, so every change after it is against a value that may or may
1188
+ not be what the sender thinks. ]]
1189
+ if failure then
1190
+ report(channel, sender, "parse", failure, bytes)
1191
+ desync(channel)
1192
+ return
1193
+ end
1194
+
1195
+ if value == nil then
1196
+ --[[ Gone. Dropped here rather than left for the handler, so that a handler which
1197
+ raises cannot leave this endpoint believing it still has the subject. ]]
1198
+ store.drop(sender, channel, subject)
1199
+ else
1200
+ --[[ Before it is recorded and before the handler sees it, because those are the same
1201
+ table. See `harden`. ]]
1202
+ harden(value)
1203
+ store.keep(sender, channel, subject, value)
1204
+ end
1205
+
1206
+ --[[
1207
+ Nobody is listening yet, and this class does not use the queue the others do: the
1208
+ baseline *is* the queue (PLAN-M4-BUG D-3), and `drain` walks it when `:listen`
1209
+ attaches. Queued here instead, the entry reached `call` with a nil handler — reported
1210
+ as the game's own handler raising, with a traceback — and was never delivered,
1211
+ because the baseline already said this client had the subject and the server sends
1212
+ a snapshot once. A static subject in the first batch was invisible for the session,
1213
+ on the join path, in exactly the module order the queue exists for (M4-1, 중대).
1214
+ ]]
1215
+ if not channel.handler then
1216
+ return
1217
+ end
1218
+
1219
+ local count = filling.count + 1
1220
+
1221
+ if count > pendingCeiling then
1222
+ full = true
1223
+ report(channel, sender, "budget", ceilingReason, bytes)
1224
+
1225
+ --[[ The change was applied and is being dropped before the handler sees it, which
1226
+ leaves the game's own mirror behind this endpoint's baseline. Everything on this
1227
+ channel has to be asked for again. ]]
1228
+ desync(channel)
1229
+ return
1230
+ end
1231
+
1232
+ filling.count = count
1233
+ filling.channels[count] = channel
1234
+ filling.senders[count] = sender
1235
+ filling.values[count] = value
1236
+ filling.subjects[count] = subject
1237
+ filling.sizes[count] = bytes
1238
+ filling.calls[count] = 0
1239
+ filling.statuses[count] = -1
1240
+ end,
1241
+
1242
+ reply = holdReply,
1243
+
1244
+ refuse = function(channel: any?, stage: Observer.Stage, reason: string, bytes: number, id: number?)
1245
+ report(channel, sender, stage, reason, bytes)
1246
+
1247
+ --[[ Any refusal of a replicated packet is a change this endpoint will never see, and
1248
+ every change after it is relative to one it does not have. The stage does not
1249
+ matter — parse, budget or protocol, the consequence is the same. ]]
1250
+ if channel and channel.class == "replicate" then
1251
+ desync(channel)
1252
+ end
1253
+
1254
+ --[[
1255
+ A refused query is answered rather than left hanging, in both directions.
1256
+
1257
+ On the server the caller is told its request was thrown away; on the client a reply
1258
+ that would not decode resolves the parked thread as a failure instead of costing it
1259
+ the whole timeout. The rule is the same from either end: a call that cannot be
1260
+ answered gets an answer saying so.
1261
+ ]]
1262
+ if not id or not channel or channel.class ~= "query" then
1263
+ return
1264
+ end
1265
+
1266
+ if isServer then
1267
+ decline(channel, sender, id, Batch.REFUSED)
1268
+ else
1269
+ holdReply(channel, id, Batch.FAILED, nil, bytes)
1270
+ end
1271
+ end,
1272
+ }
1273
+
1274
+ return {
1275
+ receive = function(packed: buffer, instances: { unknown }?, from: any?)
1276
+ local list = claim()
1277
+
1278
+ --[[ Both of these belong to the read phase only. Restored rather than cleared, so a
1279
+ batch that arrived inside another batch's dispatch leaves the outer one as it
1280
+ found it. ]]
1281
+ local outerSender = sender
1282
+ local outerFilling = filling
1283
+ local outerFull = full
1284
+
1285
+ sender = from
1286
+ filling = list
1287
+ full = false
1288
+ refreshCeiling()
1289
+
1290
+ --[[ The same reason as `dispatch`: the read phase calls no game code and should not be
1291
+ able to raise, and "should not" is what the sidecar was. Restoring the three
1292
+ upvalues on both paths is what keeps a raise from costing every batch after it. ]]
1293
+ local ok, failure = pcall(read, packed, instances, sink)
1294
+
1295
+ sender = outerSender
1296
+ filling = outerFilling
1297
+ full = outerFull
1298
+
1299
+ if not ok then
1300
+ report(nil, from, "parse", `the read phase raised: {tostring(failure)}`, buffer.len(packed))
1301
+ end
1302
+
1303
+ dispatch(list)
1304
+ end,
1305
+
1306
+ --[[ A handler has just been attached. Whatever arrived before it did is delivered now, in
1307
+ arrival order. ]]
1308
+ drain = function(channel: any)
1309
+ if not channel.handler then
1310
+ return
1311
+ end
1312
+
1313
+ --[[
1314
+ A replicated channel keeps nothing in a queue: every subject that arrived before the
1315
+ handler is in the baseline, and delivering the baseline is delivering the queue —
1316
+ one copy, not two. The closure is one allocation per `:listen`, not per packet. A
1317
+ handler attached, detached and attached again is handed everything a second time,
1318
+ which is the same thing `:listen` on any class does with its queue.
1319
+ ]]
1320
+ if channel.class == "replicate" then
1321
+ local store = baselines
1322
+
1323
+ if isServer or not store then
1324
+ return
1325
+ end
1326
+
1327
+ local list = claim()
1328
+
1329
+ store.each(nil, channel, function(subject: any, value: any)
1330
+ local count = list.count + 1
1331
+
1332
+ list.count = count
1333
+ list.channels[count] = channel
1334
+ list.senders[count] = nil
1335
+ list.values[count] = value
1336
+ list.subjects[count] = subject
1337
+ list.sizes[count] = 0
1338
+ list.calls[count] = 0
1339
+ list.statuses[count] = -1
1340
+ end)
1341
+
1342
+ dispatch(list)
1343
+ return
1344
+ end
1345
+
1346
+ local queue = queues[channel]
1347
+
1348
+ if not queue then
1349
+ return
1350
+ end
1351
+
1352
+ local list = claim()
1353
+
1354
+ while queue.count > 0 do
1355
+ local slot = queue.read
1356
+ local count = list.count + 1
1357
+
1358
+ list.count = count
1359
+ list.channels[count] = channel
1360
+ list.senders[count] = queue.senders[slot + 1]
1361
+ list.values[count] = queue.values[slot + 1]
1362
+ list.sizes[count] = 0
1363
+ --[[ Never a query: a request with no handler is refused rather than queued, so
1364
+ nothing in a queue was ever waiting on an answer. ]]
1365
+ list.calls[count] = 0
1366
+ list.statuses[count] = -1
1367
+
1368
+ queue.values[slot + 1] = nil
1369
+ queue.senders[slot + 1] = nil
1370
+ queue.read = (slot + 1) % queue.capacity
1371
+ queue.count -= 1
1372
+ end
1373
+
1374
+ dispatch(list)
1375
+ end,
1376
+
1377
+ --[[ Once a frame. Every intent that arrived since the last one is delivered, at most one
1378
+ per player per channel. ]]
1379
+ tick = function()
1380
+ ticks += 1
1381
+
1382
+ --[[ The resyncs that arrived inside a window, honoured now that one has passed. Walked
1383
+ rather than scheduled: the table holds only peers who asked twice in half a second,
1384
+ which in a healthy server is nobody and the loop is one `next` that finds nothing. ]]
1385
+ local store = baselines
1386
+
1387
+ if store then
1388
+ for channel, senders in owed do
1389
+ for who in senders do
1390
+ local seen = resyncs[who]
1391
+ local honoured = seen and seen[channel]
1392
+
1393
+ if not honoured or ticks - honoured >= resyncWindow() then
1394
+ senders[who] = nil
1395
+
1396
+ if seen then
1397
+ seen[channel] = ticks
1398
+ end
1399
+
1400
+ store.desync(who, channel)
1401
+ end
1402
+ end
1403
+ end
1404
+ end
1405
+
1406
+ local list = claim()
1407
+
1408
+ for channel, byPlayer in coalescedValue do
1409
+ local bytes = coalescedBytes[channel]
1410
+
1411
+ for who, value in byPlayer do
1412
+ byPlayer[who] = nil
1413
+
1414
+ local count = list.count + 1
1415
+ list.count = count
1416
+ list.channels[count] = channel
1417
+ list.senders[count] = who
1418
+ list.values[count] = value
1419
+ list.sizes[count] = bytes[who] or 0
1420
+ --[[ Intents only, and an intent is not a query. ]]
1421
+ list.calls[count] = 0
1422
+ list.statuses[count] = -1
1423
+
1424
+ bytes[who] = nil
1425
+ end
1426
+ end
1427
+
1428
+ dispatch(list)
1429
+ end,
1430
+
1431
+ --[[ A player who left. Their pending intent is input nobody is waiting for, and their
1432
+ context record would otherwise outlive them. ]]
1433
+ forget = function(who: any)
1434
+ --[[ A departed peer's resync bookkeeping, which would otherwise hold their record for
1435
+ the life of the server — the same leak `PLAN-M3` D-6 is about, one table over. ]]
1436
+ resyncs[who] = nil
1437
+
1438
+ for _, senders in owed do
1439
+ senders[who] = nil
1440
+ end
1441
+
1442
+ for _, byPlayer in coalescedValue do
1443
+ byPlayer[who] = nil
1444
+ end
1445
+
1446
+ for _, bytes in coalescedBytes do
1447
+ bytes[who] = nil
1448
+ end
1449
+
1450
+ --[[
1451
+ And whatever they left in a queue, which an external review found still there (M3
1452
+ phase 9).
1453
+
1454
+ A queue holds packets for a channel nobody is listening to yet. Attaching the
1455
+ `:listen` afterwards used to dispatch them all, including the ones sent by a player
1456
+ who has since left — so a command ran for somebody who is gone, with
1457
+ `ctx.character == nil`, and `Context.acquire` built a fresh record for the departed
1458
+ `Player` to run it against, which nothing would ever forget again.
1459
+
1460
+ Compacted in place rather than rebuilt: the ring is walked in arrival order and the
1461
+ survivors are written back from `read`, so the entry being written is always at or
1462
+ behind the entry being read and the order the queue exists to preserve is kept.
1463
+ ]]
1464
+ for channel, queue in queues do
1465
+ if queue.count == 0 then
1466
+ continue
1467
+ end
1468
+
1469
+ local kept = 0
1470
+
1471
+ for index = 0, queue.count - 1 do
1472
+ local slot = (queue.read + index) % queue.capacity
1473
+ local from = queue.senders[slot + 1]
1474
+
1475
+ if from ~= who then
1476
+ local target = (queue.read + kept) % queue.capacity
1477
+ queue.values[target + 1] = queue.values[slot + 1]
1478
+ queue.senders[target + 1] = from
1479
+ kept += 1
1480
+ end
1481
+ end
1482
+
1483
+ --[[ The tail the survivors no longer reach. Nil'd rather than left, because a
1484
+ queued value holds every table and Instance the packet decoded into. ]]
1485
+ for index = kept, queue.count - 1 do
1486
+ local slot = (queue.read + index) % queue.capacity
1487
+ queue.values[slot + 1] = nil
1488
+ queue.senders[slot + 1] = nil
1489
+ end
1490
+
1491
+ local dropped = queue.count - kept
1492
+ queue.count = kept
1493
+
1494
+ if dropped > 0 then
1495
+ report(channel, who, "queue", `dropped {dropped} queued packets; the sender left`, 0)
1496
+ end
1497
+ end
1498
+
1499
+ Context.forget(who)
1500
+ end,
1501
+
1502
+ pooled = function(): number
1503
+ return #free
1504
+ end,
1505
+ }
1506
+ end
1507
+
1508
+ return Inbound